Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

module - Ansible extract shell output using awk

---
- name: Data Collection
  hosts: all
  tasks:
    - name: List all users
      shell: "cat /etc/passwd | awk -F: '{print $1}'"
      register: users
    - lineinfile:
        dest: /tmp/users.csv
        create: yes
        line: "The {{ inventory_hostname}}, {{ users.stdout }}"
      delegate_to: localhost

Doesn't give the intended output as I'm getting syntax error for using awk / grep in shell module. Kindly refer the intended output.

172.17.254.201, root
172.17.254.201, bin
172.17.254.201, nobody
172.17.254.201, test1
172.17.254.201, test2
172.17.254.202, root
172.17.254.202, bin
172.17.254.202, nobody
172.17.254.202, test1
172.17.254.202, test2
..

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are you certain the error is related to the shell task? I was able to run it without errors.

One issue with the provided example is that lineinfile is only used once (i.e. only a single line will be updated). We can solve this issue by utilizing Ansible loop.

---
- name: Data Collection
  hosts: all
  tasks:
    - name: List all users
      shell: "cat /etc/passwd | awk -F: '{print $1}'"
      register: users
    - lineinfile:
        dest: /tmp/users.csv
        create: yes
        line: "{{ inventory_hostname}}, {{ item }}"
      loop: "{{ users.stdout_lines }}"
      delegate_to: localhost

If you're using DNS records in the inventory file but want IP addresses in the .csv file, then you'll want to replace inventory_hostname with a host_vars lookup (likely) for hostvars[inventory_hostname]['ansible_default_ipv4']['address'].

If not, the above example should suffice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...