Terraform
Manage values in modules
Make your Terraform modules flexible, composable, and reusable by defining input variable values, local values, and output values.
Background
Terraform modules communicate with each other through inputs and outputs. Add variables to parameterize your module so that other users can provide custom input values at runtime. Outputs expose data from a module, letting you export information about your infrastructure. Locals let you define and reuse expressions within a module.
Defining clear interfaces for your modules creates boundaries between them, letting you compose infrastructure from reusable components while keeping each module's implementation independent.
Define variables to input module arguments
Variables define the input interface of your module by specifying the values your module accepts as arguments.
For example, the following variable block defines an input variable named instance_type, letting a module consumer specify an EC2 instance type for web at runtime:
variable "instance_type" {
type = string
description = "EC2 instance type for the web server"
default = "t2.micro"
}
resource "aws_instance" "web" {
instance_type = var.instance_type
# ...
}
To learn more about defining variables, assigning values to them, and managing variables in HCP Terraform, refer to Use variables to input module arguments. To learn more about the variable block and its arguments, refer to the variable block reference.
Define locals to reuse expressions
Locals define temporary values scoped to your module, letting you name and reuse expressions in your configuration. For example, the following locals block defines a local value for the name of an application:
locals {
app_name = "${var.project_name}-${var.environment}"
}
resource "aws_instance" "example" {
# ...
tags = {
Name = local.app_name
}
}
resource "aws_instance" "example2" {
# ...
tags = {
Name = local.app_name
}
}
You can reference locals in other parts of your configuration to avoid retyping an expression multiple times.
To learn more about when to use local values, refer to Use locals to reuse expressions. To learn more about the locals block and its arguments, refer to the locals block reference.
Define outputs to expose module data
Outputs expose data from a module, making module values available in the Terraform CLI, HCP Terraform, and other parts of your configuration.
In the following example, the instance_ip output exports the private IP address of the web EC2 instance:
output "instance_ip" {
description = "Private IP address of the EC2 instance"
value = aws_instance.web.private_ip
}
resource "aws_instance" "web" {
# …
}
To learn more about exposing data from modules and accessing those values, refer to Use outputs to expose module data. To learn more about the output block and its arguments, refer to the output block reference.