Ansible – loop over netsted variables

I’ve started using Ansible at my work, where we use it to deploy Splunk environments.

One of the things I needed to do is to provide a list of tcp ports to a “with_items” statement in a form of list.

I have this vars file and I needed to filter out only the TCP ports

port:
  dns:
    tcp: 5001
    udp: 5002
  dual:
    tcp: 6001
    udp: 6002
  relay:
    tcp: 7001
    udp: 7002

So here is how you can do it (in 2 steps) in Ansible.

    - name: set_fact
      set_fact:
        tcp_ports: "{% for feed in port %}{{ port[feed]['tcp'] }},{% endfor %}"

    - name: print tcp ports
      debug:
        msg: "{{ item }}"
      with_items:
      - "{{ (tcp_ports| regex_replace(',', '')).split (',') | list }}"

Of course you can replace the debug msg with whatever other action you need.
By the way, if you know how to do it in a single step please let me know.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.