Looping through list/array values

Hello Everyone,

I’m new to Ansible/yaml and have been trying to develop some basic playbooks to assist with some simple deployment/verification tasks. I have a simple playbook/play that is using the uri module to make a connection to websites - I’d like to be able to output the name of the website that the play connected to and the status of the connection attempt.

I’ve found that the values I’m trying to reference (from the playbook below) are webpage.results[].url and webpage.results[].status. I can type in a debug message that prints the values when I know the number of entries, but my goal is to have a dynamic list, so I wouldn’t know how many sites to iterate through to print the results.

Here’s the playbook:

webpage.results is a list and with_items takes a list.

  - debug: msg="The result of {{ item.url }} is {{ item.status }}"
    with_items: '{{ webpage.results }}'

I’ve found that using a template has solved my general issue - the only thing I’m trying to figure out is how to insert a carriage return or new line for each result:

  • debug:
    msg: “{% set output = %}
    {% for result in webpage.results %}
    {{output.append('Website: ’ + result.url + ’ got status ’ + result.status|string + ‘.’ )}}
    {% endfor %}
    {{output}}”

You are here creating a variable output that is a list each element contains "Website: X got status Y."
Since this is a list adding newline doesn't make sense.

If you are just trying to print out a nice output on screen you can use multiline yaml.

  - debug:
      msg: |
        {% for result in webpage.results %}
        Website: {{ result.url }} got status {{ result.status }}.
        {% endfor %}