0

I need help extracting hosts informations from /etc/hosts file and exporting that content to a predefined file. I created a Ansible's Playbook to this task, but the content is not written on the output file. Do you guys, can help me, please?

Following Playbook:

- hosts: sigt-temp 
  become: yes
  become_user: root
  gather_facts: yes
  
  tasks:
  
    - name: Collecting Data
      shell:
        cmd: grep -P -i '^10\.129\.' /etc/hosts
      register: etc_hosts
      
    - name: Collecting Data
      debug: var=ansible_hostname,ansible_default_ipv4['address'],etc_hosts
    - name: Output info
      local_action: lineinfile path=./etc-hosts.txt line={{ansible_hostname}};{{ansible_default_ipv4['address']}};{{etc_hosts}}; create=yes
      
    - name: Validation
      debug: var=etc_hosts.stdout_lines
Gerald Schneider
  • 23,274
  • 8
  • 57
  • 89

1 Answers1

3

The only error you have is that you use {{etc_hosts}} in the lineinfile action, which dumps the complete information about the hosts file into your .txt file. This should be {{etc_hosts.stdout_lines}} instead, if you are sure that you only get a single line returned.

If the possibility exists that a hosts file contains more than one entry that matches your regex, you should loop over the result.

    - name: Output info
      local_action: lineinfile path=./etc-hosts.txt line={{ansible_hostname}};{{ansible_default_ipv4['address']}};{{item}}; create=yes
      loop: "{{ etc_hosts.stdout_lines }}"
Gerald Schneider
  • 23,274
  • 8
  • 57
  • 89
  • Thank very much, my friend. Its working fine. Gerald, could you recommend an ansible course to improve my skills please? – Adelmo Silva Nov 01 '22 at 13:01