Newbie to Ansible - need help on Ansible loop

Hi, i’m new to ansible and trying to create a simple script to check for one of the host services e.g systemctl status hostA{0…3}. Script is to check the status of the services whether it is active or inactive. I’m trying to convert it using ansible script so that it can run through multiple hosts. initial draft as follow

- name: Confirm host services state
hosts: <host>
gather_facts: false
become: true
order: sorted

tasks:
- name: Run check
ansible.builtin.systemd:
name: hostA{{ item }}
loop: "{{ range(0, 4) }}"
register: reg_hostA


- name: Print result
ansible.builtin.debug:
var: reg_hostA.status.ActiveState

Result of the run
===============
ok: [hostA.2] =>
reg_hostA.status.ActiveState: VARIABLE IS NOT DEFINED!
ok: [hostA.1] =>
reg_hostA.status.ActiveState: VARIABLE IS NOT DEFINED
  • tried to use the build in shell but ansible lint is not happy and need to make use of the builtin.systemd.
  • did go through the ansible documentation on loop but still unsure how to print out the output correctly / issue with the variable not defined. Some guidelines and assistance would be great. Many thanks in advanced.

Try this way instead.

- name: Confirm host services state
  hosts: <host>
  gather_facts: false
  become: true
  order: sorted

  tasks:
    - name: Run check
      ansible.builtin.systemd:
        name: "hostA{{ item }}"
      loop: "{{ range(0, 4) | list }}"
      register: reg_hostA

    - name: Print result
      ansible.builtin.debug:
        msg: "Service hostA{{ item.item }} is {{ item.status.ActiveState }}"
      loop: "{{ reg_hostA.results }}"
      loop_control:
        label: "{{ item.item }}"

Thanks Vijayakumar for the guide. learned something new that the list needs to be included to output the loop result.

As a more general tip: have a read on this page → Loops — Ansible Community Documentation

There’s even more tricks there you can use to enhance loops and add more logic to them if you need it :slight_smile:

1 Like