how to assign in the variable for each server a line of the file with ansible?

Viewed 36

I have a file with numbers, what I want the playbook to do is read the first line of the file and save it in the variable var_num for that server, then delete that first line, and the next server I have in inventory does the same. I'm launching it from the AWX. And Iand I don't launch 1 server and then another, a set of servers is launched. I want to launch a group of servers. could you help me? Thank you very much.

number.txt:
 1001
 1002
 1005
 1008 

playbook.yml

---
- name: get number
  hosts: 
     -  server1
     -  server2
     -  server3
  vars:
    var_number: 
 
  tasks:

  - name: read the number
    shell: "head -n1 number.txt"
    register: result
    delegate_to: localhost

  - set_fact:
      var_number: "{{ result.stdout_lines }}"
    delegate_to: localhost
 
  - name: delete number
    shell: "sed -i '1d' number.txt"
    args:
      warn: false
    delegate_to: localhost
what it does:
 server1 --> 1001
 server2 --> 1001
 server3 --> 1001 

 what I want it to do:
 server1 --> 1001
 server2 --> 1002
 server3 --> 1005
1 Answers

Get the number in the first play and use it in the second play. Set serial: 1 for the first play to serve the hosts one by one. For example, given the inventory

shell> cat hosts
server1
server2
server3

and the file at the controller

shell> cat number.txt
1001
1002
1005
1008

The playbook

- name: get number
  hosts: all
  gather_facts: false
  serial: 1
  tasks:
    - name: read the number
      command: head -n1 number.txt
      register: result
      delegate_to: localhost
    - set_fact:
        var_num: "{{ result.stdout }}"
    - name: delete the number
      command: sed -i '1d' number.txt
      delegate_to: localhost

- name: print number
  hosts: all
  gather_facts: false
  tasks:
    - debug:
        var: var_num

gives (abridged)

PLAY [print number] **************************************************

TASK [debug] *********************************************************
ok: [server1] => 
  var_num: '1001'
ok: [server2] => 
  var_num: '1002'
ok: [server3] => 
  var_num: '1005'
shell> cat number.txt
1008
Related