Search code examples
terraformamazon-vpcterraform-provider-awsaws-security-group

Terraform - Authorizing Security Groups Between VPC Peering Connection


I am running on AWS and I have VPC-A and VPC-B I have a VPC peering between the two VPCs

I want to allow traffic from SecurityGroupB which is in VPC-B to SecurityGroupA in VPC-A

Up until now I did it with the ruby client with the following call

        security_group_a.authorize_ingress(
          ip_permissions: [
            {
              from_port: "-1",
              ip_protocol: "-1",
              to_port: "-1",
              user_id_group_pairs: [
                {
                  description: "Accept all traffic from SecurityGroupB",
                  group_id: security_group_b.id,
                  vpc_id: vpc_b.id,
                  vpc_peering_connection_id: peering_connection_id,
                },
              ],
            },
          ]
        )

I had a look at terraform's aws_security_group_rule but couldn't find anything equivalent to the settings described above.

When I try to just put the security group B in the ingress of security group A I get the following error:

Error: Error authorizing security group rule type ingress: InvalidGroup.NotFound: You have specified two resources that belong to different networks

what am I doing wrong here? how can I create a ruleto allow traffic from security group on VPC B into a security group on VPC A, assuming I have a peering connection set up?


Solution

  • Security group rules can reference security groups in peered VPCs if the following conditions are met:

    1. The VPCs must be in the same region
    2. The peering connection must be in the active state
    3. If the peered VPC is in another account, the reference must include the account number as a prefix. For example, 123456789012/sg-1a2b3c4d.

    So long as these conditions are met, you should have no problem.

    Here's an example of how a Terraform resource would look:

    resource "aws_security_group_rule" "example" {
      type                     = "ingress"
      from_port                = 0
      to_port                  = 65535
      protocol                 = "tcp"
      security_group_id        = "sg-123456"
      source_security_group_id = "sg-789012"
    }