AWS: Naming UNIX instances

Problem

Generating meaningful hostnames without human intervention.

Requirements

Uniquely identify instance by its purpose, environment (qa, prod, stage, dev) & location .

One solution

1) Query the ec2 metadata service for indentifiers.

2) Generate and set a unique hostname.

Optionally, the instace may register its hostname in DNS using an api, nsupdate, etc.

(EG: wwwprd1b99.east.openphoto.net)

Pseudocode for instance boot

(As with all code on OTN, details and error handling have been removed for clarity. Do not execute as is!)

#!/bin/sh
#### generate a unique hostname at boot ####
service="www"
environment="prd"
domain="openphoto.net"
metadata="http://169.254.169.254/latest/meta-data"
az=$(curl -s $metadata/placement/availability-zone/ | awk -F- '{print $3}')
region=$(curl -s $metadata/placement/availability-zone/ | awk -F- '{print $2}')
lastoctet=$(curl -s $metadata/local-ipv4 | awk -F. '{print $4}')
hostname=$(echo "${service}${environment}-$az-$lastoctet.$region.$domain")
hostname $(echo $hostname)
/u/local/bin/register-instance-dns $hostname
exit $?

To permanently set the hostname on a RHEL/CentOS system, /etc/sysconfig/network should be updated.

Leave a Reply

Your email address will not be published. Required fields are marked *