Ansible set_fact with with_items always prints last item

Hi Experts,

I am looking to capture certain service status using ansible the problem is debug prints only last item.Below is the expected output.

Hostname : test

httpd → Running
ntpd → Running

Below are the playbook.

Hi Experts,

I am looking to capture certain service status using ansible the problem is debug prints only last item.Below is the
expected output.

Hostname : test

httpd --> Running
ntpd --> Running

Below are the playbook.

---
- hosts: test
become: true
gather_facts: false
tasks:
- name: Service facts
service_facts:

\- set\_fact:
   elk\_app1: "\{\{ ansible\_facts\.services\[item \+ '\.service'\]\.name\}\} Running"
  when: ansible\_facts\.services\[item \+ '\.service'\]\.state == 'running'
  with\_items:
    \- httpd
    \- ntpd
  register: foo\_result

\- debug: msg="\{\{ foo\_result \}\}"

Regards
Kumar

Hello Kumar,

if you use set_fact with a loop, you need to reference the variable on the right hand side:

set_fact:
  elk_app1: "{{ elk_app1 | default('') + ansible_facts.services[item + '.service'].name + ' Running\n' }}"

The default filter is necessary as the variable is undefined on the first iteration of the loop.

Regards
   Racke

Hi Brae,

Thanks for the help was able to get the desired output.But the output are in same line is there way to print new line for each service?

TASK [debug] ***********************************************************************************************************************************************************
ok: [test] => {
“msg”: “httpd.service Running\nntpd.service Running\n”
}

Expected output:

httpd.service Running
ntpd.service Running

Regards
Kumar

Hi Brae,

Thanks for the help was able to get the desired output.But the output are in same line is there way to print new line
for each service?

TASK [debug]
***********************************************************************************************************************************************************
ok: [test] => {
"msg": "httpd.service Running\nntpd.service Running\n"
}

Expected output:

httpd.service Running
ntpd.service Running

Regards
Kumar

Hello Kumar,

use the YAML callback plugin, e.g in ansible.cfg:

# Use the YAML callback plugin.
stdout_callback = yaml

This changes the output to look like as follows:

ok: [buster-test-box] =>
  elk_app1: |-
    sympa.service Running
    wwsympa.service Running

Regards
         Racke