Set hostname on CentOS using cloud-init

1.3k Views Asked by At

I want to use generic configuration in my cloud config file, to manually set the hostname for the deployed OS. cloud-init's "hostname" works just fine for ubuntu images, but cant get it to work for Centos cloud images(CentOS 7.8) to be specific. I see the entries are being made in /etc/hosts file, but 'hostname' command still returns 'localhost.localdomain'

Here is my cloud-config file:

preserve_hostname: true
hostname: worker1
fqdn: worker1.local
manage_etc_hosts: true

Here is the output of 'hostname' command:

[root@localhost ~]# hostname
localhost.localdomain

Here are the contents of /etc/hosts:

[root@localhost ~]# cat /etc/hosts
# Your system has configured 'manage_etc_hosts' as True.
# As a result, if you wish for changes to this file to persist
# then you will need to either
# a.) make changes to the master file in /etc/cloud/templates/hosts.redhat.tmpl
# b.) change or remove the value of 'manage_etc_hosts' in
#     /etc/cloud/cloud.cfg or cloud-config from user-data
#
# The following lines are desirable for IPv4 capable hosts
127.0.0.1 worker1.local worker1
127.0.0.1 localhost.localdomain localhost
127.0.0.1 localhost4.localdomain4 localhost4

I do not want to take the approach of 'hostnamectl' for setting hostname, as it will not be applicable to ubuntu/other OS.

So how can we achieve this using cloud-init?

[Version Info: CentOS: 7.8.2003 cloud-init: 18.5 ]

1

There are 1 best solutions below

0
On

You should change

preserve_hostname: True

to

preserve_hostname: False