This article is intended to be a tutorial for the steps on how to change hostname on Linux using Ansible. This means that we’ll be demonstrating 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 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 hostname on Linux with Ansible:
- SSH access to the server
- User with sudo privileges
- Python 3.x > version installed on the remote server
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
How to change hostname on Linux using Ansible(code)
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 how to change Linux hostname. The code is straightforward and simple to use:
- name: "Server configuration" hosts: "all" tasks: - name: "Configure hostname" ansible.builtin.hostname: name: "new-hostname" become: true
Change hostname on Linux using Ansible - code
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 - command
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 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…