How to Change the Hostname of a Red Hat/CentOS 7 AWS Instance

Normally, changing the hostname if a Red Hat 7 or CentOS 7 sytem is straightforward. Just edit the /etc/hostname file and reboot. AWS instances are a little bit different, though.

AWS Cloud Configuration

An AWS instance comes with Amazon’s “cloud configuration”. This is the setup which provides those handy customizations with which users of AWS will be familiar, viz:

  • the default hostname, of the form “ip-” followed by the IP address, eg. “ip-“.
  • the default user and SSH key.
  • the default swap setup, root file system type, sudo configuration, DHCP options and so on.

Hostname Reverts

If you change the hostname by just editing /etc/hostname and rebooting, it will simply change back to the default, for example “ip-”. The cloud configuration causes this.

To change the hostname effectively, first edit /etc/hostname, then you must also edit the file /etc/cloud/cloud.cfg and add the line “preserve_hostname: true“. Then reboot.

For example, here is the cloud.cfg file from an instance I recently renamed. With the line added to the end of the file, it was easy to change the hostname in the usual way.

# tail /etc/cloud/cloud.cfg
   shell: /bin/bash
  distro: rhel
    cloud_dir: /var/lib/cloud
    templates_dir: /etc/cloud/templates
  ssh_svcname: sshd

# vim:syntax=yaml
preserve_hostname: true

Ansible Code

A suitable piece of Ansible might be something like this, (assuming your Ansible hosts file contains a “hostname” variable):

- hosts: testboxes
    - name: Set Hostname
      hostname: name="{{ hostname }}"

    # Double quoting to allow the space,colon
    # in the "line=" line.

    - name: Disable cloud hostname
      lineinfile: "dest=/etc/cloud/cloud.cfg
                  line='preserve_hostname: true'

…followed by a reboot, as applicable.

Leave a Reply

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