Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referring to resources named with variables in Terraform

Tags:

I'm trying to create a module in Terraform that can be instantiated multiple times with different variable inputs. Within the module, how do I reference resources when their names depend on an input variable? I'm trying to do it via the bracket syntax ("${aws_ecs_task_definition[var.name].arn}") but I just guessed at that.

(Caveat: I might be going about this in completely the wrong way)

Here's my module's (simplified) main.tf file:

variable "name" {}  resource "aws_ecs_service" "${var.name}" {     name = "${var.name}_service"     cluster = ""     task_definition = "${aws_ecs_task_definition[var.name].arn}"     desired_count = 1 }  resource "aws_ecs_task_definition" "${var.name}" {     family = "ecs-family-${var.name}"     container_definitions = "${template_file[var.name].rendered}" }  resource "template_file" "${var.name}_task" {     template = "${file("task-definition.json")}"      vars {         name = "${var.name}"     } } 

I'm getting the following error:

Error loading Terraform: Error downloading modules: module foo: Error loading .terraform/modules/af13a92c4edda294822b341862422ba5/main.tf: Error reading config for aws_ecs_service[${var.name}]: parse error: syntax error 
like image 805
Mike Ottum Avatar asked Jul 27 '16 17:07

Mike Ottum


2 Answers

I was fundamentally misunderstanding how modules worked.

Terraform does not support interpolation in resource names (see the relevant issues), but that doesn't matter in my case, because the resources of each instance of a module are in the instance's namespace. I was worried about resource names colliding, but the module system already handles that.

like image 107
Mike Ottum Avatar answered Sep 30 '22 18:09

Mike Ottum


The picture below shows what is going on.

The terraform documentation does not make their use of "NAME" clear versus the "name" values that are used for the actual resources created by the infrastructure vender (like, AWS or Google Cloud).

Additionally, it isn't always "name=, but sometimes, say, "endpoint= or even "resource_group_name= or whatever.

And there are a couple of ways to generate multiple "name" values -- using count, variables, etc., or inside tfvar files and running terraform apply -var-file=foo.tfvars

terraform resource

like image 45
warrens Avatar answered Sep 30 '22 18:09

warrens