Home > Back-end >  Ansible - Add 1 in variable each time running on host
Ansible - Add 1 in variable each time running on host

Time:04-06

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!

CodePudding user response:

Your scenario need to be executed sequentially host after host with the incremental hostname*. So try the below approach

- name: set count
  set_fact:
    count: 1

- name: Hostname Update Block
  block:
    # 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 }}
  with_items: groups['win'] 

CodePudding user response:

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 }}
  • Related