I'm trying to change the hostnames for a remote server using the following ansible playbook:
---
- hosts: dbservers
  remote_user: testuser1
  become: yes
  become_method: sudo
  vars: 
    LOCAL_HOSTNAME: 'db01'
    LOCAL_DOMAIN_NAME: 'ansibletest.com'
  tasks:
    # Checks and removed the existing occurences of <IP hostname FQDN> from /etc/hosts
    - name: Remove occurences of the existing IP
      lineinfile: dest=/etc/hosts
                  regexp='{{ hostvars[item].ansible_default_ipv4.address }}'
                  state=absent
      when: hostvars[item].ansible_default_ipv4.address is defined
      with_items: "{{ groups['dbservers'] }}"
    #  Adds the IP in the format  <IP hostname FQDN> to /etc/hosts
    - name: Add the IP and hostname to the hosts file
      lineinfile: dest=/etc/hosts
                  regexp='.*{{ item }}$'
                  line="{{ hostvars[item].ansible_default_ipv4.address }} {{ LOCAL_HOSTNAME }} {{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}"
                  state=present
      when: hostvars[item].ansible_default_ipv4.address is defined
      with_items: "{{ groups['dbservers'] }}"
    - name: Remove HOSTNAME occurences from /etc/sysconfig/network
      lineinfile: dest=/etc/sysconfig/network
                  regexp='^HOSTNAME'
                  state=absent
      when: hostvars[item].ansible_default_ipv4.address is defined
      with_items: "{{ groups['dbservers'] }}"
    - name: Add new HOSTNAME to /etc/sysconfig/network
      lineinfile: dest=/etc/sysconfig/network
                  regexp='^HOSTNAME='
                  line="HOSTNAME={{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}"
                  state=present
      when: hostvars[item].ansible_default_ipv4.address is defined
      with_items: "{{ groups['dbservers'] }}"
    - name: Set up the hostname
      hostname: name={{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}
Here, the LOCAL_HOSTNAME is assigned the value of db01 and dbservers group has one server
[dbservers]
192.168.1.93
But I have 2 more servers assigned to webservers
[webservers]
192.168.1.95
192.168.1.96
[dbservers]
192.168.1.93
I want to change their names to web01.domain and web02domain. I've read the docs and it says that we can do this by using with_sequence. I want to know if I could possibly use 2 variables in loops? like this:
i=1
for host in webservers:
   open host(/etc/hosts):
       add "IP<space>HOSTNAME{i}<space>"<space>"HOSTNAME{i}.FQDN"
       i++
Can this be done using playbook or is there any other way to achieve this??