Virtual Machines with Custom Hostnames
When you first create a virtual machine (VM) on Google Cloud, an internal DNS name is automatically created. The default hostname of the machine will take the form [INSTANCE_NAME].[ZONE].c.[PROJECT_ID]. For example, if you name your instance “my-instance,” the project ID is “my-project” and you create the instance in “zone us-central1-a”, the VM’s hostname will be my-instance.us-central1-a.c.my-project.
This might not seem like a big deal – unless you’re using the VM as a web and email server. Of course, right after installing the application stack you need to run the website, you’ll start seeing the problem with this conveniently self-configured hostname. Name servers and mail transfer agents like Exim will want the hostname to be a fully qualified domain name (FQDN) like myserver.example.com.
If you’re like me, you’ll start digging through Google’s documents only to find out you could have set the hostname when you first created the VM. Unfortunately, you’ve spend days configuring the machine and now you can’t change the VM’s hostname. Or can you?
Changing the VM’s hostname when the network starts
The first problem we’ll solve is to make sure the hostname is set correctly whenever the network restarts. You’ll need to log into your VM and elevate your privileges to root. On a RedHat / Centos / AlmaLinux / Rocky Linux machine you’d SSH into the machine, and then:
First, we need to make a directory, and check that it was created successfully:
mkdir /etc/dhcp/dhclient-exit-hooks.d/ cd /etc/dhcp ls -all
If making the directory was a success you should see it listed. Next, we need to create a script to set the hostname. Using your favorite editor (mine is nano):
The contents of this file need to be as shown below, substituting your hostname for myserver.example.com:
#!/bin/bash hostname myserver.example.com
Save the file using control X, and saying “y” or “yes.” The last step is to make the file executable:
chmod +x /etc/dhcp/dhclient-exit-hooks.d/apply-hostname.sh
Setting the hostname during reboots
At this point, we’ve solved the network startup problem, but we will still have an issue during reboots. We need to go back to the Google Cloud Console VM instance details and edit the custom metadata section, by adding the following:
Key hostname-script Value #! /bin/bash hostname myserver.example.com
You might find the services that depend on the hostname started before this startup script runs and have the Google-assigned hostname we are trying to overwrite. You can remedy that problem by restarting the service using the same startup script. For example, you could add the following line to the above script to restart Exim:
Key hostname-script Value #! /bin/bash hostname myserver.example.com systemctl restart exim.service