Execute command with items from inventory group

Hi everyone,

I’m looking to execute a command for each items in an inventory group - in this case for each item in a “staging-webservers” group, I want to allow access to it in the firewall.

This doesn’t seem to work but here is kind of what I want to do:


- name: Update firewall rules
command: sudo ufw allow proto tcp from $item to port 9200
with_items:
- [staging-webservers]

In addition if I wanted to write a list of hosts from a group into a template how can I do that?

Thanks in advance,

Alex

I think you want:

with_items: groups[‘staging-webservers’]

same var is available for templates to use:

{% for host in groups[‘staging-webservers’]%}
{{host}}
{%endfor%}

Thank you.

This worked for me:

  • name: Allow webservers access
    action: command /usr/sbin/ufw allow proto tcp from $item to any port 7474
    with_items:
  • ${groups.staging_webservers}

Also the above syntax is overkill :slight_smile:

with_items: groups.staging_webservers

Legacy variables are also bad!

action: command /usr/sbin/ufw allow proto tcp from $item to any port 7474

Should be

{{ item }}