1. 程式人生 > >AWS學習筆記(四)--CLI創建EC2時執行腳本

AWS學習筆記(四)--CLI創建EC2時執行腳本

scl type cycle 實例 doc settings shell腳本 system input

When you launch an instance in Amazon EC2, you have the option of passing user data to the instance that can be used to perform common automated configuration tasks and even run scripts after the instance starts. You can pass two types of user data to Amazon EC2: shell scripts and cloud-init directives.

If you are interested in more complex automation scenarios, consider using AWS CloudFormation and AWS OpsWorks.(中國不支持AWS OpsWorks)

Linux Shell
Scripts entered as user data are executed as the root user, so do not use the sudo command in the script. Remember that any files you create will be owned by root; if you need non-root users to have file access, you should modify the permissions accordingly in the script.

By default, user data and cloud-init directives only run during the first boot cycle when you launch an instance.If you stop an instance, modify the user data, and start the instance, the new user data is not executed automatically.

日誌文件/var/log/cloud-init.log

下面的例子使用user-data屬性,Launch Instance時執行Shell腳本配置DNS,然後給Instance增加了Tag:

run-instance.sh

#!/bin/bash  

run_instance() {  
  # 根據配置文件創建EC2實例,創建時執行shell腳本,返回instance id  
  instance_id=$(aws ec2 run-instances --cli-input-json file://instance.json --user-data file://add_dns.sh --query ‘Instances[0].[InstanceId]‘ | grep -o -E "i-\w{17}")  
  echo "InstanceId: $instance_id"  

  # 為EC2添加tag  
  echo "Add tags: Name:$1, Category:$2"  
  aws ec2 create-tags --resources $instance_id --tags Key=Name,Value="$1" Key=Category,Value="$2"  
}  

run_instance "test" "test"

EC2配置文件instance.json

{  
    "DryRun": false,   
    "ImageId": "ami-4ec31723",   
    "KeyName": "Prod Key Pair",   
    "SecurityGroupIds": [  
        "sg-06242b63"  
    ],  
    "InstanceType": "m3.large",   
    "Placement": {  
        "AvailabilityZone": "cn-north-1b",   
        "Tenancy": "default"  
    },   
    "Monitoring": {  
        "Enabled": false  
    },   
    "SubnetId": "subnet-6166bc16",   
    "DisableApiTermination": true,   
    "InstanceInitiatedShutdownBehavior": "stop",   
    "PrivateIpAddress": "10.184.140.11",   
    "EbsOptimized": false  
}

配置DNS Shell腳本add-dns.sh

#!/bin/bash  

IFCFG="/etc/sysconfig/network-scripts/ifcfg-eth0"  

# 將第六行替換為PEERDNS="no"  
sed -i ‘6c PEERDNS="no"‘ $IFCFG  
# 增加DNS  
sed -i ‘$a DNS1="10.184.141.11"‘ $IFCFG  
sed -i ‘$a DNS1="10.184.141.12"‘ $IFCFG  

systemctl restart network

Windows Script
由Amazon Windows AMI創建EC2 Instance時會執行userdata;如要自定義AMI,在創建AMI前要先修改EC2Launch service或EC2Config service配置(從Windows Server 2016開始使用EC2Launch,之前使用EC2Config),才會執行userdata。

EC2Launch位於C:\ProgramData\Amazon\EC2-Windows\Launch目錄下。有兩種方式啟用:

  • 在PowerShell下運行C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeInstance -Schedule
  • 運行C:\ProgramData\Amazon\EC2-Windows\Launch\Settings目錄下的Ec2LaunchSettings,勾選要初始化的選項,選擇Shutdown with Sysprep(註意這會關機的)
    技術分享圖片
    Ec2ConfigService位於C:\Program Files\Amazon\Ec2ConfigService目錄下,可以從開始菜單運行EC2ConfigService Settings
    技術分享圖片
    也有兩種方式啟用userdata:
  • 選中General選項卡中的User Data
  • 選擇Image選項卡中的Shutdown with Sysprep(這會忽略General選項卡中的User Data是否選中)
    技術分享圖片

Windows支持兩種Script,一種是cmd,一種是PowerShell,要分別用<script></script>和<powershell></powershell>封裝。如:
<script>dir > c:\test.log</script>

powershell例一:修改DNS

<powershell>Set-DnsClientServerAddress -InterfaceAlias "Ethernet 2" -ServerAddresses ("10.184.13.14","10.184.13.15")</powershell>

powershell例二:修改DNS服務器域名對應的IP地址

<powershell>
$OldObj = Get-DnsServerResourceRecord -Name "prod-db" -ZoneName "iata.com" -RRType "A"
$NewObj = $OldObj.Clone()
$NewObj.RecordData.IPv4address=[System.Net.IPAddress]::parse("10.184.12.73")
Set-DnsServerResourceRecord -NewInputObject $NewObj -OldInputObject $OldObj -ZoneName "asd.com" -PassThru
</powershell>

AWS CLI示例:

aws ec2 run-instances --image-id ami-2fb56342 --instance-type m3.large  --user-data file://user_data.txt --subnet-id subnet-fbc42a3 --security-group-ids sg-fbc42a3 --key-name jason-test

Running Commands on Your Linux Instance at Launch
Executing Scripts on Windows Instance at Launch
AWS EC2 userdata on Windows
Configuring a Windows Instance Using EC2Launch
Configuring a Windows Instance Using the EC2Config Service
Managing Windows Instance Configuration
PowerShell - About Execution Policies
Domain Name System (DNS) Server Cmdlets
cloud-init

AWS學習筆記(四)--CLI創建EC2時執行腳本