amazon-web-servicesterraformterraform-provider-aws

Is it possible to put a loop in the output section of a Terraform plan?


$ terraform -v
Terraform v1.5.7
on darwin_amd64
+ provider registry.terraform.io/hashicorp/aws v5.80.0

I have a module that instantiates multiple EC2 instances, and I print out the information I want in the output section.

// Create an EC2 instances
module "ec2_node" {
  count                  = var.num_nodes
  source                 = "../modules/ec2_node"
  ami_id                 = var.ami_id
  availability_zone      = var.availability_zone
  ...
}

output "module_ec2_node_ec2_name_0" {
  value = module.ec2_node[0].ec2_tag_name
}

output "module_ec2_node_ec2_id_0" {
  value = module.ec2_node[0].ec2_id
}

output "module_ec2_node_private_ip_0" {
  value = module.ec2_node[0].ec2_priv_ip
}

output "module_ec2_node_ec2_name_1" {
  value = module.ec2_node[1].ec2_tag_name
}
output "module_ec2_node_ec2_id_1" {
  value = module.ec2_node[1].ec2_id
}

output "module_ec2_node_private_ip_1" {
  value = module.ec2_node[1].ec2_priv_ip
}

Is there anyway to put a loop in the output section instead of the way I did it?


Solution

  • Since you are using the module with the count meta-argument, the splat expression (*) can be used to get all attributes of a module output. In your case that would be:

    output "module_ec2_node_name" {
      value = module.ec2_node[*].ec2_tag_name
    }
    output "module_ec2_node_ec2_id" {
      value = module.ec2_node[*].ec2_id
    }
    output "module_ec2_node_private_ip" {
      value = module.ec2_node[*].ec2_priv_ip
    }