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}"
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With