Output Variables in Terraform Modules
In HashiCorp Configuration Language (HCL), output variables provide a way to expose specific values from a Terraform module to be used in the calling configuration or by other modules. This allows for the extraction of important information or results from a module. In this guide, we’ll explore how output variables work within Terraform modules.
Defining Output Variables
Output variables in Terraform modules are defined using the output
block in a file, commonly named outputs.tf
. These variables specify what values should be made available to the calling configuration.
# my_module/outputs.tf
output "instance_ip" {
description = "Public IP address of the created instance."
value = aws_instance.example.public_ip
}
output "instance_id" {
description = "ID of the created instance."
value = aws_instance.example.id
}
In this example, the “my_module” module defines two output variables: instance_ip
and instance_id
. They expose the public IP address and ID of an AWS instance, respectively.
Accessing Output Variables
To access the output variables from a module, you reference them in the calling configuration, usually within a module
block.
module "example_module" {
source = "./my_module"
}
resource "aws_security_group_rule" "example" {
type = "ingress"
from_port = 22
to_port = 22
protocol = "TCP"
cidr_blocks = ["0.0.0.0/0"]
security_group_id = module.example_module.instance_security_group_id
}
In this snippet, the public IP address and ID of the AWS instance created by “my_module” are accessed using the module.example_module.instance_ip
and module.example_module.instance_id
references, respectively.
Variable Dependencies
Terraform automatically manages dependencies between input and output variables. If a resource in a module depends on an input variable, Terraform ensures that the resource is created or updated after the input variable’s value is known. The same applies to output variables.
# my_module/main.tf
resource "aws_instance" "example" {
instance_type = "t2.micro"
ami = "ami-0c55b159cbfafe1f0"
subnet_id = aws_subnet.example.id
availability_zone = "us-west-2a"
}
# my_module/outputs.tf
output "instance_id" {
value = aws_instance.example.id
}
In this example, the “instance_id” output variable depends on the value of aws_instance.example.id
Summary
Output variables in Terraform modules are a powerful tool for exposing specific information or results to the calling configuration or other modules. They enable you to retrieve and utilize critical data, creating more dynamic and adaptable infrastructure as a result. By properly defining and referencing output variables, you can enhance the modularity and reusability of your Terraform code.