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 module block.

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:

ArgumentDescriptionTypeRequired?
typeSpecify a type constraint for the value argument of this variable.Type constraintOptional
defaultSets the default value for this variable. Variables without a default value are required to define a value argument.ExpressionOptional
descriptionA description of the variable’s purpose and the value it expects.StringOptional
validationSpecify a rule the value of this variable must meet, in addition to any type constraints.BlockOptional
sensitiveSpecifies if Terraform hides this value in CLI output.BooleanOptional
nullableSpecifies if the value of a variable can be null.BooleanOptional
ephemeralSpecifies whether to prevent storing this value in state or plan files.BooleanOptional

Variable Precedence

If the root module receives multiple values for the same variable name from different sources, Terraform uses the following order of precedence:

  1. Any -var and -var-file options on the command line in the order provided and variables from HCP Terraform
  2. Any *.auto.tfvars or *.auto.tfvars.json files in lexical order
  3. The terraform.tfvars.json file
  4. The terraform.tfvars file
  5. Environment variables
  6. The default argument of the variable block