BudiBadu Logo
Samplebadu

Terraform by Example: Variables

1.x

Variables make your configurations reusable and flexible. This code example illustrates defining variables with types, descriptions, and defaults to parameterize your infrastructure.

Code

variable "region" {
  description = "AWS region"
  type        = string
  default     = "us-east-1"
}

variable "instance_count" {
  description = "Number of instances"
  type        = number
  default     = 2
}

variable "tags" {
  description = "Tags to apply to resources"
  type        = map(string)
  default     = {
    Environment = "Dev"
    Terraform   = "True"
  }
}

resource "aws_instance" "app" {
  count         = var.instance_count
  ami           = "ami-12345678"
  instance_type = "t2.micro"
  
  tags = var.tags
}

Explanation

Input variables act as parameters for your Terraform modules, allowing you to customize behavior without altering the source code. By defining variables, you make your infrastructure code reusable across different environments (like development, staging, and production) and easier to share with others. Best practices dictate always including a type constraint and a meaningful description for every variable.

Terraform supports various data types, including simple types like string, number, and bool, as well as complex collections like list, map, and object. Defining explicit types helps catch errors early by ensuring that only valid data is passed to your configuration. You can also provide a default value, making the variable optional, or omit it to force the user to provide a value at runtime.

Variable values can be set through multiple mechanisms with a specific precedence order: environment variables (TF_VAR_name), variable definition files (terraform.tfvars), or command-line flags (-var). This flexibility allows for seamless integration into CI/CD pipelines and automated workflows.

Code Breakdown

1
variable "region" declares a new input variable.
3
type = string enforces strict type checking for the input.
4
default = "us-east-1" provides a fallback value if none is supplied.
15
type = map(string) specifies a collection of key-value string pairs.
23
count = var.instance_count dynamically sets resource count from the variable.