Skip to content

Instantly share code, notes, and snippets.

@YarGnawh
Last active March 2, 2016 21:47
Show Gist options
  • Save YarGnawh/1f54247fce6148ca154d to your computer and use it in GitHub Desktop.
Save YarGnawh/1f54247fce6148ca154d to your computer and use it in GitHub Desktop.
AWS EC2 Ubuntu Update HOSTNAME Using JSON USER_DATA
#!/bin/bash
# Write to /usr/local/ec2/ec2-hostname.sh
# Execute chmod 755 ec2-hostname.sh
# Append /usr/local/ec2/ec2-hostname.sh to /etc/rc.local
# Referenced: http://ternarylabs.com/2010/09/15/automatically-configure-hostname-for-new-ec2-instances/
USER_DATA=`/usr/bin/curl -s http://169.254.169.254/latest/user-data`
IPV4=`/usr/bin/curl -s http://169.254.169.254/latest/meta-data/public-ipv4`
echo "Metdata user data : $USER_DATA"
USER_DATA_HOST=`echo $USER_DATA | python -c 'import json,sys; obj=json.load(sys.stdin); print obj["host"];'`
USER_DATA_DOMAIN=`echo $USER_DATA | python -c 'import json,sys; obj=json.load(sys.stdin); print obj["domain"];'`
echo "Updating hostname to $USER_DATA_HOST.$USER_DATA_DOMAIN"
# Set the host name
hostname $USER_DATA_HOST.$USER_DATA_DOMAIN
echo $USER_DATA_HOST.$USER_DATA_DOMAIN > /etc/hostname
# Update host file
cat<<EOF > /etc/hosts
# This file is automatically genreated by ec2-hostname script
127.0.0.1 localhost
127.0.0.1 $USER_DATA_HOST.$USER_DATA_DOMAIN $USER_DATA_HOST
$IPV4 $USER_DATA_HOST.$USER_DATA_DOMAIN $USER_DATA_HOST
# 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
EOF
{
"host":"jenkins",
"domain":"ofunc.com"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment