RaghuCK
RaghuCK

Reputation: 125

Terrafrom datasource aws_vpcs - count.index error

I am trying to use data source aws_vpcs to get the vpc id having specific tag.

For reference: https://www.terraform.io/docs/providers/aws/d/vpcs.html

Below is my terraform yaml file. Terrafrom version used is: 0.12.3

data "aws_vpcs" "foo" {
  tags = {
    Name = "test1-VPC"
  }
}

resource "aws_security_group" "cluster" {
  count = "${length(data.aws_vpcs.foo.ids)}"
  vpc_id = "${tolist(data.aws_vpcs.foo.ids)[count.index]}"
}

resource "aws_security_group_rule" "cluster-ingress-node-https" {
  description              = "Rule to do xyz"
  from_port                = 443
  protocol                 = "tcp"
  security_group_id        = "${aws_security_group.cluster.id}"
  to_port                  = 443
  type                     = "ingress"
}

I am getting below error. Request for help to fix this

terraform plan

Error: Missing resource instance key

  on modules/eks/eks-cluster.tf line 40, in resource "aws_security_group_rule" "cluster-ingress-node-https":
  40:   security_group_id        = "${aws_security_group.cluster.id}"

Because aws_security_group.cluster has "count" set, its attributes must be
accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    aws_security_group.cluster[count.index]

Upvotes: 0

Views: 4653

Answers (3)

rocky
rocky

Reputation: 163

I know this was posted a while ago. Stumbled upon this issue.

${aws_security_group.cluster.*.id} should do it.

Since the resource aws_security_group is creating multiple security groups with count, resource block aws_security_group_rule needs to reference the correct index in the list.

Upvotes: 1

Ashutosh Angiras
Ashutosh Angiras

Reputation: 51

You will need to convert the list of security group. Terraform provides flatten function to do that https://nedinthecloud.com/2018/07/16/terraform-fotd-flatten/ You should not get this error afterwards

Upvotes: 1

Blokje5
Blokje5

Reputation: 5023

You are creating a list of aws_security_group as you are using count on the aws_security_group resource. The error even mentions it:

Because aws_security_group.cluster has "count" set, its attributes must be accessed on specific instances.

So either you need to include count on the aws_security_group_rule resource and create one aws_security_group_rule for each aws_security_group created, or in the case you expect only one VPC to be returned, create only one aws_security_group by accessing the returned aws_vpcs.foo.ids with index 0.

Upvotes: 1

Related Questions