---
resources:
    {% for sg in security_groups %}
    {% set sanitized_name=sg.name.replace('-','').replace('_','') %}
    {{sanitized_name}}:
      Type: "AWS::EC2::SecurityGroup"
      Properties:
        {% if sg.description %}
        GroupDescription: "{{sg.description}}"
        {% else %}
        GroupDescription: "{{_env.name}}:{{_env.stage}}:{{_layer.name}}"
        {% endif %}
        VpcId: {{vpc}}
        Tags:
            - Key: Name
              Value: {{sg.name}}
            {% if sg.description %}
            - Key: Description
              Value: "{{sg.description}}"
            {% endif %}
    {% if sg.egress_rules %}
    {% for rule in sg.egress_rules %}
    {{sanitized_name}}Egress{{loop.index}}:
      Type: "AWS::EC2::SecurityGroupEgress"
      Properties:
        GroupId:
            Ref: {{sanitized_name}}
        IpProtocol: {{rule.ip_protocol}}
        {% if rule.cidr_ip %}
        CidrIp: {{rule.cidr_ip}}
        {% endif %}
        {% if rule.from_port %}
        FromPort: {{rule.from_port}}
        {% endif %}
        {% if rule.to_port %}
        ToPort: {{rule.to_port}}
        {% endif %}
        {% if rule.source_security_group %}
        SourceSecurityGroupId: {{rule.source_security_group_id}}
        {% endif %}
    {% endfor %}  # Egress rule loop
    {% endif %}
    {% if sg.ingress_rules %}
    {% for rule in sg.ingress_rules %}
    {{sanitized_name}}Ingress{{loop.index}}:
      Type: "AWS::EC2::SecurityGroupIngress"
      Properties:
        GroupId:
            Ref: {{sanitized_name}}
        IpProtocol: {{rule.ip_protocol}}
        {% if rule.cidr_ip %}
        CidrIp: {{rule.cidr_ip}}
        {% endif %}
        {% if rule.from_port %}
        FromPort: {{rule.from_port}}
        {% endif %}
        {% if rule.to_port %}
        ToPort: {{rule.to_port}}
        {% endif %}
        {% if rule.source_security_group %}
        SourceSecurityGroupId: {{rule.source_security_group_id}}
        {% endif %}
    {% endfor %}  # Egress rule loop
    {% endif %}
    {% endfor %}  # Security group loop
