如何将 Ansible 变量内容插入到 CSV 文件中?

问题描述 投票:0回答:1

我希望将 2 个变量中的内容插入到 CSV 文件中,每个变量都在单独的列中,但两个变量都将其内容插入到同一列中。

我已经尝试过这个剧本

- name: "fetch remote host data"
  hosts: "redhat"

  tasks:

    - name: fetch user list
      shell: |
        awk -F: '{print $1}' /etc/passwd
      register: user_data

    - name: fetch /etc/host info
      shell: |
        awk -F: '{print $1}' /etc/hostname
      register: host_data

    - name: create write csv file
      local_action:
        module: lineinfile
        dest: /tmp/output.csv
        line: "users,host_data"
        create: yes

    - name: write remote host data to csv file
      local_action:
        module: lineinfile
        dest: /tmp/output.csv
        line: "{{ user_data.stdout }},{{ host_data.stdout }}"
        create: yes
csv ansible
1个回答
0
投票

一般来说,建议使用专用的、特定的 Ansible 模块,而不是通用的

shell
模块。在你的例子中
getent
模块 – Unix
getent
实用程序
的包装器。

一个最小的示例手册

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - getent:
      database: passwd
      split: ':'
    register: result

  - debug:
      msg: "{{ result.ansible_facts.getent_passwd.keys() }}"

  - debug:
      msg: |
        User;Hostname;
        {% for user in result.ansible_facts.getent_passwd.keys() %}
        {{ user }};{{ inventory_hostname }}
        {% endfor %}

将产生请求的输出。

TASK [debug] *******
ok: [localhost] =>
  msg:
  - root
  - nobody
  - sshd
  - admin
...

TASK [debug] *******
ok: [localhost] =>
  msg: |-
    User;Hostname;
    root;localhost
    nobody;localhost
    sshd;localhost
    admin;localhost
...

将其写入文件很简单,例如通过

copy
模块 – 将文件复制到远程位置 - 参数:
content

类似问答


为了完整性

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - getent:
      database: passwd
      split: ':'
    register: result

  - local_action:
      module: copy
      dest: output.csv
      content: |
        User;Hostname
        {% for host in ansible_play_hosts %}
        {% for user in hostvars[host].result.ansible_facts.getent_passwd.keys() %}
        {{ user }};{{ host }}
        {% endfor %}
        {% endfor %}
    run_once: true
© www.soinside.com 2019 - 2024. All rights reserved.