Search code examples
automationansibledevopsansible-2.x

Ansible save registered variable to a file using lineinfile module


I'm trying to save the value of a registered variable to a file using lineinfile module, I have 3 hosts in hosts file, but the output contain only 2 host information. Am I missing anything in the lineinfile module?

count.yaml

---
- name: Ansbile script to save command line output
  hosts: all
  become_user: root
  tasks:

  - name: create a file
    file:
     path: /home/codemaster/count.txt
     state: touch
     force: yes
    delegate_to: localhost


  - name: Check End Points 
    shell: kamctl online | wc -l
    register: ep

  - name: save result to a file
    lineinfile:
      dest: /home/codemaster/count.txt
      line: "{{ inventory_hostname + ' ' + ep.stdout }}"
      insertafter: EOF
    delegate_to: localhost

hosts_file

[webrtc]
128.6.6.10 
128.6.6.12 
128.6.6.18

OUTPUT:

[codemaster@127.9.7.6 ~]$ cat count.txt
128.6.6.10 4694
128.6.6.12 4280

Solution

  • Avoid concurrent writing from all hosts. Write it in one task. For example,

     - name: save result to a file
       lineinfile:
         dest: /home/codemaster/count.txt
         line: "{{ item }} {{ hostvars[item].ep.stdout }}"
         insertafter: EOF
       loop: "{{ ansible_play_hosts_all }}"
       delegate_to: localhost
       run_once: true
    

    (not tested)