Skip to content

Instantly share code, notes, and snippets.

@Shubhamnegi
Last active December 22, 2021 09:17
Show Gist options
  • Save Shubhamnegi/8a2c9b3224cf1f316198d9cfc2bf7efd to your computer and use it in GitHub Desktop.
Save Shubhamnegi/8a2c9b3224cf1f316198d9cfc2bf7efd to your computer and use it in GitHub Desktop.
To create AMI and update launch template
#!/bin/bash
AWS="aws"
INSTANCE_NAME=""
EPOCH=$(date +%s)
AMI_ID=""
# To show usage of the script
print_usage() {
printf "Usage: create-ami.sh -i instance-id -r region -l launch-template-id"
}
# To get caller identity
print_caller_identity() {
echo "Getting caller identity"
command="$AWS sts get-caller-identity"
echo $command
eval $command
}
# To get instance details
print_instance_info() {
command="$AWS ec2 describe-instances --instance-ids $1"
echo "$command"
i=$(eval $command)
name=$(echo $i | jq -r '.Reservations[0].Instances[0] | (.Tags[]?|select(.Key=="Name")|.Value)')
INSTANCE_NAME=$name
echo "Instance name: "$INSTANCE_NAME
}
# To create new ami
create_ami() {
ami_name="$INSTANCE_NAME-$EPOCH"
command="$AWS ec2 create-image --description 'AMI created using jenkins' --instance-id $1 --name $ami_name --no-reboot --tag-specifications 'ResourceType=image,Tags=[{Key=Name,Value=$INSTANCE_NAME}]' 'ResourceType=snapshot,Tags=[{Key=Name,Value=$INSTANCE_NAME}]'"
echo $command
result=$(eval $command)
# result="{ \"ImageId\": \"ami-01d5c8f2c7fc2de94\" }"
# echo $result
result=$(echo $result | jq -r '.ImageId')
echo "AMI: "$result
AMI_ID=$result
}
# To update launch template
update_launch_template() {
command="$AWS ec2 describe-launch-templates --launch-template-ids $1"
echo "$command"
current_version=$(eval $command)
# echo $current_version
current_version=$(echo $current_version | jq -r ".LaunchTemplates[0].LatestVersionNumber")
echo "current lt version: "$current_version
command="$AWS ec2 create-launch-template-version --launch-template-id $1 --source-version $current_version --launch-template-data '{\"ImageId\": \"$AMI_ID\"}'"
echo $command
result=$(eval $command)
# echo $result
result=$(echo $result | jq -r ".LaunchTemplateVersion.VersionNumber")
echo "new lt version: "$result
command="$AWS ec2 modify-launch-template --launch-template-id $1 --default-version $result"
echo $command
eval $command
}
while getopts "i:r:l:" arg; do
case $arg in
i) INSTANCE=$OPTARG;;
r) REGION=$OPTARG;;
l) LAUNCH_TEMPLATE=$OPTARG;;
*) print_usage
exit 1 ;;
esac
done
echo "Will be creating ami for $INSTANCE in Region $REGION and update L.T: $LAUNCH_TEMPLATE"
AWS="$AWS --region $REGION"
print_caller_identity
print_instance_info $INSTANCE
create_ami $INSTANCE
update_launch_template $LAUNCH_TEMPLATE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment