How to override the hostname that DHCP configures on a CentOS7 box in AWS? [duplicate]

Solution 1:

Alright. I spent probably a total of five hours on this problem before arriving at an answer. @Sirex's suggestion to uninstall cloud-init was the clue. Essentially, cloud-init is a service built into most EC2 images (AMIs), including AMI Linux and CentOS. The system does lots of things (google it), and is probably useful for certain provisioning and maintenance foo. Thus, I am hesitant to simply disable it. But, it also appears to be setting the EC2 hostname. So, to override that with your preferred hostname, simply do this:

(1) create a file called something like 99_...cfg (I named mine 99_hostname.cfg), and write the following contents into it:

#cloud-config
hostname: foo
fqdn: foo.bar.baz

replacing "foo" and "foo.bar.baz" with your host name and fully-qualified domain name, of course.

(2) Place this file in /etc/cloud/cloud.cfg.d/99_hostname.cfg

(3) Make sure the file permissions/owner/selinux context (if you have SELinux enforcing) are set properly via these commands:

sudo su -
cd /etc/cloud/cloud.cfg.d/
chown root: 99_hostname.cfg
chmod 644 99_hostname.cfg
chcon system_u:object_r:etc_t:s0 99_hostname.cfg

(4) Reboot your VM, and the new hostname should be set. If you don't trust your bash prompt, you can check this, by, for example, executing either of the following:

hostnamectl

or

cat /etc/hostname

Solution 2:

uninstall cloud-init.

This drove me mental the first time :-)

Still looking to find time to work out how to make cloud-init set the hostname as expected (from a tag or such) - not got that far myself yet.