I was setting up a shiny new CentOS 7 EC2 instance, but when I tried to set the hostname using all of the typical Linux-y ways, none of them stuck after a reboot.  It just kept going back to the default EC2 naming convention of ‘ip-172.31.x.x’.  Since I am still getting used to CentOS 7 and all of the stuff they changed from 6, I figured it was a CentOS 7 thing.  Not so…

Turns out it was due to the EC2 instance being provisioned with cloud-init which AWS uses to configure the AMIs.  First I headed over to the cloud-init docs to see what I could glean from RTFM.  Meh, pretty useless.  So after some searching I came across AWS’ documentation and a few posts that outlined some examples of parameters to change in the cloud-init configuration.  So for me, the config that worked was the following:

# echo my-host1 > /etc/hostname (or use your fav editor)
# vim /etc/cloud/cloud.cfg

and make sure that cloud.cfg file has the following line at the bottom (noted in red):

    name: centos
    lock_passwd: true
    gecos: Cloud User
    groups: [wheel, adm, systemd-journal]
    sudo: ["ALL=(ALL) NOPASSWD:ALL"]
    shell: /bin/bash
  distro: rhel
    cloud_dir: /var/lib/cloud
    templates_dir: /etc/cloud/templates
  ssh_svcname: sshd

preserve_hostname: true

NOTE: notice that the line “preserve_hostname” has no indentation, e.g. “top level”.  This had me flummoxed for a reboot or two.

Now when I reboot, my hostname is correctly set!

[centos@my-host1 ~]$ hostname
[centos@my-host1 ~]$ hostname -f

Perfect!  For my FQDN I use a private Route 53 zone and have my DHCP options set to use that zone as the default for my VPC so that the hosts automatically pull the domain name.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s