aRTURIUS
aRTURIUS

Reputation: 1370

Update existing security group when creating new ec2 CloudFormation

I have ec2 instance which was created using such cfn template:

Parameters:

"VPCId": {
    "Type":  "AWS::EC2::VPC::Id"
    "Description": "The VPC Id to where this instance is being created"
}
"Subnet": {
  "Description": "Subnet to put Instance",
  "Type": "AWS::EC2::Subnet::Id",
},

Have the following Security Group:

"InstanceSecurityGroup": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupDescription": "Enables access to instance by port 80",
        "VPCId": {
            "Ref": "VPCId"
        },
        "SecurityGroupIngress": [
          {
            "IpProtocol": "tcp",
            "FromPort": "80",
            "ToPort": "80",
            "CidrIp": {
              "Ref": "ClientCIDR"
            }
          }
        ]
      },

And part of Instance Resource:

"WebServer": {
  "Type": "AWS::EC2::Instance",
  "Properties": {
    "IamInstanceProfile": "access-profile",
    "SecurityGroupIds": [
      { "Fn::GetAtt": [
          "InstanceSecurityGroup",
          "GroupId"
        ]
      }
    ],
    "SubnetId": {
      "Ref": "Subnet"
    },

I want to create a few another instances using another template. This instances should have access to the above instance by port 22 and connect to it in UserData.

I'm not sure how it can be organized, the one way i see is update security group using aws cli through UserData before establishing ssh connection to the first instance. How it can be organized using resources? I didn't find any information or examples regarding this. Please help! Thanks!

Upvotes: 1

Views: 2358

Answers (1)

spg
spg

Reputation: 9827

You can modify the InstanceSecurityGroup to allow access from the other instances:

"InstanceSecurityGroup": {
  "Type": "AWS::EC2::SecurityGroup",
  "Properties": {
    "GroupDescription": "Enables access to instance by port 80",
    "VPCId": {
        "Ref": "VPCId"
    },
    "SecurityGroupIngress": [
      {
        "IpProtocol": "tcp",
        "FromPort": "80",
        "ToPort": "80",
        "CidrIp": {
          "Ref": "ClientCIDR"
        }
      },
      {
        "IpProtocol": "tcp",
        "FromPort": "22",
        "ToPort": "22",
        "SourceSecurityGroupId": {
          "Ref": "OtherInstancesSecurityGroup"
        }
      }
    ]
  },

where OtherInstancesSecurityGroup is a new Security Group you will assign the the other instances.

Upvotes: 2

Related Questions