Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CloudFormation - Security Group VPC issue

I have a template which creates an ELB and attaches an existing subnet within a VPC. This creates just fine but when I then update my stack and add a security group with a VpcId property with a value equal to the existing VPC ID in which my attached subnet belongs the stack fails with the following error:

"You have specified two resources that belong to different networks"

If I remove the VpcId property from my security group it creates it in my default VPC and the stack creation works. I cannot understand why this can be because the security group has a relationship to the ELB in the specified ingress rules -

"IpProtocol": "tcp",
            "FromPort": "8000",
            "ToPort": "8010",
            "SourceSecurityGroupOwnerId": {
              "Fn::GetAtt": [
                "ElasticLoadBalancer",
                "SourceSecurityGroup.OwnerAlias"
              ]
            },

I cannot explicitly state the VPC ID on the ELB as it has no such property, only Subnet or AZ.

like image 883
John Avatar asked Sep 07 '25 01:09

John


1 Answers

Thanks for your help guys. I found the issue and solved the problem.

The issue is that I am trying to reference one security group from another in the security group ingress definition within the security group definition. As the documentation says:

If you want to cross-reference two security groups in the ingress and egress rules of those security groups, use the AWS::EC2::SecurityGroupEgress and AWS::EC2::SecurityGroupIngress resources to define your rules. Do not use the embedded ingress and egress rules in the AWS::EC2::SecurityGroup. If you do, it causes a circular dependency, which AWS CloudFormation doesn't allow.

So, I specified my two security groups then specified a SecurityGroupIngress in a separate resource. This must be entered manually into the template as there is no CloudFormation icon from the left hand menu for this resource. It took a while to figure out because the error message generated when I created the stack doesn't make it obvious.

"InstanceIngress": {
  "Type": "AWS::EC2::SecurityGroupIngress",
  "Properties": {
    "GroupId": {
      "Fn::GetAtt": [
        "InstanceSecurityGroup",
        "GroupId"
      ]
    },
    "IpProtocol": "tcp",
    "FromPort": "7997",
    "ToPort": "8100",
    "SourceSecurityGroupId": {
      "Fn::GetAtt": [
        "ELBSecurityGroup",
        "GroupId"
      ]
    }
  },
like image 108
John Avatar answered Sep 10 '25 22:09

John