【问题标题】:Ansible extract shell output using awkAnsible 使用 awk 提取 shell 输出
【发布时间】:2020-12-30 14:02:44
【问题描述】:
---
- 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

没有给出预期的输出,因为我在 shell 模块中使用 awk / grep 时遇到语法错误。请参考预期的输出。

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
..

【问题讨论】:

    标签: shell module ansible ansible-template


    【解决方案1】:

    您确定错误与shell 任务有关吗?我能够毫无错误地运行它。

    所提供示例的一个问题是lineinfile 仅使用一次(即仅更新一行)。我们可以利用 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
    

    如果您在清单文件中使用 DNS 记录,但希望在 .csv 文件中使用 IP 地址,那么您需要将 inventory_hostname 替换为 host_vars 查找(可能)hostvars[inventory_hostname]['ansible_default_ipv4']['address']

    如果没有,上面的例子就足够了。

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      相关资源
      最近更新 更多