Terraform Variable Type

The type argument in a variable block allows you to restrict the type of value that will be accepted as the value for a variable. If no type constraint is set then a value of any type is accepted.

type constraints are optional but its recommended by terraform to specifying them.

Type constraints are created from a mixture of type keywords and type constructors. The supported type keywords are:

  • string
  • number
  • bool

The type constructors allow you to specify complex types such as collections:

  • list
  • map

If both the type and default arguments are specified, the given default value must be convertible to the specified type.

Variable description

Because the input variables of a module are part of its user interface, you can briefly describe the purpose of each variable using the optional description argument.

let's create a file variable.tf in your current working directory. with the below content.

variable username {
  type = string
  default = "world"


variable age {
  type = number
  default = 23

and create one more file printvariable.tf with the below content

output "printvariable" {
  value = "Hello ${var.username} and your age is ${var.age}"

you can pass the variable value from the command line using below syntax

terraform plan -var "variablename=variablevalue" -var "variable2name=varible2value"

now lets run terraform plan command in actions.

└─$ terraform plan -var "username=Learning-Ocean" -var "age=23"

Changes to Outputs:
  + printname = "Hello, Learning-Ocean, your age is 23"

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.

if we pass age as String it will give an error.

└─$ terraform apply -var username="Gaurav" -var age=gaurav
│ Error: Invalid value for input variable
│ The argument -var="age=..." does not contain a valid value for variable "age": a number is required.
│ Error: Incorrect variable type
│   on variable.tf line 5:
│    5: variable "age" {
│ The resolved value of variable "age" is not appropriate: a number is required.

Demo Video