4

Instead of having to set ingress and egress rules, how do I reference existing EC2 security groups in a CloudFormation Template?

   Resources:
      EC2Instance:
        Type: AWS::EC2::Instance
        Properties:
          InstanceType:
            Ref: InstanceType
          SecurityGroups:
          - Ref: InstanceSecurityGroup
          KeyName:
            Ref: KeyName
          ImageId:
            Fn::FindInMap:
            - AWSRegionArch2AMI
            - Ref: AWS::Region
            - Fn::FindInMap:
              - AWSInstanceType2Arch
              - Ref: InstanceType
              - Arch
      InstanceSecurityGroup:
        Type: AWS::EC2::SecurityGroup
        Properties:
          GroupDescription: Existing Groups
          SecurityGroupIds:
          - Ref: sg-12345
          - Ref: sg-12312

  SecurityGroupIngress:
  - IpProtocol: tcp
    FromPort: 80
    ToPort: 80
    CidrIp: 0.0.0.0/0
  SecurityGroupEgress:
  - IpProtocol: tcp
    FromPort: 80
    ToPort: 80
    CidrIp: 0.0.0.0/0
rumplesmyboy
  • 109
  • 1
  • 7

1 Answers1

2

To do this you just add them in your EC2 Resource property directly under SecurityGroupIds:

Resources:
    EC2Instance:
        Type: AWS::EC2::Instance
        Properties:
            InstanceType:
                Ref: InstanceType
            SecurityGroupIds:
              - sg-12345
              - sg-12312
            KeyName: 
                Ref: KeyName
            ImageId: 
                Fn::FindInMap:
                - AWSRegionArch2AMI
                - Ref: AWS::Region
                - Fn::FindInMap:
                  - AWSInstanceType2Arch
                  - Ref: InstanceType
                  - Arch
rumplesmyboy
  • 109
  • 1
  • 7