Terraform for_each and output values
Posted on March 14, 2023 (Last modified on July 2, 2024) • 1 min read • 121 wordsLet’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
}