Terraform Variables

Terraform variables act as placeholders to parameterize your infrastructure configurations, allowing you to use the same codebase across different environments (development, staging, production) without hardcoding values. They are essential for creating flexible, reusable, and maintainable Infrastructure as Code (IaC). 

Declaring Variables

Variables are declared using a variable block in a .tf file (conventionally in a separate variables.tf file).

  • type: Specifies the type of data (e.g., string, number, bool, list, map, object, set, tuple).
  • default: Makes the variable optional; this value is used if no other value is provided.
  • description: Documents the purpose of the variable for users of the module.
  • validation: Enforces custom rules on the variable's value, returning a custom error message if the condition is not met.
  • sensitive: Marks the value as sensitive, preventing it from being shown in CLI output (though it is still stored in the state file).
  • nullable: Controls whether the variable can be assigned a null value (default is true as of recent versions)

Using Variables
Within your Terraform configuration, you reference a variable's value using the syntax var.<variable_name>
For Example:

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type # Using the variable
  # ...
}

Assigning Values
You can assign values to variables using several methods, which Terraform loads in a specific order of precedence (highest to lowest): 
  • Command-line flags: Using the -var or -var-file options when running terraform plan or terraform apply (e.g., terraform apply -var="instance_type=t2.large").
  • *.auto.tfvars files: Any files ending in .auto.tfvars or .auto.tfvars.json are automatically loaded in lexical order.
  • terraform.tfvars file: The exact file terraform.tfvars or terraform.tfvars.json is automatically loaded if present.
  • Environment variables: Terraform searches for environment variables prefixed with TF_VAR_ (e.g., export TF_VAR_instance_type="t2.micro").
  • default argument: The default value specified within the variable block itself. 
If a required variable has no default value and a value is not provided through any of these methods, Terraform will prompt the user to enter a value interactively. 
We can also explore how to manage these variables securely, especially sensitive data. 

Terraform variables support a range of data types, which are used to enforce type constraints and ensure data integrity within your configuration. These types can be broadly categorized into primitive types and complex types (collections).
Here are the main types you can specify in the type argument of a variable block:

Primitive Types
These are simple data types that represent a single value


For Example:

variable "region" {
  type = string
}

variable "max_count" {
  type = number
}

Complex Types (Collections)
These types represent a set of multiple values. They can be homogeneous (all elements are the same type) or heterogeneous (elements can be different types).


Type Constraints and Structure
You can use type constraints to define exactly what structure your complex type must adhere to:
For example:

variable "instance_config" {
  type = object({
    ami_id        = string
    instance_type = string
    tags          = map(string)
  })
  default = {
    ami_id        = "ami-xyz"
    instance_type = "t2.micro"
    tags          = { Name = "Default" }
  }
}

variable "subnet_ids" {
  type = list(string)
}

By specifying robust types, you enable Terraform to validate user inputs early in the process (during plan or validate), leading to more reliable infrastructure deployments.

Comments

Popular posts from this blog

Extend the Life of Windows Server 2012/2012 R2 with Azure Arc and SCCM Integration

High Availability vs. Disaster Recovery in Cloud: Key Differences Explained

Understanding App Registration vs. Enterprise Application in Microsoft Entra ID