ec2_group, are circular dependencies possible

I am trying to recreate some SGs (that were created manually) that have circular dependencies.

eg,

sg1: out sg2
sg2: in sg1

I can’t see how this is possible with ansible.

Answer: Yes, it is possible. First you must “declare” the group using purge_rules*=false and then add the actual rules.

For example:

  • name: Declare api-service ELB security group
    ec2_group:
    name: “{{env_prefix}}api-service-elb”
    description: API Service ELB security group
    vpc_id: “{{ec2_vpc_id}}”
    purge_rules: false
    purge_rules_egress: false

  • name: Declare api-service security group
    ec2_group:
    name: “{{env_prefix}}api-service”
    description: API Service security group
    vpc_id: “{{ec2_vpc_id}}”
    purge_rules: false
    purge_rules_egress: false

  • name: Define api-service ELB security group
    ec2_group:
    name: “{{env_prefix}}api-service-elb”
    description: API Service ELB security group
    vpc_id: “{{ec2_vpc_id}}”
    rules:

  • proto: tcp
    from_port: 443
    to_port: 443
    cidr_ip: 0.0.0.0/0
    rules_egress:

  • proto: tcp
    from_port: 443
    to_port: 443
    group_name: “{{env_prefix}}api-service”

  • name: Define api-service security group rules
    ec2_group:
    name: “{{env_prefix}}api-service”
    description: API Service security group
    vpc_id: “{{ec2_vpc_id}}”
    rules:

  • proto: tcp
    from_port: 443
    to_port: 443
    group_name: “{{env_prefix}}api-service-elb”

But while this works, the declare are always marked as changed so I needed to add ‘changed_when: false’ to those. Still I get changed every time for “Define api-service ELB security group” – not sure why yet.

Much better answer:

Digging thru the code I notice an option ‘group_desc’. It is used when creating a rule to a not yet created security group, where ansible will auto-create the security group. Then you can follow up and fill in the details.

So the above is greatly simplified to:

  • name: Declare api-service ELB security group
    ec2_group:
    name: “{{env_prefix}}api-service-elb”
    description: API Service ELB security group
    vpc_id: “{{ec2_vpc_id}}”
    rules:

  • proto: tcp
    from_port: 443
    to_port: 443
    cidr_ip: 0.0.0.0/0
    rules_egress:

  • proto: tcp
    from_port: 443
    to_port: 443
    group_name: “{{env_prefix}}api-service”
    group_desc: “{{api_sg_desc}}”

  • name: Declare api-service security group
    ec2_group:
    name: “{{env_prefix}}api-service”
    description: “{{api_sg_desc}}”
    vpc_id: “{{ec2_vpc_id}}”
    rules:

  • proto: tcp

from_port: 443
to_port: 443
group_name: “{{env_prefix}}api-service-elb”