Ansible 在本地打印远程配置

Ansible print remote config locally

我正在尝试使用 Ansible 在多个服务器上找到具有不同值的类似设置,然后通过 CSV 在我的系统上本地输出。问题是 Ansible 只会向文件输出一行,即使它找到并组装了甚至说它从每个服务器创建了两行。

因此,示例设置:

Server1
file.conf
key=value1

Server2
file.conf
key=value2

Local
result.txt

---
# ansible-playbook pb-get-file.yml -i inventory --limit=server1,server2
- name: Playbook to get a list of all file values
  hosts: all
  gather_facts: no

  tasks:
  - name: Find the status and targetUri of the nested DS Served
    find:
      paths: 
        - /opt/
        - /etc/
      recurse: yes
      contains: '.*key.*'
      patterns: '*file.conf'
    register: ds_status
    become: yes
  
  - name: Get values
    shell:
      cmd: "awk '/key/{print $NF}' {{ item.path }}"
    register: r
    with_items: "{{ ds_status.files }}"
    become: yes
    when: ds_status.matched > 0

  - name: Save results
    lineinfile:
      line: "{{ item.0 }}, {{ item.1.path }}, {{ item.2.stdout }}"
      path: result.txt
      create: yes
    with_items: "{{ result_line }}"
    delegate_to: localhost
    with_together:
      - "{{ inventory_hostname }}"
      - "{{ ds_status.files }}"
      - "{{ r.results }}" 
    when: ds_status.matched > 0 

run_onceloop ansible_play_hosts_all 在任务“保存结果”中。例如,给定文件

shell> ssh admin@test_11 cat /opt/file.conf
key1=value1
key2=value2
key3=value3

shell> ssh admin@test_12 cat /opt/file.conf
key1=value1
key2=value2
key3=value3

shell> ssh admin@test_13 cat /opt/file.conf
key1=value1
key2=value2
key3=value3

您的行动手册包含以下修改后的任务

    - name: Save results
      debug:
        msg: |
          {{ item }},
          {{ hostvars[item].r.results.0.item.path }},
          {{ hostvars[item].r.results.0.stdout }}
      loop: "{{ ansible_play_hosts_all }}"
      delegate_to: localhost
      run_once: true

给予

ok: [test_11 -> localhost] => (item=test_11) => 
  msg: |-
    test_11,
    /opt/file.conf,
    key1=value1
    key2=value2
    key3=value3
ok: [test_11 -> localhost] => (item=test_12) => 
  msg: |-
    test_12,
    /opt/file.conf,
    key1=value1
    key2=value2
    key3=value3
ok: [test_11 -> localhost] => (item=test_13) => 
  msg: |-
    test_13,
    /opt/file.conf,
    key1=value1
    key2=value2
    key3=value3

循环中每个远程主机只显示一个文件。在下一次迭代中保存循环 include_tasks 中的所有文件。