Amazon-Web-Services

 

Userdata scripts are a powerful way to customize an Amazon Web Service AMI or instance.  It’s goal is allow the administrator to tweak a generalized AMI into something very specific.  On instance creation (only, take note that the userdata script will only run once), a script can be entered into the EC2 web console to be run as root.  Using this process, one can automatically update an instance, add a web server, copy down some files from an S3 bucket, and start the web daemon for example.  The goal here is a good example of Amazon’s entire goal for the product, making compute resources dynamic and disposable.

The easiest way to complete this process is to write a bash script.  Once the script has been tested and confirmed working in a real live instance, it’s time to add it into the usedata section.  For this example, we’re simply going to sync some files from S3 into a temporary directory.

If the instance is running Amazon linux, then things are easy as it comes preinstalled with the AWS CLI tools.  If you’re using another linux distribution, make sure those tools are installed.  Make sure to use the full path to any commands.  The code is quite simple:

#!/bin/bash
/bin/mkdir /home/ec2-user/test
/usr/bin/aws s3 sync s3://yourFiles/ /home/ec2-user/test

 


It’s important to note that in the last six or so months ago (as of this writing), Amazon changed the look and feel of the EC2 console.  The userdata field used to be more prominent, but is somewhat buried now.  If you’re unable to locate it, this is where the userdata field lives now:

userdata

 

And that’s all there is to it.  Once your code is plugged into the userdata field in the console, the instance (or AMI) will run the code on first boot up.

For further reference, this is a link to the Amazon docs on the topic:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html

This post originally appeared on stegsolutions.com. Need help with your virtualization project? Let us help. Contact zac@stegsolutions.com for more information.