Code Sample
#!/bin/bash
InstanceID=("i-xxxxxxxxx" "i-xxxxxxxxxxxxxxxxxxx" "i-xxxxxxxxxxxx65")
ImageName="create-ami"
CurrentTime=`date +%Y%m%d`
ImageVersion=${2:-v1.1.1}
ImageDescription="create-ami-by-script"
num=1
for value in "${InstanceID[@]}";
do
aws ec2 create-image \
--instance-id $InstanceID \
--name $ImageName-$CurrentTime-$ImageVersion-$value-$num \
--description "$ImageDescription" \
--tag-specifications 'ResourceType=image,Tags=[{Key=Name,Value=create-ami}]' \
'ResourceType=snapshot,Tags=[{Key=Name,Value=create-ami}]' \
--region ap-northeast-2 --debug --profile awsprofile
((num+=1))
echo $value
done
To get each ec2 instance ID with aws cli for comfort,
below is the sample code to implement.
$ aws ec2 describe-instances \
--profile awsprofile \
--query 'Reservations[*].Instances[*].{Instance:InstanceId,Subnet:SubnetId}' \
--output text --region ap-northeast-2
adding below option will prevent inaccurate order of ami creation since the reboot will take some time to operate for each target server.
--no-reboot
reference: https://docs.aws.amazon.com/cli/latest/reference/ec2/create-image.html