3
votes

I am trying to create a Security Group using terraform module terraform-aws-modules/security-group/aws. This would need vpc id which is taken from aws_vpcs data source. The vpc id requires a string value, but the aws_vpcs data source returns a list with a single value. Please find

-

data "aws_vpcs" "this" {
  tags = {
    "Name" = "example"
  }
}

module "route53_sg" {
  source = "terraform-aws-modules/security-group/aws"

  name        = "R53_health_checkers"
  description = "Security group for Route53 health checkers"
  vpc_id      = element([data.aws_vpcs.this.ids], 0)
  ingress_cidr_blocks = [
...
...
...
  ]
  ingress_rules = ["https-443-tcp"]
}




$ terraform apply
data.aws_lb.ext_alb: Refreshing state...
data.aws_vpcs.this: Refreshing state...

Error: Invalid value for module argument

  on main.tf line 75, in module "route53_sg":
  75:   vpc_id      = element([data.aws_vpcs.this.ids], 0)

The given value is not suitable for child module variable "vpc_id" defined at
.terraform/modules/route53_sg/terraform-aws-modules-terraform-aws-security-group-d55e4de/variables.tf:10,1-18:
string required.



vpc_id is expecting a Single string. FOLLOWING is a result from Output.tf

$ terraform apply
data.aws_lb.ext_alb: Refreshing state...
data.aws_vpcs.this: Refreshing state...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

vpc = [
  "vpc-08067a598522a7b30",
]
1

1 Answers

4
votes

data.aws_vpcs.this.ids is already a list, you don't need to put it into another list.

Try:

vpc_id = element(data.aws_vpcs.this.ids, 0)

EDIT: Answering questions from the comment: It seems like the ids returned is a set instead of a list, as mentioned in a similar issue here: https://github.com/terraform-providers/terraform-provider-aws/issues/7522

If you are using 0.12.x: You can do

vpc_id = element(tolist(data.aws_vpcs.this.ids), 0)

If you are using 0.11.x: You can do

vpc_id = element(split(",", join(",", data.aws_vpcs.this.ids))), 0)