A variable block declares an input variable for a Terraform module. It lets module users change configuration without editing the module itself, improving reuse across deployments. section 3.3.1 section 3.8.2
Configure a variable block with these arguments and controls:
- Use its single label as the variable name, such as ami, subnet_id, or instance_type. section 2.2.2
- Add description to document the input; external tools can use it to generate documentation. section 3.3.1
- Set type to restrict accepted values, default to supply a value when none is provided, and sensitive to reduce log exposure. section 3.3.1 section 3.8.2
- Use nullable to control whether null is accepted, and validation to add checks for values such as AWS subnet identifiers. section 3.3.1 section 3.8.2
Configuring and consuming module inputs
variable "instance_type" { type = string description = "The type of instance to launch." default = "t3.micro" } variable "subnet_id" { type = string description = "The ID of the Subnet to launch the instance into." validation { condition = length(regexall("^subnet-[\\d|\\w]+$", var.subnet_id)) == 1 error_message = "The subnet_id must match the expected pattern." } } resource "aws_instance" "hello_world" { subnet_id = var.subnet_id instance_type = var.instance_type } The var keyword followed by the variable name refers to an input elsewhere in the module. Type restrictions and validation catch unsuitable values before deployment. section 3.8.2 section 3.3.1
Listing 3.2 Example variables
variable "ami" {
type = string #1
description = "The Amazon Machine Image to use when launching the EC2
Instance."
}
variable "subnet_id" {
type = string
description = "The ID of the Subnet to launch the instance into."
}
variable "instance_type" {
type = string
description = "The type of instance to launch." #2
default = "t3.micro" #3
}
#1 Variables can be restricted to specific data types, such as strings.
#2 Inputs can have descriptions, and it’s a good practice to always add them.
#3 Inputs can have default values so users don’t have to explicitly define all of them.
Inspect a complete set of documented variables showing type constraints, descriptions, and defaults. section 3.3.1
