Using Cloud-Init to Auto-Deploy New EC2 Instances

So you have a machine role that you’re auto-scaling in AWS and you want new EC2 instances to initialize automatically after their creation? Cloud-init is here to help; it let’s you manage and configure many aspects of the machine (like installing the latest updates or missing packages). It also let’s you run any commands you want. So what else would you need to get your own bits installed? That’s right, nothing!

#cloud-config
# Update existing packages
apt_update: true

# Install more packages
packages:
- tomcat7
- jq

# Download the latest bits from S3, extract and setup.
runcmd:
- aws s3api get-object --bucket my-bits --key latest/mybits.tar.gz mybits.tar.gz
- mkdir mybits
- tar xvzf mybits.tar.gz -C mybits
- bash mybits/my-own-setup-script.sh

In this case, the script my-own-setup-script.sh is run at the end of initialization and can make sure to deploy everything as required. All you need to do, is push a package with the latest bits onto S3 and all new instances for this role will automatically get the latest bits installed when they are created. Of course you’ll need to make sure that the machine’s IAM role is allowed access to the corresponding S3 bucket and file.