Module 4: Terraform Configuration
Lab 4A: Variables, Types, Expressions, and the Console
- Time
- 25 min
- Cost
- $0
- Prerequisites
- None listed
Starting files
Create ~/tf-course/lab4a/ with these files.
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
cd ~/tf-course/lab4a
terraform init && terraform apply -auto-approve
cat report.txtExpected output in report.txt:
prefix = tf-dev
api: medium on port 9090
web: small on port 8080Map iteration in a for expression is in lexical key order, so api comes before web. Also check the outputs:
unique_regionscontains 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.
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 allExpected output: the plan proposes changing the output to from-env, then from-tfvars, then from-auto, then from-cli.
Clean up afterward:
unset TF_VAR_environment && rm terraform.tfvars z.auto.tfvarsecho '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:
terraform plan -var-file=prod.tfvars | grep -A1 'environment'Expected output: it now changes to from-named. Remove the file with rm prod.tfvars.
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
terraform destroy -auto-approveThis lab has no verification checklist in the course file, so it counts as complete when every step is checked.