1

I am trying to use Terraform to create a single security group that will allow traffic for mongo on port 27017 from all my private subnets that are stored in a variable. My issue is I am unsure how this would work since I only want one SG but the foreach creates multiple - at least it did before with subnets

my variable

variable "subnet_numbers_private" {
  description = "Useless info"
  default     = {
    "us-east-1a" = 1
    "us-east-1b" = 2
    "us-east-1c" = 3
  }
}

my security group resource

resource "aws_security_group" "mongo" {
  for_each = var.subnet_numbers_private
  name        = "Mongo"
  description = "Allow mongo traffic"
  vpc_id      = aws_vpc.Main_VPC.id

  ingress {
    from_port   = 27017
    to_port     = 27017
    protocol    = "tcp"
    cidr_blocks = [cidrsubnet(aws_vpc.Main_VPC.cidr_block, 8, each.value)]
  }

  tags = {
    Name = "Mongo-${each.key}"
  }
}

Currently this just provides an error that doesn't mean much to me as I don't know TF 0.12 well enough

Because aws_security_group.mongo has "for_each" set, its attributes must be
accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    aws_security_group.mongo[each.key]
1

Figured out the answer, fourtinately for me I had missed the example in the blog post about terraform 0.12 linked below

Here is my final (working how I want) security group

resource "aws_security_group" "mongo" {
  name        = "Mongo"
  description = "Allow mongo traffic"
  vpc_id      = aws_vpc.Main_VPC.id

  ingress {
    from_port   = 27017
    to_port     = 27017
    protocol    = "tcp"
    cidr_blocks = [
      for num in var.private_subnet_numbers:
      cidrsubnet(aws_vpc.Main_VPC.cidr_block, 8, num)
    ]
  }

  tags = {
    Name = "Mongo"
  }
}

Link to blog post about foreach - https://www.hashicorp.com/blog/hashicorp-terraform-0-12-preview-for-and-for-each/

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.