Skip to content

Instantly share code, notes, and snippets.

@nandotorres
Created December 12, 2016 17:54
Show Gist options
  • Save nandotorres/0ac32aaecd268d627dda61281615db22 to your computer and use it in GitHub Desktop.
Save nandotorres/0ac32aaecd268d627dda61281615db22 to your computer and use it in GitHub Desktop.
Shell script to run packer command line tool and build an AMI with Chef cookbook
#!/bin/bash
rm -rf vendor/*
# Group all recipes and cookbooks for provisioning
chef exec berks vendor vendor/cookbooks
chef exec berks install
##########################################################
# Deregister any existing image for this commit revision
# Note: $CI_BUILD_REF is authomatically exported by GitLab
# with the SHA1 for the commit revision number
##########################################################
# Query AWS if exists an AMI with TAG SHA1 = $CI_BUILD_REF
EXISTING_AMI=$(aws ec2 describe-images \
--filter="Name=tag-key,Values=SHA1,Name=tag-value,Values=$CI_BUILD_REF")
# Extract the AMI ID
AMI_ID=$(echo $EXISTING_AMI |jq ".Images[] .ImageId" |sed -e 's/^"//' -e 's/"$//')
if [[ ! -z "$AMI_ID" ]]
then
# If exists an AMI, extracts the ID of the corresponding Snapshot
SNAPSHOT_ID=$(echo $EXISTING_AMI |jq ".Images[0] .BlockDeviceMappings[0] .Ebs .SnapshotId" |sed -e 's/^"//' -e 's/"$//')
# Deregister the AMI
echo "Found previous AMI for the revision $CI_BUILD_REF ($AMI_ID)"
echo "Removing image $AMI_ID"
echo "Runing aws ec2 deregister-image --image-id $AMI_ID"
aws ec2 deregister-image --image-id $AMI_ID
# Delete the snapshot
echo "Removing snapshot $SNAPSHOT_ID"
echo "Running aws ec2 delete-snapshot --snapshot-id $SNAPSHOT_ID"
aws ec2 delete-snapshot --snapshot-id $SNAPSHOT_ID
fi
# Create a new AMI for this commit revision
AMI_NAME_SUFIX=`date "+%Y%m%d%H%M"`
packer build \
-var "ami_name=TechTalk-TODO-App-$AMI_NAME_SUFIX" \
-var "account_id=$AWS_ACCOUNT_ID" \
-var "aws_access_key_id=$AWS_ACCESS_KEY_ID" \
-var "aws_secret_key=$AWS_SECRET_ACCESS_KEY" \
-var "aws_region=us-east-1" \
-var "source_ami=ami-40d28157" \
-var "aim_ebs_optimized=false" \
-var "instance_type=t2.micro" \
-var "associate_public_ip_address=true" \
-var "vpc_id=vpc-14b55572" \
-var "subnet_id=subnet-a71ad09b" \
-var "security_group_id=sg-20fc265d" \
-var "ssh_username=ubuntu" \
-var "ci_build_ref=$CI_BUILD_REF" \
-only=amazon-ebs packer.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment