Terraform for_each and output values
Let’s say you have conditionally created a “thing” using for_each:
resource "aws_instance" "this" {
for_each = var.create_me == true ? toset(["yaaay"]) : toset([])
# ...
}
Now you want to use the instance’s IP address, lets say in the module’s “output”, just to have an example (you can use it within the module as well, anywhere you want). I always have to look into existing code to remember, so here are the multiple possible ways I’ve used so far :) :
output "instance_ip_address_method_1" {
type = string
value = element(values(aws_instance.this), 0)["public_ip"]
}
output "instance_ip_address_method_2" {
type = string
value = element([for v in values(aws_instance.this) : v.public_ip], 0)
}
output "instance_ip_address_method_3" {
description = "method 3"
type = string
value = aws_instance.this["yaaay"].public_ip
}