Module 4: Terraform Configuration

Lab 4A: Variables, Types, Expressions, and the Console

Time
25 min
Cost
$0
Prerequisites
None listed
Objectives
0 of 5 checked

Starting files

Create ~/tf-course/lab4a/ with these files.

main.tfHCL
terraform {
  required_version = "~> 1.12.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
  }
}

variable "environment" {
  type        = string
  description = "Deployment environment."
  default     = "dev"
}

variable "enable_monitoring" {
  type    = bool
  default = false
}

variable "regions" {
  type    = list(string)
  default = ["us-east-1", "us-west-2", "us-east-1"]
}

variable "tags" {
  type    = map(string)
  default = { owner = "platform" }
}

variable "servers" {
  type = map(object({
    size = string
    port = optional(number, 8080)
  }))
  default = {
    web = { size = "small" }
    api = { size = "medium", port = 9090 }
  }
}

locals {
  name_prefix   = "tf-${var.environment}"
  unique_region = toset(var.regions)
  common_tags   = merge(var.tags, { environment = var.environment })
  server_lines  = [for name, cfg in var.servers : "${name}: ${cfg.size} on port ${cfg.port}"]
  medium_only   = { for name, cfg in var.servers : name => cfg if cfg.size == "medium" }
}

resource "local_file" "report" {
  filename = "${path.module}/report.txt"
  content  = join("\n", concat(["prefix = ${local.name_prefix}"], local.server_lines, [""]))
}

output "environment" {
  value = var.environment
}

output "unique_regions" {
  value = local.unique_region
}

output "common_tags" {
  value = local.common_tags
}

output "medium_servers" {
  value = keys(local.medium_only)
}

output "monitoring_label" {
  value = var.enable_monitoring ? "monitored" : "unmonitored"
}

Steps

Shell
cd ~/tf-course/lab4a
terraform init && terraform apply -auto-approve
cat report.txt

Expected output in report.txt:

Text
prefix = tf-dev
api: medium on port 9090
web: small on port 8080

Map iteration in a for expression is in lexical key order, so api comes before web. Also check the outputs:

  • unique_regions contains two values, because the set removed the duplicate.
  • medium_servers = ["api"]
  • monitoring_label = "unmonitored"

Run each command, in this order, and note the environment output each time.

Shell
export TF_VAR_environment=from-env
terraform plan | grep -A1 'environment'          # from-env

echo 'environment = "from-tfvars"' > terraform.tfvars
terraform plan | grep -A1 'environment'          # from-tfvars beats env

echo 'environment = "from-auto"' > z.auto.tfvars
terraform plan | grep -A1 'environment'          # from-auto beats terraform.tfvars

terraform plan -var 'environment=from-cli' | grep -A1 'environment'   # from-cli beats all

Expected output: the plan proposes changing the output to from-env, then from-tfvars, then from-auto, then from-cli.

Clean up afterward:

Shell
unset TF_VAR_environment && rm terraform.tfvars z.auto.tfvars

Shell
echo 'environment = "from-named"' > prod.tfvars
terraform plan | grep -A1 'environment'

Expected output: no change, because prod.tfvars isn't loaded automatically. Then load it explicitly:

prod.tfvarsShell
terraform plan -var-file=prod.tfvars | grep -A1 'environment'

Expected output: it now changes to from-named. Remove the file with rm prod.tfvars.

Shell
terraform plan -var 'enable_monitoring=maybe'

Expected output: an error that the value isn't a valid bool.

Run terraform console and evaluate each expression. Write down your prediction before pressing Enter.

Expression Expected result
toset(["a", "b", "a"]) A set of "a" and "b"
tolist(toset(["b", "a"]))[0] "a" (sets of strings are sorted)
lookup({ a = 1 }, "b", 0) 0
merge({ a = 1 }, { a = 2, b = 3 }) { a = 2, b = 3 } (the later map wins)
[for n in range(3) : n * 2] [0, 2, 4]
flatten([[1, 2], [3]]) [1, 2, 3]
try(tonumber("abc"), -1) -1
coalesce("", "fallback") "fallback"
format("%s-%03d", "web", 7) "web-007"
cidrsubnet("10.0.0.0/16", 8, 2) "10.0.2.0/24"
var.servers["web"].port 8080 (the optional() default)
local.medium_only A map containing only api
local_file.report.filename "./report.txt", read from state
toset(["a"])[0] Error: sets can't be indexed

Verification and cleanup

Shell
terraform destroy -auto-approve

Lab 4A complete. Every step is checked.

This lab has no verification checklist in the course file, so it counts as complete when every step is checked.