How To Output Multiple Count Items With Terraform

In this blog post, we will explore the output feature in Terraform and how it can be used to output multiple values when using the meta-argument.

About Count

The count meta-argument in Terraform allows users to create multiple instances of a resource by specifying the number of instances to create. The count argument can be used to create multiple instances of any resource that supports it.

How Does Terraform Count Work?

When the count argument is used, Terraform creates multiple instances of the specified resource based on the value of the count argument. Terraform creates unique resource names for each instance by appending a zero-based index to the end of the resource name.

For example, if you create three instances of an EC2 instance, Terraform will create three unique resource names: aws_instance.example[0], aws_instance.example[1], and aws_instance.example[2].

What is Terraform Output?

Terraform output is a feature that allows users to retrieve information about the infrastructure created or updated by Terraform. This information can be used for various purposes, such as configuring other tools or integrating with third-party services. Terraform output is defined in the Terraform configuration file and can be accessed using the Terraform CLI or other tools.

Defining an output in Terraform is straightforward when there is only when resource we need to output. The syntax for defining an output is as follows:

output "output_name" {
  value = value_to_return
}

Code

When we need to output multiple values, things can get a bit complex, as you will see in the example below.

In the example below, I’m creating multiple Public IPs on Azure, which I’m going to output.

resource "azurerm_public_ip" "win11publicip" {
  count               = var.num_vms
  name                = "${var.win11prefix}-${count.index}"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  allocation_method   = "Dynamic"

}

In the below code, I’m outputting both of the IPs to the terminal screen after deployment. Notice the code structure and how I use * to loop over the IPs.

output "public_ip_address" {
  
  value = [azurerm_windows_virtual_machine.win11vm.*.public_ip_address]
}

Processing…
Success! You're on the list.


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.