如何迭代循环 Ansible 的模块输出并仅捕获特定值

How iterate module output from a loop Ansible and capture particular value only

如何从 ansible 中的循环迭代模块输出并捕获要重定向到文件的特定值。示例:'amazon-ssm-agent.service']['state']":"运行" 应推送到本地文件。

[ansibleadm@node1 ~]$ cat myloops3.yaml
---
-  name: collect service status remotely
   hosts: remote
   become: yes
   roles:
     - role: myServices
       myServiceName:
         - amazon-ssm-agent.service
         - cloud-init-local.service
[ansibleadm@node1 ~]$ cat roles/myServices/tasks/main.yml
---
# tasks file for myServices
-   name: collect systemd info
    service_facts:

-   name: cross verify service is runnng or not
    debug:
       var: ansible_facts.services['{{ item }}']['state']
    loop: "{{ myServiceName }}"
[ansibleadm@node1 ~]$

## Outputs ##

TASK   [myServices : cross verify service is runnng or not] 
*****************************************************************

ok:   [3.109.201.79] => (item=amazon-ssm-agent.service) => {
         "ansible_facts.services['amazon-ssm-agent.service']['state']": "running",
         "ansible_loop_var": "item",
         "item": "amazon-ssm-agent.service"
}
ok:   [3.109.201.79] => (item=cloud-init-local.service) => {
         "ansible_facts.services['cloud-init-local.service']['state']": "stopped",
         "ansible_loop_var": "item",
         "item": "cloud-init-local.service"
}

假设你想将这些服务状态输出到一个文件中,你可以使用这样的东西:

- name: collect systemd info
  service_facts:

- name: cross verify service is runnng or not
  copy:
    content: |
      {% for s in myServiceName %}{{ s }}={{ ansible_facts.services[s]['state'] }}
      {% endfor %}
    dest: /tmp/test.txt

会给你:

$> cat /tmp/test.txt
amazon-ssm-agent.service=running
cloud-init-local.service=running

或者,如果您希望每个服务一个文件:

- name: cross verify service is runnng or not
  loop: "{{ myServiceName }}"
  copy:
    content: |
      {{ ansible_facts.services[item]['state'] }}
    dest: "/tmp/{{ item }}.txt"

给出:

$> cat /tmp/amazon-ssm-agent.service.txt
running

如果你需要例子中的引文和括号(我平衡了开头)

Example: "['amazon-ssm-agent.service']['state']": "running"

下面的 Jinja 应该创建它。例如,给定 myServiceName: [ssh, xen]

    - service_facts:
    - copy:
        content: |
          {% for s in myServiceName %}
          "['{{ s }}']['state']": "{{ ansible_facts.services[s]['state'] }}"
          {% endfor %}
        dest: /tmp/test.txt

创建文件

shell> cat /tmp/test.txt 
"['ssh']['state']": "running"
"['xen']['state']": "running"