Ansible increment variable globally for all hosts

ansible

I have two servers in my inventory (hosts)

[server]
10.23.12.33
10.23.12.40

and playbook (play.yml)

---
- hosts: all
  roles:
    web

Inside web role in vars directory i have main.yml

---
file_number : 0

Inside web role in tasks directory i have main.yml

---
- name: Increment variable
  set_fact: file_number={{ file_number | int + 1 }}

- name: create file
  command: 'touch file{{ file_number }}'

Now i expect that in first machine i will have file1 and in second machine i will have file2 but in both machines i have file1

So this variable is local for every machine, how could i make it global for all machines.

My file structure is:

hosts
play.yml
roles/
  web/
    tasks/
      main.yml
    vars/
      main.yml

Best Answer

I haven't found a solution with ansible although i made work around using shell to make global variable for all hosts.

  1. Create temporary file in /tmp in localhost and place in it the starting count
  2. Read the file for every host and increment the number inside the file

I created the file and initialized it in the playbook (play.yml)

- name: Manage localhost working area
  hosts: 127.0.0.1
  connection: local
  tasks:
    - name: Create localhost tmp file
      file: path={{ item.path }} state={{ item.state }}
      with_items:
       - { path: '/tmp/file_num', state: 'absent' }
       - { path: '/tmp/file_num', state: 'touch' }

    - name: Managing tmp files
      lineinfile: dest=/tmp/file_num line='0'

Then in web role in main.tml task i read the file and increment it.

- name: Get file number
  local_action: shell file=$((`cat /tmp/file_num` + 1)); echo $file | tee /tmp/file_num
  register: file_num

- name: Set file name
  command: 'touch file{{ file_num.stdout }}'

Now i have in first host file1 and in second host file2

Related Topic