Skip to content

Instantly share code, notes, and snippets.

@electrawn
Forked from danrigsby/packer-ami-id
Last active January 5, 2023 23:14
Show Gist options
  • Save electrawn/be0c239e46517a859e31bf0a2496235e to your computer and use it in GitHub Desktop.
Save electrawn/be0c239e46517a859e31bf0a2496235e to your computer and use it in GitHub Desktop.
Get AMI ID from a packer build
#!/bin/bash
#
#Machine Readable Technique to get AMI_ID, tee forwards stdout to stderr.
#
#AMI_ID=`packer build -machine-readable packer.json | tee >(cat 1>&2) | awk -F, '$0 ~/artifact,0,id/ {print $6}'`
#
#Human readable format sends stdout to stderr, awk catches the AMI_ID. This allows output to end up in a jenkins/bamboo output.
# The output of the AWS builder ends with region: ami-id, So rather than have awk read the whole line... we target column 2.
#
AMI_ID=`packer build packer.json | tee >(cat 1>&2) | awk 'match($2, /ami-.*/) { print substr($2, RSTART, RLENGTH) }'`
echo "AMI is ${AMI_ID}";
#
# And now a useful example:
# If AMI_ID not empty, create a new AS version of an existing launch configuration template my-LC. Autoscale group my-AS is set to use latest version
# and we bounce the servers in this AS group without cooldown because "dev"
# printf template used to generate json on the commandline, avoids use of jq or some real unreadable quoting magic.
#
if [ ! -z "$AMI_ID" ]; then
template='{"ImageId":"%s"}'
aws --profile default ec2 create-launch-template-version --launch-template-name my-LC --version-description WebVersion2 --source-version 1 --launch-template-data $(printf "$template" "$AMI_ID")
aws --profile default autoscaling set-desired-capacity --auto-scaling-group-name my-AS --desired-capacity 0 --no-honor-cooldown
sleep 60
aws --profile default autoscaling set-desired-capacity --auto-scaling-group-name my-AS --desired-capacity 2 --no-honor-cooldown
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment