This article will demonstrate how we to set a hostname on a Linux server using Ansible playbook. The end goal of this procedure is to automate the process changing the hostname on our remote Linux server.

Overall this process is simple when executed manually but this playbook can have it’s uses too. One example - use it as a template for new server deployment

Requirements in order to successfully change the hostname:

  • SSH access to the server
  • User with sudo privileges
  • Python 3.x > version installed on the remote server

Setup environment

In one directory we’re going to create an Ansible playbook “change-hostname.yml” file and an empty file called “inventory”. The “inventory” file will be populated with the IP addresses of our remote hosts.

touch inventory && touch change-hostname.yml

vim inventory

Ansible code to change the hostname

Ansible does provide by default the module called the “ansible.bultin.hostname” which allows us to change the hostname. What’s even great, Ansible is capable changing the hostname on Linux without rebooting the machine.

Bellow is an example for the Ansible playbook. The code is straightforward and simple to use:

- name: "Server configuration"
  hosts: "all"


    - name: "Configure hostname"
        name: "new-hostname"
      become: true

Change hostname on Linux using Ansible

Command to execute in order to test and see will the Ansible playbook work and change the hostname on Linux:

ansible-playbook -u markon -k -K -i inventory.txt change-hostname.yml

In the Ansible command we provided the sudo user, set options for Ansible to prompt us the SSH password and password of the sudo user to gain sudo privileges, defined the inventory file and the Ansible playbook we’re running.

The end result should look like the example bellow:

Change hostname on Linux using Ansible

Change hostname on Linux using Ansible

End result


Let’s summarize - we showcased the procedure on how to change hostname on Linux using Ansible. So what we have accomplished is - we created an Ansible playbook which allowed us to automatically change hostname on our remote Linux server and as a bonus it does so that without the need of restarting the server.

Thank you for your time…