Search code examples
variablesansiblehostname

Ansible - Add 1 in variable each time running on host


I am trying to make a playbook that can change the hostname of multiple hosts. So each time the task runs at a host it has to be add +1 to the name. So hostname1, hostname2 etc.

---
- name: Hostname
  hosts: win
  vars:
    winname: server
    count: 1
  tasks:

# Hostname edit
  - name: Hostname edit
    ansible.windows.win_hostname:
      name: "{{ winname }}{{ count }}"
    register: reboot

# Reboot host
  - name: Reboot
    ansible.windows.win_reboot:
    when: reboot.reboot_required

# Add 1
  - set_fact:
    count: "{{ count +1}}"

I have tried this, but the count stays at 1. Someone have any idea how I can fix this?

Thanks!


Solution

  • After the answer of Krishna Reddy I solved it this way: I did not use a block, but included a separate file.

    ---
    - name: Hostname
      hosts: win
    
      tasks:
      
        - name: set count
          set_fact:
            count: 1
    
        - include: hostnamesub.yml
          with_items: "{{ groups['win'] }}"
    

    Then in the separate file:

    # Hostname edit
    - name: Hostname edit
      ansible.windows.win_hostname:
        name: "server{{ count }}"
      register: reboot
      delegate_to: "{{ item }}"
      run_once: true
    
    # Reboot host
    - name: Reboot
      ansible.windows.win_reboot:
      delegate_to: "{{ item }}"
      run_once: true
      when: reboot.reboot_required
    
    # Count Increment
    - name: increase count
      set_fact: count={{ count | int + 1 }}