Thuta Learning
IntermediateDevOpsintermediate

Variables

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand Variables, no intimidation required
  • Get hands-on running terraform commands and HCL code yourself
  • Be ready to apply this concept in a real project right away

Let's think about this for a second

If you hardcode `instance_type = "t3.micro"` in your config, you'd have to manually edit the code every time you switch environments (dev vs prod). Using an Input Variable (`variable "name" { type = ... }`) instead lets you supply the value at run time — via a command-line flag, a `.tfvars` file, an environment variable, or a default value. Specifying a variable's `type` (string, number, bool, list, map, object) means Terraform will catch a mistyped value with an error before applying.

Let's connect this to a real scenario

If you define `variable "instance_type" { type = string; default = "t3.micro" }` and reference it in a resource block as `instance_type = var.instance_type`, you can override the value with `terraform apply -var="instance_type=t3.large"` (or a `.tfvars` file) — this lets a single config file handle small instances for dev and large instances for prod.

Let's look at an example

hcl
variable "instance_type" {
  description = "EC2 instance size"
  type        = string
  default     = "t3.micro"
}

variable "environment" {
  type = string
}

resource "aws_instance" "web" {
  instance_type = var.instance_type
  tags = {
    Environment = var.environment
  }
}
You should see
$ terraform apply -var="environment=staging"
var.instance_type
  EC2 instance size

  Enter a value: (uses default "t3.micro" if left blank)

5-minute try-it

Define 2 variables (instance_type, environment) and run `terraform plan`, passing a value with the `-var` flag — try both the default value and an override.

A quick word of caution

If you write sensitive values (passwords, API keys) in a `.tfvars` file, add it to `.gitignore` so it never gets committed to your git repository.

Easy traps

  • Getting confused when `variable "environment"` has no default and no value is passed in, causing `apply` to suddenly show an interactive prompt
  • Hardcoding a sensitive variable (like a password) into a `default` value — this can leak if the `.tf` file gets committed

Now try it yourself

Define 2 variables (instance_type, environment) and run `terraform plan`, passing a value with the `-var` flag — try both the default value and an override.

You'll know it worked when: $ terraform apply -var="environment=staging" var.instance_type EC2 instance size Enter a value: (uses default "t3.micro" if left blank)

Variables | Thuta Learning