Bird
Raised Fist0
Terraformcloud~5 mins

Type constraints in variables in Terraform - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
When you write Terraform code, you often use variables to make your setup flexible. Type constraints help make sure the values you give to these variables are the right kind, like numbers or lists. This stops mistakes early and keeps your setup working smoothly.
When you want to make sure a variable only accepts a number, not text.
When you need a list of strings for multiple server names.
When you want to accept a map of key-value pairs for configuration.
When you want to avoid errors by restricting variable types before applying changes.
When you want to document what kind of data a variable should hold for others reading your code.
Config File - main.tf
main.tf
variable "instance_count" {
  type        = number
  description = "Number of instances to create"
  default     = 3
}

variable "server_names" {
  type        = list(string)
  description = "List of server names"
  default     = ["web1", "web2", "web3"]
}

variable "tags" {
  type        = map(string)
  description = "Map of tags for resources"
  default     = {
    environment = "production"
    team        = "devops"
  }
}

output "instance_count_output" {
  value = var.instance_count
}

output "server_names_output" {
  value = var.server_names
}

output "tags_output" {
  value = var.tags
}

This file defines three variables with type constraints:

  • instance_count must be a number.
  • server_names must be a list of strings.
  • tags must be a map with string keys and string values.

Each variable has a default value to use if none is provided.

The outputs show the values of these variables after Terraform applies the configuration.

Commands
This command initializes the Terraform working directory. It downloads necessary plugins and prepares the environment to run Terraform commands.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure. All Terraform commands should now work.
This command checks the configuration files for syntax errors and validates that the variable types and other settings are correct before applying.
Terminal
terraform validate
Expected OutputExpected
Success! The configuration is valid.
This command applies the Terraform configuration to create or update infrastructure. The -auto-approve flag skips the manual approval step.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_instance.example: Creating... aws_instance.example: Creation complete after 10s [id=i-1234567890abcdef0] Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: instance_count_output = 3 server_names_output = ["web1", "web2", "web3"] tags_output = { "environment" = "production" "team" = "devops" }
-auto-approve - Automatically approve the apply without prompting
This command shows the current values of the outputs defined in the configuration, confirming the variables were set correctly.
Terminal
terraform output
Expected OutputExpected
instance_count_output = 3 server_names_output = ["web1", "web2", "web3"] tags_output = { "environment" = "production" "team" = "devops" }
Key Concept

If you remember nothing else from this pattern, remember: type constraints in variables help catch mistakes early by ensuring inputs are the right kind of data.

Common Mistakes
Not specifying a type constraint for a variable.
Terraform accepts any type, which can cause errors later if the wrong data type is used.
Always specify the expected type to prevent invalid inputs.
Using a wrong type in the variable default or input, like a string instead of a number.
Terraform will fail to apply because the value does not match the expected type.
Make sure default values and inputs match the declared type exactly.
Declaring a list variable but providing a single string value.
Terraform expects a list but gets a string, causing a type error.
Provide a list even if it has one item, e.g., ["single-item"].
Summary
Define variables with type constraints to ensure correct data types.
Use terraform init to prepare the environment and terraform validate to check configuration correctness.
Apply the configuration with terraform apply and check outputs with terraform output.

Practice

(1/5)
1. What is the main purpose of using type constraints in Terraform variables?
easy
A. To assign default values to variables
B. To make variables optional
C. To encrypt variable values
D. To ensure variables only accept specific kinds of data

Solution

  1. Step 1: Understand variable type constraints

    Type constraints limit what kind of data a variable can accept, like strings or lists.
  2. Step 2: Identify the purpose

    This helps catch errors early by preventing wrong data types from being used.
  3. Final Answer:

    To ensure variables only accept specific kinds of data -> Option D
  4. Quick Check:

    Type constraints = restrict data type [OK]
Hint: Type constraints restrict variable data types [OK]
Common Mistakes:
  • Confusing type constraints with default values
  • Thinking type constraints make variables optional
  • Assuming type constraints encrypt data
2. Which of the following is the correct syntax to declare a variable with a list of strings type constraint in Terraform?
easy
A. variable "names" { type = list(string) }
B. variable "names" { type = "list of strings" }
C. variable "names" { type = [string] }
D. variable "names" { type = string[] }

Solution

  1. Step 1: Recall Terraform type syntax

    Terraform uses list(string) to specify a list of strings as a type.
  2. Step 2: Compare options

    variable "names" { type = list(string) } uses the correct syntax. Others use invalid or unsupported formats.
  3. Final Answer:

    variable "names" { type = list(string) } -> Option A
  4. Quick Check:

    List of strings = list(string) [OK]
Hint: Use list(string) for list of strings type [OK]
Common Mistakes:
  • Using quotes around type names incorrectly
  • Using array syntax like string[] which is invalid in Terraform
  • Writing type as a plain string description
3. Given this variable declaration:
variable "ports" {
  type = set(number)
  default = [80, 443, 8080]
}

What will be the type and value of var.ports when accessed in Terraform?
medium
A. A list of numbers: [80, 443, 8080]
B. A set of numbers: {80, 443, 8080}
C. A map with keys 80, 443, 8080
D. A string containing "80,443,8080"

Solution

  1. Step 1: Understand the declared type

    The variable type is set(number), which means a set of unique numbers.
  2. Step 2: Check the default value

    The default is a list, but Terraform converts it to a set because of the type constraint.
  3. Final Answer:

    A set of numbers: {80, 443, 8080} -> Option B
  4. Quick Check:

    Type set(number) = set of numbers [OK]
Hint: set(number) converts list to unique number set [OK]
Common Mistakes:
  • Confusing set with list type
  • Expecting a map instead of a set
  • Thinking default list stays a list despite type
4. Identify the error in this variable declaration:
variable "config" {
  type = map(string)
  default = ["a", "b", "c"]
}
medium
A. Default values must be numbers
B. Type map(string) is invalid syntax
C. Default value is a list, but type expects a map
D. Variable name cannot be "config"

Solution

  1. Step 1: Analyze the type constraint

    The type map(string) expects a map with string values, like { key = "value" }.
  2. Step 2: Check the default value

    The default is a list, which does not match the map type.
  3. Final Answer:

    Default value is a list, but type expects a map -> Option C
  4. Quick Check:

    Type map(string) needs map, not list [OK]
Hint: Match default value type to variable type [OK]
Common Mistakes:
  • Using list as default for map type
  • Thinking map(string) is invalid syntax
  • Believing variable names are restricted
5. You want a variable that accepts either a string or a list of strings. Which type constraint correctly allows this in Terraform?
hard
A. type = string | list(string)
B. type = any
C. type = object({ string_or_list = string })
D. type = string, list(string)

Solution

  1. Step 1: Understand union types in Terraform

    Terraform supports union types using the pipe symbol | to allow multiple types.
  2. Step 2: Identify correct syntax

    type = string | list(string) uses string | list(string), which means the variable can be either a string or a list of strings.
  3. Step 3: Check other options

    type = any allows any type, which is too broad. type = object({ string_or_list = string }) defines an object, not a union. type = string, list(string) is invalid syntax.
  4. Final Answer:

    type = string | list(string) -> Option A
  5. Quick Check:

    Union type uses | to combine types [OK]
Hint: Use | to combine types for union constraints [OK]
Common Mistakes:
  • Using commas instead of | for union types
  • Choosing any type instead of specific union
  • Confusing object type with union type