AWS学习笔记(四)--CLI创建EC2时执行脚本

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

猜你喜欢

转载自billben.iteye.com/blog/2331809