写入csv文件

时间:2019-05-29 14:51:10

标签: csv ansible

我需要使用ansible将csv格式的某些内容写入文件中

shell: ps -ef | grep java | awk '{print $1}'
register: username

shell: ps -ef | grep java | awk '{print $2}'
register: id

用户名的输出将类似于:

root
admin
test_admin

id的输出将类似于:

1232
4343
2233

所以我希望将其写为csv文件

root,1232
admin,4343
test_admin,2233

请提出建议。

1 个答案:

答案 0 :(得分:2)

您可以结合使用zip,map和join过滤器来获得所需的结果:

- hosts: all
  tasks:
    - name: combination of two lists
      set_fact:
        lines: "{{ [1,2,3]|zip(['a','b','c'])|list }}"
    - debug:
        msg: "{{ lines }}"
    - name: transform each line into a string
      set_fact:
        lines: "{{ lines | map('join', ', ') | list }}"
    - debug:
        msg: "{{ lines }}"
    - name: combine lines
      set_fact:
        lines: "{{ lines | join('\n') }}"
    - debug:
        msg: "{{ lines }}"
    - name: write lines to file
      copy:
        content: "{{ lines }}"
        dest: "output.csv"

或将过滤器组合在一起时:

- name: write lines to file
  copy:
    content: "{{ [1,2,3] | zip(['a','b','c']) | map('join', ', ')  | join('\n') }}"
    dest: "output.csv"

output.csv的内容为:

1, a
2, b
3, c