Score:0

Playbook to extract hosts from /etc/hosts

hk flag

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
Score:3
in flag

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 }}"
Adelmo Silva avatar
hk flag
Thank very much, my friend. Its working fine. Gerald, could you recommend an ansible course to improve my skills please?
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.