Last active
November 9, 2015 18:22
-
-
Save Rican7/13515825659f6d5032f0 to your computer and use it in GitHub Desktop.
Automatically set a structured, formatted hostname containing the AWS EC2 Instance ID for an EC2 virtual machine running RHEL/CentOS 6.x.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Enable strict error handling | |
set -u -o pipefail | |
# Define our hostname formats | |
readonly HOSTNAME_FORMAT="%s.my-service-name.environment-name" | |
readonly FQDN_HOSTNAME_FORMAT="%s.service.example.com" | |
# Get the current hostname | |
readonly OLD_HOSTNAME="$(hostname --fqdn)" | |
# Get the AWS "instance-ID" associated with the current (v) machine | |
instance_id="" | |
for _ in {1..5}; do | |
instance_id="$(curl --fail --silent http://169.254.169.254/latest/meta-data/instance-id)" | |
[ 0 == "$?" ] && break | |
sleep 2 | |
done; | |
# If our current hostname already contains our instance ID | |
if [[ "${OLD_HOSTNAME}" == *"${instance_id}"* ]]; then | |
# No need to change anything | |
echo "Hostname unchanged: '$(hostname)' '${OLD_HOSTNAME}'" | |
exit 0 | |
fi | |
# Create our new hostname from our format and instance id | |
new_hostname="$(printf -- "$HOSTNAME_FORMAT" "$instance_id")" | |
fqdn_new_hostname="$(printf -- "$FQDN_HOSTNAME_FORMAT" "$new_hostname")" | |
# Replace our hostname as defined in our network config | |
sed -i "s/HOSTNAME=.*/HOSTNAME=${new_hostname}/g" /etc/sysconfig/network | |
# Set the hostname through the CLI for temporary resolution | |
hostname "${new_hostname}" | |
# Add a hosts file DNS definition | |
sed -i "s/\(\(127\.0\.0\.1\|::1\)\s\+\)\(.*\)/\1 ${fqdn_new_hostname} ${new_hostname} \3/g" /etc/hosts | |
# Restart our networking service | |
service network restart | |
# Report our success | |
echo "New hostname: '${new_hostname}' '${fqdn_new_hostname}'" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment