Change/Remove Remote Hostname Using Ansible Playbook

Change/Remove Hostname Using Ansible Playbook on ubuntu

Today, In this article I will explains how to setting up hostname using ansible playbook.

My Setup:

I use 3 systems, One machine as ansible server setup and other two machine as a remote machine. Let look at below details for more understanding.

Ansible Server: (hostname: ansible)
Remote Server1: (hostname: remote1)
Remote Server2: (hostname: remote2)

Using ansible Playbook I will setting up Remote Server1 hostname to “remote1” and for remote server2 set “remote2” hostname.

1) Setting up inventory file.

For the inventory, I created a file (i.e “hosts” ) and filled it with following content details.

/etc/ansible# cat hosts
server1 ansible_host= ansible_user=gaurav ansible_ssh_pass=123 ansible_connection=ssh new_hostname=remote1
server2 ansible_host= ansible_user=gaurav ansible_ssh_pass=123 ansible_connection=ssh new_hostname=remote2

Above inventory file allows us to use the “server1” and “server2” as target hosts in our ansible playbook.

2) Setting up playbook.

In second step I created the playbook (i.e playbook.yaml) and add hosts (ansible run this playbook for all available hosts). I set ‘become‘ to true to activate privilege escalation and use ‘become_method‘ as a sudo (In our case ‘gaurav‘ is the sudo user).

The next step is to fill Playbook with tasks to change the hostname. I used hostname module for change the hostname. This module does not modify /etc/hosts. So I use other task to replace hostname in /etc/hosts file.

  name: 'Playbook for change the hostname'
  hosts: remoteservers
  become: True
  become_method: sudo
    - name: "Update Hostnames"
        name: "{{ new_hostname }}"
    - name: 'Add hostname to /etc/hosts'
        path: /etc/hosts
        regexp: '^127\.0\.0\.1[ \t]+localhost'
        line: ' localhost {{ new_hostname }}'
        state: present

Note: We use “new_hostname” variable for hostname of remote server which we set in invortory file.

3) Execute the playbook in the cli.

Now execute the playbook in ansible server using below command.

root@ansible:/etc/ansible/playbook# ansible-playbook playbook.yaml --ask-become-pass

Ansible will then print the feedback for each task.

Now check or verify the hostnames in remote servers.

Verify the hosts file in remote1 server.

check on other remote server.

The hostname of my both remote servers has changed you can see the output above screenshot.

Ansible automation was successfully changed the hostname. Hope this post will help Devops beginners. Please share you feedback and Comments. Stay tune for more updates with …!!!

Leave a Reply


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of