Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

terraform Concatenate variable and string

Tags:

terraform

I need to pass a variable to a data construct. However I don't want to build data object with all possible iterations. The intend is to query AWS to get resource ID. Here is a sample code:

variable "subnet" {}

data "aws_subnet" "subnet" {
  filter {
    name   = "state"
    values = ["available"]
  }

  filter {
    name   = "tag:Name"
    values = ["${var.subnet}"]
  }
}

output "data" {
  value = "${data.aws_subnet.'stage-a'.id}"
}
like image 408
Jacek Perry Avatar asked Nov 08 '22 04:11

Jacek Perry


1 Answers

Your codes nearly work. You use the wrong name with stage-a when reference its id in data source aws_subnet.

Here is the updated code.

variable "subnet" {}

data "aws_subnet" "subnet" {
  filter {
    name   = "state"
    values = ["available"]
  }

  filter {
    name   = "tag:Name"
    values = ["${var.subnet}"]
  }
}

output "data" {
  value = "${data.aws_subnet.subnet.id}"
}

Since there is no real resource created, you can run terraform apply freely.

$ TF_VAR_subnet="private" terraform apply
data.aws_subnet.subnet: Refreshing state...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

data = subnet-21f5a847

The only problem is, if there is no match, terraform will report problem and stop to apply the change if required.

$ TF_VAR_subnet="not_found" terraform apply
data.aws_subnet.subnet: Refreshing state...

Error: Error refreshing state: 1 error(s) occurred:

* data.aws_subnet.subnet: 1 error(s) occurred:

* data.aws_subnet.subnet: data.aws_subnet.subnet: no matching subnet found
like image 81
BMW Avatar answered Nov 15 '22 07:11

BMW