Mastodon Mastodon - Terraform for_each and output values
 logo
  • Home 
  • Tags 
  • Blog posts 
  1. Home
  2. Blog posts
  3. Terraform for_each and output values

Terraform for_each and output values

Posted on March 14, 2023  (Last modified on July 2, 2024) • 1 min read • 121 words
Terraform   Snippet   Solved  
Terraform   Snippet   Solved  
Share via
Link copied to clipboard

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
}
 pg_dump and pg_restore
Use VSCodium with Microsoft's proprietary marketplace 
In case you want to follow me

Here are some links. The further to the right, the less active.

           
(c) Axel Bock | Powered by Hinode.
Code copied to clipboard