Creating Security group with VPC for cross region peering in terraform

83 Views Asked by At

I want to create security groups for each vpc in cross region using terraform below are the terraform files I am using

"securitygroup.tf"

locals {
  vpcs = ["aws_vpc.vpc_useast.id", "aws_vpc.vpc_uswest.id"]
}

resource "aws_security_group" "alb_security_group" {  
  for_each = toset(local.vpcs)  

    name        = "alb security group"
    description = "enable ssh/http/https access on port 80/443"
    vpc_id      = each.value
    
    ingress {
    }
    
    egress {
    }

    tags = {
      Name = "allow_SSH_HTTP_HTTPS"
    }
    provider = aws.us-east-2
}

"vpc.tf"

resource "aws_vpc" "vpc_useast" {
  cidr_block = "20.0.0.0/16"
  tags = {
    Name = "TF-LB-VPC-A"
  }
}

"provider.tf"

provider "aws" {
  region     = "us-east-1"
}
provider "aws" {
  alias      = "us-east-2"
  region     = "us-east-2"
}

After executing getting the following error Error: creating Security Group (alb security group): InvalidVpcID.NotFound: The vpc ID 'aws_vpc.vpc_useast.id' does not exist status code: 400, request id: 72eefd3b-5316-4693-964e-08dfe55a2b0a

   with aws_security_group.alb_security_group1["aws_vpc.vpc_useast.id"],
   on securitygroup.tf line 9, in resource "aws_security_group" "alb_security_group1":
    9: resource "aws_security_group" "alb_security_group1" { 

Please help

1

There are 1 best solutions below

2
Cloudlady On

The problem is with the local values definition:

locals {
  vpcs = ["aws_vpc.vpc_useast.id", "aws_vpc.vpc_uswest.id"]
}

When you put the double quotes, the Terraform looks at the value as a string with the text inside the quotes. Meaning, the IDs you have passed to the function are: aws_vpc.vpc_useast.id and aws_vpc.vpc_uswest.id, and not the actual ids.

To resolve this issue you need to remove the double quotes so the variables will point to the actual IDs.