Skip to content

Instantly share code, notes, and snippets.

@kirtfitzpatrick
Created April 9, 2012 21:27
Show Gist options
  • Save kirtfitzpatrick/2346664 to your computer and use it in GitHub Desktop.
Save kirtfitzpatrick/2346664 to your computer and use it in GitHub Desktop.
Knife Ec2 Hostname Script - for Chef
#!/usr/bin/env ruby
# This script is intended to preprocess a knife ec2 server create command and
# generate a user_data script in the /tmp folder that will rename the host
# to match whatever the node name is before the chef bootstrapping process
# begins. It then splits the knife command in front of the --node-name or -N
# options and inserts "--user-data /tmp/server-01.userdata" (in the example
# below) and execs the command.
#
# Usage:
# ec2_hostname knife ec2 server create --node-name server-01 --run-list 'role[awesome]' --whatever honey-badgers
require "erb"
class Ec2Hostname
def go(argv=ARGV)
node_name_index = argv.index('--node-name') || argv.index('-N')
@hostname = argv[(node_name_index+1)]
@domain = 'airtime.com'
user_data_path = "/tmp/#{@hostname}.userdata"
File.open(user_data_path, 'w') do |f|
f.write ERB.new(DATA.read).result(binding)
end
argv.insert(node_name_index, user_data_path)
argv.insert(node_name_index, '--user-data')
safe = argv.map do |arg|
case arg
when /[\]\[]/
"\"#{arg.gsub(',','","')}\""
else
arg
end
end
puts safe.join(' ')
exec safe.join(' ')
end
end
Ec2Hostname.new.go(ARGV)
__END__
#!/bin/bash
# Replace this with your domain
DOMAIN="<%= @domain %>"
HOSTNAME="<%= @hostname %>"
IPV4=`/usr/bin/curl -s http://169.254.169.254/latest/meta-data/public-ipv4`
# Set the host name
hostname $HOSTNAME
echo $HOSTNAME >> /etc/hostname
# Add fqdn to hosts file
echo "# Start of ec2_hostname modifications
127.0.0.1 localhost
$IPV4 $HOSTNAME.$DOMAIN $HOSTNAME
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
# End of ec2_hostname modifications
" > /etc/hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment