Terraform Variables

Learn how to define and use variables in Terraform configurations.

Defining Variables

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

Using Variables

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cb41deb1b"
  instance_type = var.instance_type
}

Variables allow you to parameterize your configuration, making it reusable and configurable across different environments.

Best Practices

Example tfvars file

# variables.tf
variable "region" {
  description = "AWS region"
  type        = string
  default     = "us-east-1"
}

variable "vpc_cidr" {
  description = "VPC CIDR block"
  type        = string
  default     = "10.0.0.0/16"