How to set hostname with running number

Hi,
In my inventory file i have 3 server, I need to set the hostname including prefix1-3

web1
web2
web3

Inventory fie:

[web]
192.168.0.47
192.168.0.48
192.168.0.49

Playbook

  • hosts:

  • web
    become: true
    any_errors_fatal: true
    tasks:

  • name: update hostname
    hostname:
    name : “web ???”

Hi,
In my inventory file i have 3 server, I need to set the hostname including prefix1-3

web1
web2
web3

*Inventory fie:*

[web]
192.168.0.47
192.168.0.48
192.168.0.49

Add the hostname to the inventory file:

web1 ansible_host=192.168.0.47

*Playbook*

- hosts:
- web
become: true
any_errors_fatal: true
tasks:

 \- name: update hostname
   hostname:
     name : "web ????"

Now you can use the inventory_hostname variable in your task:

        - name: update hostname
          hostname:
            name: "{{ inventory_hostname }}"

Please note that might not survive reboots, e.g on Ubuntu I'm doing:

- name: Enable preserving hostname in Cloud configuration
   lineinfile:
     path: /etc/cloud/cloud.cfg
     line: 'preserve_hostname: true'
     regexp: '^preserve_hostname:'
   tags: hostname

Regards
           Racke