Creating AMIs based on Tags

26 / Mar / 2015 by Aakash Garg 0 comments

You must be wondering how to make AMI of the Web Server(EC2 instance) in which you have made some changes. In this blog I will walk you through a script that will ease up your work and make AMI of instances with user specified tags.

Consider a use-case where user has made some changes to the Web Server and he wants to take AMI according to the tags specified to that particular server. Now he wants to create AMI whose tags can be defined according to the server, so that he recognize that particular AMI easily. Additionally,  user can specify the Launch Time of the server with the time on which AMI is being created.

 

[js]
_key=Environment
_value=Production
echo "Your Specified Key = $_key and Value = $_value"
[/js]

User has to specify the Tags of the instances for creating the image

[js]
instanceIds=($(aws ec2 describe-instances –query ‘Reservations[*].Instances[*].[InstanceId]’ –filter "Name=instance-state-name,Values=running" –output text))
[/js]

Now get the instanceIds of the running instances in an array with this command.

[js]
instanceKeys=($(aws ec2 describe-instances –query ‘Reservations[*].Instances[*].Tags[*].Key’ –filter "Name=instance-id,Values=$instanceId" –output text ))
[/js]

Put this command in loop of every instanceId to get the Keys of that running instance

[js]
if [ ${instanceKey[$Key_count]} == $_key ];
then
instanceValues=($(aws ec2 describe-instances –query ‘Reservations[*].Instances[*].Tags[*].Value’ –filter "Name=instance-id,Values=$instanceId" –output text))
[/js]

This is command is used in loop for every Key of the instance and it will verify the key specified above
If it is correct then only it will find the Value otherwise it will be out of the loop.

[js]
instanceTime=$(aws ec2 describe-instances –instance-ids $instanceId –query ‘Reservations[*].Instances[*].LaunchTime’ –output text)
### Command will retrieve the Launch Time of that running instance ###

Time=$(date -d $instanceTime +%x-%H-%M-%S)
### Requirement of change in format of time is required ###
### because in the Name of AMI no ‘-‘ can be added. It will throw error ###

imageId=($(aws ec2 create-image –instance-id $instanceId –name "$instanceName $instanceId $Time" –output text))
### AMI will be created ###
### Id of the created AMI will be stored ###

aws ec2 create-tags –resources $imageId –tags Key=Name,Value="$instanceValues`date`"
### Tags can be given here to the created AMI with the time when the AMI is been created ###
[/js]

Use these statements after user specified Key and Value has been verfied with the running instanceIds.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *