Create Security Group by dynamically assigning EC2 Instance's privateIP as inbound rule using AWS cloud formation Template

35 Views Asked by At

I have tried below template,but it is giving error as below

Here I am trying to launch 2 Instances MyEC2Instance1 and MyEC2Instance2 and creating a security group that should allow access from MyEC2Instance2

Cloud Formation Template to launch EC2 instance and Security group:

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  SourceAccountId:
    Type: String
    Description: "AWS Account ID where the AMIs are shared from"
  SourceAmis:
    Type: List<String>
    Description: "List of shared encrypted AMI IDs"
  VpcId:
    Type: String
    Description: "VPC ID where the security groups will be created."

Resources:
  MyEC2Instance1:
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: !Select [0, !Ref SourceAmis]  # Select the first AMI from the list
      InstanceType: t2.micro
      KeyName: New_Test_PIM
      SubnetId: subnet-xxxxxxxxxxxx
      Tags:
        - Key: Name
          Value: "Test_1_EC2"

  MyEC2Instance2:
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: !Select [1, !Ref SourceAmis]  # Select the second AMI from the list
      InstanceType: t2.micro
      KeyName: New_Test_PIM
      SubnetId: subnet-xxxxxxxxxxxxx
      Tags:
        - Key: Name
          Value: "Test_2_EC2"

  MyEIP:
    Type: 'AWS::EC2::EIP'

  MySecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    DependsOn: MyEC2Instance2
    Properties:
      GroupDescription: "Allow traffic from MyEC2Instance2s private IP"
      VpcId: !Ref "VpcId"

  MySecurityGroupIngress:
    Type: 'AWS::EC2::SecurityGroupIngress'
    DependsOn: MySecurityGroup
    Properties:
      GroupId: !GetAtt MySecurityGroup.GroupId
      IpProtocol: tcp
      FromPort: 22
      ToPort: 22
      CidrIp: !Sub "{{MyEC2Instance2.PrivateIpAddresses[0]}}/32"
      Description: "Inbound Rule 1"

Error:

CIDR block {{MyEC2Instance2.PrivateIpAddresses[0]}}/32 is malformed (Service: AmazonEC2; Status Code: 400; Error Code: InvalidParameterValue; Request ID: dd12c2d9-fe00-481d-b267-d6ad355ab2b0; Proxy: null)

Can anyone please help me with how can I dynamically assign Instance IP address to security group inbound rule?

1

There are 1 best solutions below

1
John Rotenstein On

The 'more correct' way is to create two separate security groups:

  • SG1 for MyEC2Instance1
  • SG2 for MyEC2Instance2

You can then configure an Inbound rule on SG1 that permits inbound traffic from SG2. Any resource that is associated with SG2 would be granted Inbound access to any resource associated with SG1. In this situation, MyEC2Instance2 would be granted Inbound access to MyEC2Instance1.

The benefit of referring to other Security Groups is that the individual instances can be replaced with other instances without needing to change the referenced IP address in the security group.