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

Time:03-06

How to iterate module output from a loop in ansible and capture particular value to be redirected to a file. Example: 'amazon-ssm-agent.service']['state']": "running" should be pushed to a file locally.

[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"
}

CodePudding user response:

Say you want to output those services status into a file, you may use something like this:

- 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

Would give you:

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

Or, if you want one file per service:

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

Which gives:

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

CodePudding user response:

If you need the quotation and parenthesis from the example (I balanced the beginning)

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

the Jinja below should create it. For example, given myServiceName: [ssh, xen]

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

creates the file

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