Skip to content

Instantly share code, notes, and snippets.

@callumj
Created July 12, 2012 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callumj/3095059 to your computer and use it in GitHub Desktop.
Save callumj/3095059 to your computer and use it in GitHub Desktop.
Set hostname from EC2 Tags (Name, Domain)
#!/usr/bin/env ruby
require 'net/http'
require 'open-uri'
require 'uri'
require 'base64'
require 'openssl'
require 'cgi'
def query_aws(host, path, action, params = {}, method = "GET")
params["SignatureVersion"] = 2
params["SignatureMethod"] = "HmacSHA1"
params["Action"] = action
params["Version"] = "2012-06-15"
params["Expires"] = (Time.now + 60).iso8601
sec_token = params.delete "SecurityToken"
sign_string = "#{method}\n"
sign_string << "#{host}\n"
sign_string << "#{path}\n"
sign_string << params.sort.collect { |key, value| [CGI.escape(key.to_s), CGI.escape(value.to_s)].join('=') }.join('&')
key = sec_token
hmac = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), sec_token, sign_string)).strip
params['Signature'] = hmac
base_url = "http://#{host}#{path}?"
querystring = params.collect { |key, value| [CGI.escape(key.to_s), CGI.escape(value.to_s)].join('=') }.join('&')
url = "#{base_url}#{querystring}"
resp = open(url).read
resp
end
# IAM identity for tag-query user
AWS_ACCESS_KEY = ""
AWS_SECRET = ""
# fetch the system's current instance_id
instance_id = open("http://169.254.169.254/latest/meta-data/instance-id").read
# fetch the system's region
az = open("http://169.254.169.254/latest/meta-data/placement/availability-zone").read
ipv4 = open("http://169.254.169.254/latest/meta-data/local-ipv4").read
region = az.gsub(/[A-Za-z]+$/,"")
# query the AWS API tags
resp = query_aws "ec2.#{region}.amazonaws.com", "/", "DescribeTags", {"AWSAccessKeyId" => AWS_ACCESS_KEY, "SecurityToken" => AWS_SECRET,
"Filter.1.Name" => "resource-type", "Filter.1.Value.1" => "instance", "Filter.2.Name" => "resource-id", "Filter.2.Value.1" => instance_id}
hostname = resp.match(/<key>Name<\/key>\s+<value>(.*)<\/value>/)[1] rescue nil
domain = resp.match(/<key>Domain<\/key>\s+<value>(.*)<\/value>/)[1] rescue nil
# run system hostname config
File.open("/etc/hostname", "w") {|file| file.write(hostname)}
`hostname -F /etc/hostname`
# set FQDN for further queries
host_file = "127.0.0.1 localhost
# 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
# Added by EC2 hostname resolver
#{ipv4} #{hostname}.#{domain} #{hostname}"
File.open("/etc/hosts", "w") { |file| file.write(host_file)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment