variable block reference
Use thevariable block to parameterize your configuration so that module consumers can pass custom values into the configuration at runtime.
Hands-on: Try theCustomize Terraform Configuration with Variables tutorial.
Background
Thevariable 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 toUse variables to input module arguments.
Configuration model
Thevariable block supports the following arguments:
variable "<LABEL>"blocktypetype constraintdefaultexpressiondescriptionstringvalidationblockconditionexpressionerror_messagestring
sensitivebooleannullablebooleanephemeralboolean
Complete configuration
All available arguments are defined in the followingvariable block. There are no mutually exclusive arguments for avariable 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
Avariable block supports the following configuration.
variable "<LABEL>"
The label after thevariable 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 valididentifier except the following reserved names:source,version,providers,count,for_each,lifecycle,depends_on, orlocals.
The following arguments are supported in avariable 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 benull. | Boolean | Optional |
ephemeral | Specifies whether to prevent storing this value in state or plan files. | Boolean | Optional |
type
Thetype argument in avariable 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 toType constraints.
Summary
- Data type: Type constraint
- Default:
any - Example:Basic variable declaration
default
Thedefault 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 thetype anddefault arguments, the default value must convert to the specified type. Thedefault 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
Thedescription argument in avariable 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
Thevalidation 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 thevalidation block:
| Argument | Description | Type | Required |
|---|---|---|---|
condition | Expression that must evaluate totrue for Terraform to proceed with an operation. | A validConditional 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'scondition expression evaluates tofalse, then Terraform throws an error, displays theerror_message, and stops the current operation. Refer toValidate your configuration for more details and examples.
Summary
- Data type: Block
- Default: None
- Example:Variable with validation
sensitive
Thesensitive 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 toManage sensitive data.
Summary
- Data type: Boolean
- Default:
false - Example:Sensitive variable
nullable
Enabling thenullable argument lets module consumers assign the valuenull to the variable.
variable "example" { type= string nullable= false}Ifnullable isfalse in a variable block, then that variable must have a value that is not null. If nullable is true and the variable has adefault 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 usenull 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.
Theephemeral argument makes a variable available during runtime, but Terraform omits ephemeral values from state and plan files. Theephemeral 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
- Awrite-only argument in a resource block
- An
ephemeralresource block - In the
providerblock to configure providers - In a provisioner and provisioner connection configuration. Refer toUse a provisioner for more information.
If another expression references a variable with theephemeral argument, that expression also implicitly becomes ephemeral.
Summary
- Data type: Boolean
- Default:
false - Example:Ephemeral variable
Examples
The following examples demonstrate common use cases forvariable 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, thedocker_ports variable accepts a list of objects where each object must haveinternal andexternal number attributes and aprotocol 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 theimage_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, thedatabase_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. Theaccess_key,secret_key, andsession_token variables areephemeral, 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}