简体   繁体   中英

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!

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'] 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM