1 minute read

Looking at the standard documentation page for terraform output there are some samples for basic values and for how to access module values.

This is great, but what if you had been following some of my previous posts about looping and want get some output for resources that created with the for_each command? How can the static structure of the examples shown work for a dynamically created list of resources?

The standard syntax for an output statement is:

output "sqs_output" {
  value = aws_sqs_queue.message_queue.arn
}

NOTE: Displaying the ARN is not particular useful, but its good for demo purposes.

This will give us terraform apply output of something like:

Outputs:

sqs_output = arn:aws:sqs:ap-southeast-2:658977328088:simple-demo-sqs.fifo

But if we had created a dynamic number of sqs queues, how should we structure the output block?

One way I prefer, is to utilise the existing zipmap function with the following syntax:

output "sqs_output" {
  value = zipmap( values(aws_sqs_queue.message_queue)[*].name, values(aws_sqs_queue.message_queue)[*].arn ) 
}

This will give us terraform apply output of:

Outputs:

sqs_output = {
  "matt_test_one.fifo" = "arn:aws:sqs:ap-southeast-2:658977328088:matt_test_one.fifo"
  "matt_test_three.fifo" = "arn:aws:sqs:ap-southeast-2:658977328088:matt_test_three.fifo"
  "matt_test_two.fifo" = "arn:aws:sqs:ap-southeast-2:658977328088:matt_test_two.fifo"
}

Nice and simple.

Feel free to try this yourself in my sample terraform project in the looping folder.

This a simple solution to get what we are after! But if there is a better way you have seen, feel free to let me know via the comments below.

Comments