How to use dynamic resource names in Terraform?

hey picture hey · Sep 21, 2017 · Viewed 15.3k times · Source

I would like to use the same terraform template for several dev and production environments.

My approach: As I understand it, the resource name needs to be unique, and terraform stores the state of the resource internally. I therefore tried to use variables for the resource names - but it seems to be not supported. I get an error message:

$ terraform plan
var.env1
  Enter a value: abc

Error asking for user input: Error parsing address 'aws_sqs_queue.SqsIntegrationOrderIn${var.env1}': invalid resource address "aws_sqs_queue.SqsIntegrationOrderIn${var.env1}"

My terraform template:

variable "env1" {}

provider "aws" {
        region = "ap-southeast-2"
}

resource "aws_sqs_queue" "SqsIntegrationOrderIn${var.env1}" {
        name = "Integration_Order_In__${var.env1}"
        message_retention_seconds = 86400
        receive_wait_time_seconds = 5
}

I think, either my approach is wrong, or the syntax. Any ideas?

Answer

Farid Nouri Neshat picture Farid Nouri Neshat · Sep 22, 2017

You can't interpolate inside the resource name. Instead what you should do is as @BMW have mentioned in the comments, you should make a terraform module that contains that SqsIntegrationOrderIn inside and takes env variable. Then you can use the module twice, and they simply won't clash. You can also have a look at a similar question I answered.