How do I set the hostname of an instance in GCE permanently? I can set it via hostname,but after reboot it is gone again.
I tried to feed in metadata (hostname:f.q.d.n), but that did not do the job. But it should work via metadata (https://github.com/GoogleCloudPlatform/compute-image-packages/tree/master/google-startup-scripts).
Anybody an idea?
The most simple way to achieve it is creating a simple script and that's what I have done.
I have stored the hostname in the instance metadata and then I retrieve it every time the system restarts in order to set the hostname using a cron job.
$ gcloud compute instances add-metadata <instance> --metadata hostname=<new_hostname>
$ sudo crontab -e
And this is the line that must be appended in crontab
@reboot hostname $(curl --silent "http://metadata.google.internal/computeMetadata/v1/instance/attributes/hostname" -H "Metadata-Flavor: Google")
After these steps, every time you restart your instance it will have the hostname <new_hostname>
.
You can check it in the prompt or with the command: hostname
Appears to be a viable solution. But I settled with the advice not to change the hostname, because it is not necessary. All outside appearing hostnames can/should be set in the respective applications.
Nice solution @Adrián, thanks! But doesn't work for me. It seems that google sets the hostname after the startup pf the cron daemon...
Inspired by this solution, I wrote a patch that preserves your hostname from overwriting from Google. stackoverflow.com/a/38344684/1325832
This did not work for me - another solution here did: stackoverflow.com/a/53607475/8177355