Notes on Life, ‘Puters and Hawaii

Give Your AMI Images a Boot Hook with EC2 userdata

I need a way to configure servers at boot - to bootstrap them. Even if I have puppet to configure my AMIs on the fly, there are still some basic settings that need to happen to get puppet bootstrapped and working - like setting the hostname, notifying dyndns, setting the puppet server hostname, restarting puppetd, etc.

What I do is I add the following to my /etc/rc.local script on my AMI images.

/usr/bin/ruby -e "\
  require 'open-uri';\
  userdata=eval(open('http://169.254.169.254/2007-01-19/user-data').read);\
  eval(open(userdata[:script]).read, binding);\
"

and then I place a bootstrap ruby script on one of my webservers like so (helloworld example):

#!/usr/bin/env ruby
open('/tmp/helloworld', 'w') do |f|
  f < < "The secret was '#{userdata[:secret]}'"
end

then when booting the new image I provide a Ruby hash as the ‘userdata’:

{
  :script => 'http://lolcat.com/bootstrap.rb',
  :secret => 'i can has cheeseburger?'
}

You can see with this setup I can pass any script into the AMI with any variables the script may need. This sample script above puts a /tmp file on the box thas says “The secret was ‘i can has cheesburger?’” However, with this pattern, anything is possible. You can change the :script at launch time to point to any ruby script you want.

Comments are closed.