Contents
Use the variable block to parameterize your configuration so that module consumers can pass custom values into the configuration at runtime. 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.
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>"
}
}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 |
Variable Precedence
If the root module receives multiple values for the same variable name from different sources, Terraform uses the following order of precedence:
- Any
-varand-var-fileoptions on the command line in the order provided and variables from HCP Terraform - Any
*.auto.tfvarsor*.auto.tfvars.jsonfiles in lexical order - The
terraform.tfvars.jsonfile - The
terraform.tfvarsfile - Environment variables
- The
defaultargument of thevariableblock