Types of Variable in Terraform (Part-7)

There are three primary types of variables in Terraform:

  1. Input Variables
  2. Output Variables
  3. Local Variables

1. Input Variables

Input variables are used to define values that can be passed into the Terraform configuration from external sources. This makes your configurations flexible and reusable.

Basic Types of Input Variables:

  • String
  • Number
  • Boolean
  • List
  • Map
  • Object
  • Tuple

Terraform input variable have 5 optional arguments.

Optional Arguments for Variable Blocks

  1. default
  2. type
  3. description
  4. validation
  5. sensitive

1. default

The default argument specifies a default value for the variable. This makes the variable optional; if no value is provided during runtime, Terraform uses the default value.

Example:

variable "instance_type" {
  description = "The type of instance to use"
  type        = string
  default     = "t2.micro"
}

2. type

The type argument specifies the type of value the variable can accept. It ensures that the correct data type is used when assigning values to the variable.

Example:

variable "instance_count" {
  description = "Number of instances to launch"
  type        = number
  default     = 1
}

3. description

The description argument provides documentation for the variable. This helps users understand the purpose of the variable.

Example:

variable "instance_name" {
  description = "The name to assign to the instance"
  type        = string
  default     = "example-instance"
}

4. validation

The validation block allows you to define custom validation rules for the variable, usually in addition to type constraints. This can help enforce specific requirements for variable values.

Example:

variable "instance_type" {
  description = "The type of instance to use"
  type        = string
  default     = "t2.micro"

  validation {
    condition     = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
    error_message = "The instance type must be t2.micro, t2.small, or t2.medium."
  }
}

5. sensitive

The sensitive argument limits the Terraform UI output when the variable is used in configuration. This is useful for variables containing sensitive information like passwords or keys.

Example:

variable "db_password" {
  description = "The password for the database"
  type        = string
  sensitive   = true
}

Complete Example with All Optional Arguments

variable "instance_type" {
  description = "The type of instance to use"
  type        = string
  default     = "t2.micro"

  validation {
    condition     = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
    error_message = "The instance type must be t2.micro, t2.small, or t2.medium."
  }
}

variable "instance_count" {
  description = "Number of instances to launch"
  type        = number
  default     = 1
}

variable "instance_name" {
  description = "The name to assign to the instance"
  type        = string
  default     = "example-instance"
}

variable "db_password" {
  description = "The password for the database"
  type        = string
  sensitive   = true
}

Summary

  • default: Specifies a default value, making the variable optional.
  • type: Defines the type of the variable (e.g., string, number, list).
  • description: Provides documentation for the variable.
  • validation: Adds custom validation rules for the variable.
  • sensitive: Limits Terraform UI output when the variable is used in configuration.

Examples of Input Variables

String Variable

variable "instance_type" {
  description = "The type of instance to use"
  type        = string
  default     = "t2.micro"
}

Number Variable

variable "instance_count" {
  description = "Number of instances to launch"
  type        = number
  default     = 1
}

Boolean Variable

variable "enable_monitoring" {
  description = "Enable monitoring for the instances"
  type        = bool
  default     = true
}

List Variable

variable "availability_zones" {
  description = "List of availability zones"
  type        = list(string)
  default     = ["us-west-1a", "us-west-1b"]
}

Map Variable

variable "tags" {
  description = "A map of tags to assign to the resource"
  type        = map(string)
  default     = {
    Name = "example-instance"
    Environment = "dev"
  }
}

Object Variable

variable "server" {
  description = "Configuration for the server"
  type = object({
    instance_type = string
    disk_size     = number
    tags          = map(string)
  })
  default = {
    instance_type = "t2.micro"
    disk_size     = 20
    tags          = {
      Name        = "example-server"
      Environment = "production"
    }
  }
}

Tuple Variable

variable "database_config" {
  description = "Database configuration"
  type = tuple([string, number, bool])
  default = ["mysql", 3306, true]
}

2. Output Variables

Output variables are used to extract information from your configurations and display it to the user or pass it to other configurations.

It is not so significant but we create output.tf files just to keep output value in on output.tf to manage all output and we can also give any name to this file.

Example of Output Variables

output "instance_id" {
  description = "The ID of the EC2 instance"
  value       = aws_instance.example.id
}

output "instance_public_ip" {
  description = "The public IP address of the EC2 instance"
  value       = aws_instance.example.public_ip
}

3. Local Variables

Local variables are used to simplify expressions within a module. They can hold intermediate values that you want to reuse in multiple places within a module.

Example of Local Variables

locals {
  instance_name = "example-instance"
  tags = {
    Name = local.instance_name
    Environment = "dev"
  }
}

resource "aws_instance" "example" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t2.micro"
  tags          = local.tags
}

Complete Example with Input, Output, and Local Variables

# variables.tf
variable "instance_type" {
  description = "The type of instance to use"
  type        = string
  default     = "t2.micro"
}

variable "instance_count" {
  description = "Number of instances to launch"
  type        = number
  default     = 1
}

variable "tags" {
  description = "A map of tags to assign to the resource"
  type        = map(string)
  default     = {
    Name        = "example-instance"
    Environment = "dev"
  }
}

# main.tf
provider "aws" {
  region = "us-west-2"
}

locals {
  name_tag = "example-instance"
  environment_tag = "dev"
}

resource "aws_instance" "example" {
  count = var.instance_count
  ami = "ami-0abcdef1234567890"
  instance_type = var.instance_type
  tags = {
    Name = local.name_tag
    Environment = local.environment_tag
  }
}

output "instance_ids" {
  description = "The IDs of the EC2 instances"
  value       = aws_instance.example.*.id
}

output "instance_public_ips" {
  description = "The public IP addresses of the EC2 instances"
  value       = aws_instance.example.*.public_ip
}

In this example:

  • Input Variables: instance_type, instance_count, and tags are used to parameterize the configuration.
  • Local Variables: name_tag and environment_tag are used to simplify the tagging of resources.
  • Output Variables: instance_ids and instance_public_ips are used to display useful information about the created resources.

Related Posts

Terraform Cheat Sheet: The Ultimate Reference for Infrastructure as Code (2025)

๐Ÿงพ Terraform Cheat Sheet: The Ultimate Reference for Infrastructure as Code (2025) Learn and master Terraform with this complete cheat sheet โ€” from basics to advanced automation….

Read More

Terraform Explained Through a Simple Story โ€“ From Manual Chaos to Automated Peace

๐ŸŒ Terraform Explained Through a Simple Story โ€“ From Manual Chaos to Automated Peace ๐Ÿšช Welcome to DevTown โ€“ The City of Applications Imagine a bustling city…

Read More

Terraform from Essentials to Advanced: The Complete Guide (2025)

๐ŸŒ Terraform from Essentials to Advanced: The Complete Guide (2025) Build, manage, and scale infrastructure like code โ€“ cloud-native, multi-cloud, and secure. ๐Ÿš€ What is Terraform? Terraform…

Read More

Terraform interview questions that are commonly asked in interviews

Basic Questions Intermediate Questions Advanced Questions Scenario-Based Questions Advanced and Scenario-Based Questions Mohammad Gufran Jahangir

Read More

Ultimate guide for terraform from basic to advance

What is the need of terraform IAAC? The need for Terraform Infrastructure as Code (IaAC) is driven by several key benefits: Summary: List of IaaC tools Here…

Read More

Terraform Pipeline (Part-18)

Terraform Pipeline A Terraform pipeline automates the process of planning, applying, and managing infrastructure as code (IaC) with Terraform. By integrating Terraform with a CI/CD pipeline, you…

Read More
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x