I'm trying to set multiple security groups at once using the ansible cloud stack module. The yaml file currently looks like this:

- name: add inbound tcp rules to security group web
  cs_securitygroup_rule:
  security_group: web
  start_port: "{{ item }}"
  end_port: "{{ item }}"
  loop:
    - 80
    - 443

The problem is there could be a vast number of security groups. So this code block would repeat over and over again, which seems not like a good solution. So I'd like to turn this whole thing into one single loop and pass the arguments using dictionaries. The datastructure cloud look something like this:

cs_security_groups:
  web:
    - 80
    - 443
  monitor:
    - 9090
    - 9100
    - 9333
  default:
    - 22

I simply can't get this to work using any kind of loop because a security group could have an arbitrary number of ports. Am I missing something or is this approach completely wrong?

I kind of solved the issue.

- name: add inbound port(s) to the security groups
  cs_securitygroup_rule:
    security_group: "{{ item.0.key }}"
    port: "{{ item.1 }}"
  loop: "{{ cs_security_groups | dict2items | subelements('value') }}"

This works, but there may be a better solution. :-)

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.