1
votes

I'm creating subnets as part of a seperate terraform template and exporting the IDs as follows.

output "subnet-aza-dev" {
  value = "${aws_subnet.subnet-aza-dev.id}"
}
output "subnet-azb-dev" {
  value = "${aws_subnet.subnet-azb-dev.id}"
}
output "subnet-aza-test" {
  value = "${aws_subnet.subnet-aza-test.id}"
}
output "subnet-azb-test" {
  value = "${aws_subnet.subnet-azb-test.id}"
}
...

I'm then intending to lookup these IDs in another template which is reused to provision multiple environments. Example below shows my second template is calling a module to provision an EC2 instance and is passing through the subnet_id.

variable "environment" {
    description = "Environment name"
    default     = "dev"
}

module "sql-1-ec2" {
  source     = "../modules/ec2winserver_sql"
  ...
  subnet_id  = "${data.terraform_remote_state.env-shared.subnet-aza-dev}" 
}

What I'd like to do is pass the environment variable as part of the lookup for the subnet_id e.g.

subnet_id  = "${data.terraform_remote_state.env-shared.subnet-aza-${var.environment}"

However I'm aware that variable interpolation isn't supported. I've tried using a map inside of the first terraform template to export them all to a 'subnet' which I could then use to lookup from the second template. This didn't work as I was unable to output variables inside of the map.

This sort of design pattern is something I've used previously with CloudFormation, however I'm much newer to terraform. Am I missing something obvious here?

1
Have you tried without wrapping var.environment in ${}? Unsure if you'll be able to do what you want, but with interpolation, you only need it once - and it's already inside that parent "${}" - TJ Biddle
@TJBiddle unfortunately when I specify it as subnet_id = "${data.terraform_remote_state.env-shared.subnet-aza-var.environment}" it doesn't expand the variable and instead it tries to read a subnet-aza-var.environment attribute which doesn't exist in the env-shared resource - PhilH

1 Answers

0
votes

Worked out a way to do this using data sources

variable "environment" {
    description = "Environment name"
    default     = "dev"
}

module "sql-1-ec2" {
  source     = "../modules/ec2winserver_sql"
  ...
  subnet_id  = "${data.aws_subnet.subnet-aza.id}" 
}

data "aws_subnet" "subnet-aza" {
  filter {
    name   = "tag:Name"
    values = ["${var.product}-${var.environment}-${var.environmentno}-subnet-aza"]
  }
}
data "aws_subnet" "subnet-azb" {
  filter {
    name   = "tag:Name"
    values = ["${var.product}-${var.environment}-${var.environmentno}-subnet-azb"]
  }
}

Whilst this works and fulfils my original need, I'd like to improve on this by moving the data blocks to within the module, so that there's less repetition. Still working on that one though...