Prettify your EC2 Hostnames
Every time we spin up an EC2 instance the hostname would be set to its internal ip. The SSH keys are generated and injected to the machine by the cloud-init scripts on boot but I’m not sure if the hostnames are also set by cloud-init. Anyways they look ugly for me. When I SSH into these boxes through bastian boxes or when I restore my tmux sessions, I always lose track of the instance I’m in. Few time I did run wrong commands in the wrong instances.
So I wanted neat hostnames. I had seen in movies and many other blog posts. They have pretty urls like db1-production-newyork-dc-2.company.net
, db2-test-oregon-dc-4.mycompany.net
. These could be public DNS or local private DNS within the data centre. So I wanted to try something like this. If not the private DNS at least I will set the hostnames and make it look little pretty.
DISCLAIMER:
- Amateur here 👨🏻💻.
- There could be better ways to do same thing what I’m trying to do, I’d love to learn them.
The hostname must be set in the
/etc/hostname
file and the FQDN must be aliased in/etc/hosts
. For more details you can refer the man page of hostname here.
Setting Hostname with persistence on boot.
- run
sudo vim /etc/hostname
and update the existing hostname to the name you want. (On boot this file is read and hostname is set, that’s how we get persistence on boot.) I’m gonna set mine todb2-staging-newyork-dc-4
. Heredb2
is the resource type (database number 2),staging
is the environment,newyork
is the region where our data centre is present and4
(data centre number 4).
2. update the /etc/hosts
file with the FQDN. Our FQDN will be db2-staging-newyork-dc-4.mycompany.net
. Here we are aliasing localhost as we want even localhost to work.
3. run sudo hostname -f /etc/hostname
. This will set the hostname of the machine from the hostname file.
4. Now you can exit the shell and login again to see your new hostname.
5. verify by rebooting the machine once and pinging your hostname.
And now you have a pretty hostname.
6. You could automate these steps by putting it in a shell script and running it while launching the instance. But, you might need another service to track these names and to generate unique names for each machine.