Skip to content

Instantly share code, notes, and snippets.

@wdalmut
Created April 19, 2012 09:29
Show Gist options
  • Save wdalmut/2419942 to your computer and use it in GitHub Desktop.
Save wdalmut/2419942 to your computer and use it in GitHub Desktop.
Run EC2 user metadata (Alestic)
#!/bin/bash
#
# ec2-run-user-data - Run instance user-data if it looks like a script.
#
# Only retrieves and runs the user-data script once per instance. If
# you want the user-data script to run again (e.g., on the next boot)
# then add this command in the user-data script:
# rm -f /var/ec2/ec2-run-user-data.*
#
# History:
# 2008-05-16 Eric Hammond <ehammond@thinksome.com>
# - Initial version including code from Kim Scheibel, Jorge Oliveira
#
prog=$(basename $0)
logger="logger -t $prog"
curl="curl --retry 3 --silent --show-error --fail"
instance_data_url=http://169.254.169.254/2008-02-01
# Wait until networking is up on the EC2 instance.
perl -MIO::Socket::INET -e '
until(new IO::Socket::INET("169.254.169.254:80")){print"Waiting for network...\n";sleep 1}
' | $logger
# Exit if we have already run on this instance (e.g., previous boot).
ami_id=$($curl $instance_data_url/meta-data/ami-id)
been_run_file=/var/ec2/$prog.$ami_id
mkdir -p $(dirname $been_run_file)
if [ -f $been_run_file ]; then
$logger < $been_run_file
exit
fi
# Retrieve the instance user-data and run it if it looks like a script
user_data_file=$(tempfile --prefix ec2 --suffix .user-data --mode 700)
$logger "Retrieving user-data"
$curl -o $user_data_file $instance_data_url/user-data 2>&1 | $logger
if [ ! -s $user_data_file ]; then
$logger "No user-data available"
elif head -1 $user_data_file | egrep -v '^#!'; then
$logger "Skipping user-data as it does not begin with #!"
else
$logger "Running user-data"
echo "user-data has already been run on this instance" > $been_run_file
$user_data_file 2>&1 | logger -t "user-data"
$logger "user-data exit code: $?"
fi
rm -f $user_data_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment