Terraform
variable block reference
Use the variable block to parameterize your configuration, making your modules dynamic, reusable, and flexible by letting them customize behavior with different values at run time.
Hands-on: Try the Customize Terraform Configuration with Variables tutorial.
Background
The variable block is similar to a function argument in other programming languages. Input variables let you customize Terraform modules without altering their source code. Variables serve as parameters for modules, making them composable and reusable.
You can define variables in root modules, or in child modules:
- In the root modules, you can set variable values using CLI options, environment variables, variable definition files, or through an HCP Terraform workspace.
- In child modules, the parent module passes values to child modules as arguments to the
moduleblock.
To learn more about the different ways to use and set values for variables, refer to Define module input arguments with variables.
Configuration model
The variable block supports the following arguments:
variable "<LABEL>"blocktypetype constraintdefaultexpressiondescriptionstringvalidationblockconditionexpressionerror_messagestring
sensitivebooleannullablebooleanephemeralboolean
Complete configuration
All available arguments are defined in the following variable block. There are no mutually exclusive arguments for a variable block.
variable "<LABEL>" {
type = <TYPE>
default = <DEFAULT_VALUE>
description = "<DESCRIPTION>"
sensitive = <true|false>
nullable = <true|false>
ephemeral = <true|false>
validation {
condition = <EXPRESSION>
error_message = "<ERROR_MESSAGE>"
}
}
Specification
A variable block supports the following configuration.
variable "<LABEL>"
The label after the variable keyword is a name for the variable, which must be unique among all variables in the same module. The name of a variable can be any valid identifier except the following reserved names: source, version, providers, count, for_each, lifecycle, depends_on, or locals.
The following arguments are supported in a variable block:
| Argument | Description | Type | Required? |
|---|---|---|---|
type | Specify a type constraint for the value argument of this variable. | Type constraint | Optional |
default | Sets the default value for this variable. Variables without a default value are required to define a value argument. | Expression | Optional |
description | A description of the variable’s purpose and the value it expects. | String | Optional |
validation | Specify a rule the value of this variable must meet, in addition to any type constraints. | Block | Optional |
sensitive | Specifies if Terraform hides this value in CLI output. | Boolean | Optional |
nullable | Specifies if the value of a variable can be null. | Boolean | Optional |
ephemeral | Specifies whether to prevent storing this value in state or plan files. | Boolean | Optional |
type
The type argument in a variable block constrains the type of value that you can assign to that variable. If you do not set a type constraint, the variable accepts a value of any type.
variable "unique_name" {
type = <type-constraint>
}
Defining type constraints helps your module consumer understand what value your variable needs, and type constraints also provide helpful error messages if consumers attempt to use an invalid type.
You can use any valid primitive, complex, or structural type as a constraint in a variable block. For details about types, constructors, and conversions, refer to Type constraints.
Summary
- Data type: Type constraint
- Default:
any - Example: Basic variable declaration
default
The default argument defines a default value for the variable, making it optional to provide a value. If you do not provide a variable value when using a module, Terraform uses the default value.
variable "region" {
type = string
default = <default-value>
}
If you specify both the type and default arguments, the default value must convert to the specified type. The default argument requires a literal value and cannot reference other objects in the configuration.
Summary
- Data type: Expression
- Default: None, but you must define a value argument if you do not define a default argument.
- Example: Basic variable declaration
description
The description argument in a variable block documents the purpose of a variable and the value the block expects.
variable "image_id" {
type = string
description = "<description-from-the-module-consumer-point-of-view>”
}
Write your description from the perspective of a module consumer to help your users understand how to use this variable. If you need to leave commentary about a variable block as a module maintainer, use a comment instead.
Summary
- Data type: String
- Default: None
- Example: Basic variable declaration
validation
The validation block lets you enforce that a variable value meets your specific requirements, in addition to any type constraints. Use variable validations to guarantee a variable meets your configuration’s needs before Terraform finishes generating a plan.
variable "unique_name" {
value = <expression-to-evaluate>
validation {
condition = <expression-to-verify>
error_message = "<error message string>"
}
}
You can specify the following arguments in the validation block:
| Argument | Description | Type | Required |
|---|---|---|---|
condition | Expression that must evaluate to true for Terraform to proceed with an operation. | A valid Conditional expression. | Required |
error_message | Message to display if the condition evaluates to false. | String | Required |
Terraform evaluates variable validations while it creates a plan, and if a validation block's condition expression evaluates to false, then Terraform throws an error, displays the error_message, and stops the current operation. Refer to Validate your configuration for more details and examples.
Summary
- Data type: Block
- Default: None
- Example: Variable with validation
sensitive
The sensitive argument prevents Terraform from showing a variable block's value in CLI output when you use that variable in your configuration.
variable "user_password" {
type = string
sensitive = true
}
When you mark a variable as sensitive, Terraform redacts its value in plan and apply logs. Terraform also treats any expressions that use a sensitive variable as sensitive.
Terraform will perform the following actions:
# some_resource.a will be created
+ resource "some_resource" "a" {
+ user_password = (sensitive value)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Terraform still records sensitive values in state, so anyone who can access your state data can access your sensitive values. For more information about safely storing sensitive data, refer to Manage sensitive data.
Summary
- Data type: Boolean
- Default:
false - Example: Sensitive variable
nullable
Enabling the nullable argument lets module consumers assign the value null to the variable.
variable "example" {
type = string
nullable = false
}
If nullable is false in a variable block, then that variable must have a value that is not null. If nullable is true and the variable has a default argument, you can explicitly set the variable value to null, overwriting the default argument.
If a variable uses a collection or structural type, such as a list or object, a module consumer can use null in nested elements as long as the collection or structure itself is not null.
Summary
- Data type: Boolean
- Default:
true
ephemeral
Note
Ephemeral variables are available in Terraform v1.10 and later.
The ephemeral argument makes a variable available during runtime, but Terraform omits ephemeral values from state and plan files. The ephemeral argument is useful for values that only exist temporarily, such as a short-lived token or session identifier.
variable "session_token" {
type = string
ephemeral = true
}
You can reference and set ephemeral variables values from specific contexts:
- An
outputblock with the ephemeral argument - In another variable block with the ephemeral argument
- A write-only argument in a resource block
- An
ephemeralresource block - In the
providerblock to configure providers - In a provisioner and provisioner connection configuration. Refer to Use a provisioner for more information.
If another expression references a variable with the ephemeral argument, that expression also implicitly becomes ephemeral.
Summary
- Data type: Boolean
- Default:
false - Example: Ephemeral variable
Examples
The following examples demonstrate common use cases for variable blocks.
Basic variable declaration
In the following example, the image_id variable requires a string value and has no default, making it required. The availability_zone_names variable accepts a list of strings and provides a default value, making it optional for users to provide a value for this variable:
variable "image_id" {
type = string
description = "The ID of the machine image (AMI) to use for the server."
}
variable "availability_zone_names" {
type = list(string)
description = "List of availability zones where resources will be deployed."
default = ["us-west-1a"]
}
Set a value to a complex type
In the following example, the docker_ports variable accepts a list of objects where each object must have internal and external number attributes and a protocol string attribute:
variable "docker_ports" {
type = list(object({
internal = number
external = number
protocol = string
}))
description = "List of port configurations for Docker containers."
default = [
{
internal = 8300
external = 8300
protocol = "tcp"
}
]
}
Variable with validation
In the following example, the validation block ensures that the image_id value is longer than 4 characters and starts with "ami-". If the variable value does not meet the condition, Terraform displays the specified error message:
variable "image_id" {
type = string
description = "The ID of the machine image (AMI) to use for the server."
validation {
condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
error_message = "The image_id value must be a valid AMI ID, starting with \"ami-\"."
}
}
Sensitive variable
In the following example, the database_password variable is marked as sensitive, which causes Terraform to redact both the variable value and any resource attributes that use it from logs:
variable "database_password" {
type = string
description = "Password for the database instance."
sensitive = true
}
resource "aws_db_instance" "example" {
identifier = "my-database"
engine = "mysql"
username = "admin"
password = var.database_password
# …
}
When you run a plan or apply operation, Terraform displays sensitive values as (sensitive value). Terraform obscures both the database_password variable and any resource arguments that use that variable, for example Terraform logs the following when applying the configuration:
Terraform will perform the following actions:
# aws_db_instance.example will be created
+ resource "aws_db_instance" "example" {
+ identifier = "my-database"
+ engine = "mysql"
+ username = "admin"
+ password = (sensitive value)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Any expression that references a sensitive variable becomes sensitive automatically.
Ephemeral variable
The following example configures the AWS provider by referencing credentials from three separate variables containing sensitive data. The access_key, secret_key, and session_token variables are ephemeral, so they are available during Terraform operations, but are not stored in state or plan files afterwards.
variable "access_key" {
description = "AWS access key"
type = string
ephemeral = true
}
variable "secret_key" {
description = "AWS sensitive secret key."
type = string
sensitive = true
ephemeral = true
}
variable "session_token" {
description = "AWS session token."
type = string
sensitive = true
ephemeral = true
}
provider "aws" {
access_key = var.access_key
secret_key = var.secret_key
token = var.session_token
}