Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform using count.index in a resource name

Tags:

terraform

using terraform i'm trying to include the count in the name of my resource using count.index, but unable to get the count to display. I'm basically looking to add the count to the resource name so that the resource can be found, otherwise the resource is unknown.

count = 3    
autoscaling_group_name = "${aws_autoscaling_group.exampleautoscaling-("count.index")-example.name}"

ERROR

resource variables must be three parts: TYPE.NAME.ATTR in:

expected is : exampleautoscaling-1-example.name,exampleautoscaling-2-example.name,exampleautoscaling-3-example.name
like image 691
hhh0505 Avatar asked Aug 16 '18 17:08

hhh0505


People also ask

How do you use count resource Terraform?

How to use Terraform Count. We use count to deploy multiple resources. The count meta-argument generates numerous resources of a module. You use the count argument within the block and assign a whole number (could by variable or expression), and Terraform generates the number of resources.

What is Count Index Terraform?

When count is set, Terraform distinguishes between the block itself and the multiple resource or module instances associated with it. Instances are identified by an index number, starting with 0 . <TYPE>. <NAME> or module.

Can I use count and For_each in Terraform?

What is count in Terraform? When you define a resource block in Terraform, by default, this specifies one resource that will be created. To manage several of the same resources, you can use either count or for_each , which removes the need to write a separate block of code for each one.

How do you count a list in Terraform?

you can use terraform built-in function length() to get the count.


2 Answers

My suggestion will be to add tags and use name_prefix arguments. But specific to your question

Here are some snippets from the documentation what you can try

"${var.hostnames[count.index]}"

OR

resource "aws_instance" "web" {
  # ...

  count = "${var.count}"

  # Tag the instance with a counter starting at 1, ie. web-001
  tags {
    Name = "${format("web-%03d", count.index + 1)}"
  }
}

Providing the link here. Look under the Math section.

like image 83
Sorabh Mendiratta Avatar answered Sep 23 '22 12:09

Sorabh Mendiratta


Your syntax is incorrect. You are trying to insert count into the middle of a resource name. You need to change it to be the following:

count = 3    
autoscaling_group_name = "${aws_autoscaling_group.exampleautoscaling.name}-${count.index}"
like image 20
Jamie Avatar answered Sep 24 '22 12:09

Jamie