You have spent five modules using functions without ever studying them. merge has been composing local.common_tags since module 4. cidrsubnet computes EcoMarket's subnets in all three clouds, with a mysterious 100-position offset that we justified in one sentence and never took apart. templatefile injects the PostgreSQL endpoint into cloud-init's user_data. try props up references that may not exist. jsonencode builds the IAM policies. They all worked, and at no point did we explain why.
This lesson settles that debt, but not as a reference list — that already exists and lives in HashiCorp's documentation, always more up to date than any course. What you will find here is the catalogue organised by what you need to do, with examples taken from EcoMarket's real infrastructure rather than from toys involving lists of fruit, and with the traps that turn an innocent function into a plan that never converges or a resource that gets recreated every Tuesday.
The other goal of the lesson is to teach you not to memorise anything. terraform console is a complete interpreter for the expression language, and everything that appears here can be tried out in it in five seconds. That habit — testing before writing into a .tf — is worth more than knowing all hundred-and-something functions in the catalogue.
- The catalogue, the documentation and
terraform console
terraform consoleTerraform ships around 130 built-in functions, grouped into eight categories. Nobody knows them all by heart, and nobody needs to. What you do need is a method.
How to look things up
The official documentation lives at developer.hashicorp.com/terraform/language/functions, with one page per function. Every page has the same structure: signature, description, runnable examples and related functions. That last section is the most useful one: if you arrived at lookup and what you needed was coalesce, the link is right there.
Inside the editor, the official Terraform extension offers autocompletion with the signature and the description. And in the terminal itself:
The console has no built-in help, so the real lookup is the website. What the console does give you is the important thing: an interpreter to test in.
The console session
terraform console opens an interpreter for the expression language with the state and the variables of the current directory loaded. That makes it far more powerful than a calculator: you can inspect module outputs, state values and real variables.
A typical working session against EcoMarket:
# Standalone expressions: calculator mode
> cidrsubnet("10.20.0.0/16", 8, 3)
"10.20.3.0/24"
> merge({ Project = "ecomarket" }, { Environment = "dev" })
{
"Environment" = "dev"
"Project" = "ecomarket"
}
# Variables loaded from the .tfvars
> var.environment
"dev"
> var.environments["dev"].web_class
"t3.micro"
# Locals from the configuration
> local.prefix
"ecomarket-dev"
> local.common_tags
{
"CostCenter" = "CC-LAB"
"Environment" = "dev"
"ManagedBy" = "terraform"
"Project" = "ecomarket"
}
# Values from state: resources already created
> module.network.vpc_id
"vpc-0a1b2c3d4e5f67890"
> keys(module.network.private_subnets)
[
"eu-west-1a",
"eu-west-1b",
"eu-west-1c",
]
# Try a complex expression BEFORE writing it into a .tf
> [for z, s in module.network.private_subnets : "${z} => ${s.cidr}"]
[
"eu-west-1a => 10.20.0.0/24",
"eu-west-1b => 10.20.1.0/24",
"eu-west-1c => 10.20.2.0/24",
]
# See the type of something when you do not know what it is
> type(var.environments)
map(
object({
cidr: string,
create_nat: bool,
db_class: string,
extra_tags: map(string),
multi_az: bool,
protect_deletion: bool,
retention_days: number,
web_class: string,
web_instances: object({
desired: number,
max: number,
min: number,
}),
}),
)
> exitFour rules of use:
| Rule | Reason |
|---|---|
Pass the same -var-file you use in plan |
Without it, var.* will prompt for values or fail |
| The console modifies nothing | It is read-only: you can poke around risk-free |
| It refreshes state on opening with some backends | With remote state it reads from the backend; you will not see changes made outside |
| It accepts piped input | echo 'cidrsubnet("10.0.0.0/16",8,5)' | terraform console for scripts |
That last one is handy in the pipeline for verifying calculations:
Tip. When an expression does not do what you expect, the right reflex is not to change the
.tfand runplan— which takes half a minute and burns API calls. It is to open the console, paste the expression and take it apart from the inside out. A two-second debugging loop versus a thirty-second one completely changes the way you work.
The two loops, compared:
flowchart LR
subgraph slow["Slow loop: ~30 s per attempt"]
L1["Edit the .tf"] --> L2["terraform plan"]
L2 --> L3["Refresh:<br/>API calls"]
L3 --> L4["Read the error"]
L4 --> L1
end
subgraph fast["Fast loop: ~2 s per attempt"]
R1["terraform console"] --> R2["Paste the expression"]
R2 --> R3["Take it apart<br/>from the inside out"]
R3 --> R2
R3 --> R4["Write the .tf<br/>once only"]
end
- Why you cannot define your own functions
Terraform does not allow you to declare your own functions. There is no function block. This is one of the most noticeable differences from a programming language, and when it bites, it hurts.
The reason is a design one: HCL is a declarative configuration language, and user-defined functions would introduce arbitrary logic, recursion and an evaluation graph far harder to reason about. HashiCorp prefers complexity to live in modules and providers, which are versionable, testable units.
The three alternatives, in order of preference:
2.1 locals as a single-use function
If the expression is long but is used once or twice, a local with a descriptive name does the job and documents it too:
locals {
# Name-normalisation "function": lowercase, no odd characters,
# truncated to 63 characters (the S3 bucket name limit).
images_bucket_name = substr(
lower(replace("${local.prefix}-images-${random_pet.suffix.id}", "/[^a-zA-Z0-9-]/", "-")),
0,
63,
)
}2.2 Modules when the logic repeats
If the same transformation is needed in several places, the right answer is a module. It can be a module with no resources, which only takes variables, computes and returns outputs:
# modules/names/variables.tf
variable "project" { type = string }
variable "environment" { type = string }
variable "component" { type = string }
variable "suffix" { type = string, default = "" }
# modules/names/outputs.tf
output "prefix" {
value = "${var.project}-${var.environment}"
}
output "resource_name" {
value = lower(join("-", compact([
var.project, var.environment, var.component, var.suffix,
])))
}
output "globally_unique_name" {
description = "For S3 buckets and names that must be unique worldwide."
value = substr(
lower(join("-", compact([var.project, var.environment, var.component, var.suffix]))),
0, 63,
)
}# Usage
module "bucket_name" {
source = "./modules/names"
project = var.project
environment = var.environment
component = "images"
suffix = random_pet.suffix.id
}
resource "aws_s3_bucket" "images" {
bucket = module.bucket_name.globally_unique_name
}It is more verbose than a function, and that is the trade-off. The upside is that the module is versionable, testable with terraform test and publishable in the registry like any other.
2.3 Provider functions (provider::)
Since Terraform 1.8, a provider can contribute its own functions, invoked through the provider::<provider>::<function> namespace:
locals {
# AWS provider function: breaks an ARN down into its parts.
arn_parts = provider::aws::arn_parse(module.data.bucket_arn)
bucket_account = local.arn_parts.account_id
}You cannot write them yourself without writing a provider — which means Go, with its own release cycle — but it is worth knowing they exist, because there are more of them all the time and they solve things that previously required acrobatics with split and regex.
| Need | Solution | Cost |
|---|---|---|
| A long expression used once | local with a descriptive name |
None |
| The same transformation in several places in one module | A shared local |
None |
| The same transformation across modules or teams | A module with no resources | Verbosity |
| Logic the language cannot express | A provider function, or precompute outside | High |
- Strings: composing, trimming and normalising names
Most string work in Terraform is generating resource names that comply with each cloud's rules.
| Function | Signature | Example with EcoMarket | Result |
|---|---|---|---|
format |
format(fmt, args...) |
format("%s-%s-%03d", var.project, var.environment, 7) |
"ecomarket-dev-007" |
formatlist |
formatlist(fmt, lists...) |
formatlist("%s.ecomarket.example.com", ["web", "api"]) |
["web.ecomarket...", "api.ecomarket..."] |
join |
join(sep, list) |
join(",", ["10.20.0.0/24", "10.20.1.0/24"]) |
"10.20.0.0/24,10.20.1.0/24" |
split |
split(sep, string) |
split(":", module.data.endpoint) |
["ecomarket-dev-db...rds.amazonaws.com", "5432"] |
replace |
replace(str, find, sub) |
replace("ecomarket_dev", "_", "-") |
"ecomarket-dev" |
trimsuffix |
trimsuffix(str, suf) |
trimsuffix("ecomarket.example.com.", ".") |
"ecomarket.example.com" |
trimprefix |
trimprefix(str, pre) |
trimprefix("arn:aws:s3:::bucket", "arn:aws:s3:::") |
"bucket" |
trimspace |
trimspace(str) |
trimspace(file("version.txt")) |
"2.5.0" |
lower / upper |
lower(str) |
lower("EU-WEST-1") |
"eu-west-1" |
title |
title(str) |
title("ecomarket dev") |
"Ecomarket Dev" |
substr |
substr(str, start, len) |
substr(random_pet.suffix.id, 0, 8) |
"noble-ba" |
startswith / endswith |
startswith(str, pre) |
startswith(terraform.workspace, "pr-") |
true |
strcontains |
strcontains(str, sub) |
strcontains(var.domain, "example.com") |
true |
strrev |
strrev(str) |
strrev("abc") |
"cba" |
indent |
indent(n, str) |
For multi-line YAML | see section 10 |
regex / regexall |
regex(pattern, str) |
regex("^(\\d+)\\.", "2.5.0") |
"2" |
The real case: S3 bucket names
Bucket names are globally unique, allow only lowercase letters, digits, dots and hyphens, and have a maximum of 63 characters. EcoMarket generates them like this:
locals {
# A candidate name, which may break any of the three rules.
candidate = "${var.project}_${var.environment}_Images_${random_pet.suffix.id}"
# Normalisation in four steps, from the inside out:
# 1. lower() -> lowercase is mandatory
# 2. replace() -> underscores to hyphens (S3 does not allow "_")
# 3. substr() -> truncate to 63
# 4. trimsuffix() -> a trailing hyphen after truncation would be invalid
bucket_name = trimsuffix(
substr(
replace(lower(local.candidate), "_", "-"),
0,
63,
),
"-",
)
}> local.candidate
"ecomarket_dev_Images_noble-bass"
> lower(local.candidate)
"ecomarket_dev_images_noble-bass"
> replace(lower(local.candidate), "_", "-")
"ecomarket-dev-images-noble-bass"The trimsuffix at the end looks like paranoia, but it is not: if truncation at 63 lands right after a hyphen, the name ends in - and S3 rejects it with an error that does not say why. Testing the composition in the console with the edge case — a long random_pet, a project with a long name — is what prevents that incident.
split for taking endpoints apart
The RDS endpoint arrives with the port stuck to it:
> module.data.endpoint
"ecomarket-dev-db.abc123.eu-west-1.rds.amazonaws.com:5432"
> split(":", module.data.endpoint)
[
"ecomarket-dev-db.abc123.eu-west-1.rds.amazonaws.com",
"5432",
]
> split(":", module.data.endpoint)[0]
"ecomarket-dev-db.abc123.eu-west-1.rds.amazonaws.com"In 05-05 this mattered because cloud-init needs the host and the port separately. The robust pattern:
locals {
db_parts = split(":", module.data.endpoint)
db_host = local.db_parts[0]
# Default port if the endpoint does not carry one: not every provider includes it.
db_port = try(tonumber(local.db_parts[1]), 5432)
}regex and regexall: the last resort
# Extract the major version from an image tag
> regex("^(\\d+)\\.(\\d+)\\.(\\d+)$", "2.5.0")
[
"2",
"5",
"0",
]
# With named groups it returns an object: far more readable
> regex("^(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)$", "2.5.0")
{
"major" = "2"
"minor" = "5"
"patch" = "0"
}
# regexall returns ALL the matches; an empty list if there are none.
# It is the idiomatic way to ask "does it match?" without failing.
> length(regexall("^pr-\\d+$", terraform.workspace)) > 0
trueregex fails the plan if there is no match; regexall returns an empty list. For checks, use regexall or wrap regex in try. And as a general rule: if you are writing a regular expression longer than thirty characters in a .tf, there is almost always a more direct function, or the data should have arrived already broken apart.
- Collections: the core of the real work
This is 70% of the function work on a real platform.
4.1 merge: the tagging debt
merge combines maps. Later arguments win over earlier ones for repeated keys.
> merge(
{ Project = "ecomarket", Environment = "dev" },
{ Environment = "prod", Owner = "platform" },
)
{
"Environment" = "prod" # ← the second map won
"Owner" = "platform"
"Project" = "ecomarket"
}That precedence is exactly what makes EcoMarket's tagging pattern useful — the one you have been using since module 4 without our ever taking it apart:
locals {
# Layer 1: tags EVERY resource must carry, no exceptions.
base_tags = {
Project = var.project
ManagedBy = "terraform"
Contact = "[email protected]"
}
# Layer 2: what the environment contributes.
environment_tags = {
Environment = var.environment
CostCenter = local.current.cost_center
}
# Layer 3: whatever the environment's .tfvars wants to add.
# merge honours the order: base < environment < extras.
common_tags = merge(
local.base_tags,
local.environment_tags,
local.current.extra_tags,
)
}And at the point of use, the fourth layer, specific to the resource:
resource "aws_s3_bucket" "images" {
bucket = local.bucket_name
tags = merge(local.common_tags, {
Name = "${local.prefix}-images"
Component = "data"
Backup = "daily"
})
}This is EcoMarket's complete tagging pattern. Four layers, each one able to override the previous, and the result is that adding a mandatory tag to the whole platform means editing base_tags in one place.
Two details about merge that catch people out:
# 1. It does NOT deep merge. A nested map is replaced wholesale.
> merge(
{ config = { a = 1, b = 2 } },
{ config = { a = 9 } },
)
{
"config" = {
"a" = 9
}
}
# The "b" key vanished. merge is shallow.
# 2. It ignores null arguments, which allows conditional merges.
> merge({ a = 1 }, var.optional_extras)Shallow merging is the cause of plenty of surprises when somebody tries to do "configuration inheritance" with nested objects. Terraform has no deepmerge; if you need one, rethink the structure so that it is flat.
4.2 flatten and the Cartesian product
flatten flattens a list of lists into a simple list, recursively:
Its canonical use is the two-dimensional Cartesian product, which shows up the moment you have resources per environment and per zone, or rules per group and per port. EcoMarket needs one VPC endpoint for each service in each zone:
locals {
vpc_services = ["s3", "secretsmanager", "ssm", "ec2messages"]
zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
# Two nested for expressions produce a list of lists...
# ...which flatten turns into a flat list of 12 objects.
combinations = flatten([
for service in local.vpc_services : [
for zone in local.zones : {
service = service
zone = zone
key = "${service}-${zone}"
}
]
])
# And from the flat list to a map, which is what for_each needs
# in order to have stable keys (remember 02-03).
endpoints = {
for c in local.combinations : c.key => c
}
}
resource "aws_vpc_endpoint" "services" {
for_each = local.endpoints
vpc_id = module.network.vpc_id
service_name = "com.amazonaws.eu-west-1.${each.value.service}"
vpc_endpoint_type = "Interface"
subnet_ids = [module.network.private_subnets[each.value.zone].id]
tags = merge(local.common_tags, {
Name = "${local.prefix}-vpce-${each.key}"
})
}Verification in the console before applying:
> length(local.combinations)
12
> keys(local.endpoints)
[
"ec2messages-eu-west-1a",
"ec2messages-eu-west-1b",
"ec2messages-eu-west-1c",
"s3-eu-west-1a",
...
]Without flatten, the nested for expressions return a list of three lists of four elements and for_each fails with an error about types. It is the number-one reason this function shows up.
4.3 setproduct: the Cartesian product without loops
setproduct does the same thing more compactly when you do not need to build objects:
> setproduct(["s3", "ssm"], ["eu-west-1a", "eu-west-1b"])
[
["s3", "eu-west-1a"],
["s3", "eu-west-1b"],
["ssm", "eu-west-1a"],
["ssm", "eu-west-1b"],
]
# Combined with a for expression to give the positions names:
> { for pair in setproduct(["s3","ssm"], ["a","b"]) : "${pair[0]}-${pair[1]}" => {
service = pair[0]
zone = pair[1]
} }Pick setproduct when the two dimensions are flat lists, and flatten with nested for expressions when you need logic inside (filters, computed fields). The for version is longer and more readable; the setproduct one forces you to remember what pair[0] is.
4.4 lookup versus indexing
> local.sizing["prod"] # indexing: fails if it does not exist
> lookup(local.sizing, "prod", local.sizing["default"])| Form | If the key exists | If it does not |
|---|---|---|
map["key"] |
Returns the value | Invalid index error, the plan fails |
lookup(map, "key") |
Returns the value | Error (same as indexing) |
lookup(map, "key", default) |
Returns the value | Returns default |
try(map["key"], default) |
Returns the value | Returns default |
The official recommendation is to use indexing when the key must exist — because the error is clearer — and lookup with a third argument when absence is legitimate. Two-argument lookup adds nothing over indexing and only makes the code longer.
locals {
# The key MUST exist: if var.environment is not in var.environments, that
# is a configuration error and I want the plan to stop.
current = var.environments[var.environment]
# The key MAY not exist: not every environment declares its own domain.
domain = lookup(local.current, "domain", "${var.environment}.ecomarket.example.com")
}4.5 The rest of the collection catalogue
| Function | What it does | Example with EcoMarket |
|---|---|---|
concat |
Joins lists | concat(local.office_cidrs, local.vpn_cidrs) |
distinct |
Removes duplicates, preserving order | distinct(concat(...)) before creating rules |
keys / values |
Keys and values of a map | keys(module.network.private_subnets) → the zones |
zipmap |
Two lists → one map | zipmap(local.zones, local.cidrs) |
coalesce |
First argument that is neither null nor empty | coalesce(var.custom_domain, local.default_domain) |
coalescelist |
First non-empty list | coalescelist(var.zones, data.aws_availability_zones.d.names) |
one |
List of 0-1 elements → the element or null |
one(aws_db_instance.replica[*].endpoint) |
slice |
Sublist [start, end) |
slice(data.aws_availability_zones.d.names, 0, 3) |
sort |
Sorts a list of strings | sort(keys(var.environments)) for stable outputs |
element |
Element by index with wrap-around | element(local.zones, count.index) |
index |
Position of a value | index(local.zones, "eu-west-1b") → 1 |
contains |
Is the value in the list? | contains(local.allowed_classes, var.web_class) |
alltrue / anytrue |
Conjunction/disjunction of a list of bool |
cross-cutting validations |
length |
Size of a list, map or string | length(local.zones) >= 2 |
compact |
Removes empty strings from a list | compact([var.project, var.suffix]) |
chunklist |
Splits a list into chunks of N | import batches |
sum |
Sums a list of numbers | total estimated cost |
reverse |
Reverses a list | destruction order in documentation |
setunion / setintersection / setsubtract |
Set operations | comparing what is deployed with what is declared |
Four of them deserve detail because their behaviour is not obvious.
element wraps around, [] does not. element(list, 5) on a three-element list returns element 5 % 3 = 2. list[5] fails. That wrap-around is useful for distributing resources across zones cyclically:
resource "aws_instance" "worker" {
count = 7
subnet_id = module.network.private_subnets[element(local.zones, count.index)].id
# 7 instances distributed cyclically across 3 zones: 3, 2, 2
}And it is a trap in any other context, because it turns an index error into a silent but wrong value.
one is the companion of conditional resources. When you use count = var.create ? 1 : 0, the reference is a list of zero or one element:
resource "aws_db_instance" "replica" {
count = local.current.create_replica ? 1 : 0
# ...
}
output "replica_endpoint" {
description = "Endpoint of the read replica, or null if it does not exist."
# one() returns the single element, or null if the list is empty.
# Without one(), you would have to write try(aws_db_instance.replica[0].endpoint, null).
value = one(aws_db_instance.replica[*].endpoint)
}one fails if the list has more than one element, which is a free check: it documents that you expected zero or one.
coalesce also discards empty strings, not just null. That is the difference from try and the reason it is the right function for optional variables the user may leave as "":
> coalesce(null, "", "value")
"value"
> coalesce("", null)
Error: no non-null, non-empty-string arguments were providedalltrue/anytrue are the engine behind cross-cutting validations. They will show up again in 06-05:
locals {
# Are all the environment CIDRs /16 or less specific?
valid_cidrs = alltrue([
for e, cfg in var.environments : tonumber(split("/", cfg.cidr)[1]) <= 16
])
# Does any environment have deletion protection turned off in prod?
prod_risk = anytrue([
for e, cfg in var.environments : e == "prod" && !cfg.protect_deletion
])
}Careful with the empty case: alltrue([]) is true and anytrue([]) is false. Mathematically correct, operationally dangerous: a validation that walks an empty list always passes.
- Numeric functions
The least used ones, but indispensable when they come up.
| Function | Example | Result | Real use in EcoMarket |
|---|---|---|---|
min |
min(var.instances, 10) |
ceiling | Capping the auto scaling maximum |
max |
max(var.instances, 2) |
floor | Guaranteeing minimum high availability |
ceil |
ceil(7 / 3.0) |
3 |
Spreading instances across zones with none left out |
floor |
floor(100 * 0.5) |
50 |
A sane minimum percentage during a rolling update |
abs |
abs(-3) |
3 |
Capacity differences |
parseint |
parseint("ff", 16) |
255 |
Converting masks and hexadecimal codes |
pow |
pow(2, 8) |
256 |
Addresses in a subnet from its bits |
signum |
signum(-4) |
-1 |
Direction of a scaling action |
log |
log(256, 2) |
8 |
Bits needed for N subnets |
locals {
# Spreading instances across zones, guaranteeing at least one per zone
# and with none left over.
instances_per_zone = ceil(local.current.web_instances.desired / length(local.zones))
# The sane minimum percentage must never leave fewer than 1 instance alive.
min_healthy = max(
floor(100 / local.current.web_instances.desired),
50,
)
# How many bits do I need to split my CIDR into N subnets?
# For 6 subnets: ceil(log(6, 2)) = 3 bits -> 8 slots.
required_bits = ceil(log(length(local.zones) * 2, 2))
}Careful with integer division. In Terraform, 7 / 3 is 2.3333... because every number is floating point; there is no implicit integer division. But ceil and floor return numbers that, when used as count, must be whole. ceil(7 / 3) is 3 and works; 7 / 3 straight into count fails with must be a whole number.
- Encoding and serialisation
6.1 JSON: the IAM policy
jsonencode converts a Terraform value into a JSON string. It is the correct way to write IAM policies when you are not using aws_iam_policy_document:
resource "aws_iam_role_policy" "web_bucket_access" {
name = "${local.prefix}-web-bucket"
role = aws_iam_role.web.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Sid = "ReadAndWriteImages"
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
]
Resource = "${aws_s3_bucket.images.arn}/*"
},
{
Sid = "ListTheBucket"
Effect = "Allow"
Action = ["s3:ListBucket"]
Resource = aws_s3_bucket.images.arn
Condition = {
StringLike = {
"s3:prefix" = ["public/*", "products/*"]
}
}
},
]
})
}Four advantages over writing the JSON as a literal string with <<EOT:
- References work without ugly interpolation:
aws_s3_bucket.images.arninstead of"${aws_s3_bucket.images.arn}"inside a string. - Terraform validates the syntax at parse time: one comma too many is an HCL error, not an AWS API error three minutes later.
terraform fmtaligns it as code, not as opaque text.- It can be composed: the statements can come out of a
for.
That last one is what makes it genuinely valuable:
locals {
read_buckets = {
images = aws_s3_bucket.images.arn
invoices = aws_s3_bucket.invoices.arn
reports = aws_s3_bucket.reports.arn
}
}
resource "aws_iam_role_policy" "web_read" {
name = "${local.prefix}-web-read"
role = aws_iam_role.web.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
for name, arn in local.read_buckets : {
Sid = "Read${title(name)}"
Effect = "Allow"
Action = ["s3:GetObject"]
Resource = "${arn}/*"
}
]
})
}jsondecode goes the other way, and its most common use is reading external configuration:
locals {
# A product catalogue maintained by the business team
catalogue = jsondecode(file("${path.module}/data/categories.json"))
}Careful with
jsonencodeand types.jsonencode(true)producestrue(a JSON boolean), butjsonencode("true")produces"true"(a string). Plenty of APIs tell the difference. Andjsonencodeof a sensitive value produces an entirely sensitive string, which masks the whole JSON in the plan output and makes it impossible to review the policy.
6.2 YAML: cloud-init and manifests
locals {
cloud_config = yamlencode({
write_files = [
{
path = "/etc/ecomarket/app.env"
permissions = "0640"
owner = "ecomarket:ecomarket"
content = join("\n", [
"DB_HOST=${local.db_host}",
"DB_PORT=${local.db_port}",
"S3_BUCKET=${aws_s3_bucket.images.id}",
"SECRET_NAME=${aws_secretsmanager_secret.db.name}",
"ENVIRONMENT=${var.environment}",
])
},
]
runcmd = [
["systemctl", "enable", "--now", "ecomarket"],
]
})
}
resource "aws_launch_template" "web" {
# The #cloud-config line is MANDATORY and yamlencode does not add it.
user_data = base64encode("#cloud-config\n${local.cloud_config}")
# ...
}yamlencode versus templatefile for cloud-init. It is a decision with a criterion:
| Criterion | yamlencode |
templatefile with .yaml.tftpl |
|---|---|---|
| Indentation | Impossible to break | Fragile: a multi-line value breaks it (hence indent()) |
| Readability of the source | HCL structure, not YAML | Real YAML, which is what the systems team expects to read |
| Comments in the result | Lost | Preserved |
| Conditional logic | HCL for/conditionals |
%{ if } directives |
| Validation up front | Guaranteed by construction | cloud-init schema |
EcoMarket uses templatefile because the systems team maintains the template and wants to see YAML. If the generator were purely programmatic, yamlencode would be safer.
yamldecode reads YAML, and its typical use case is consuming a Kubernetes manifest or a configuration file shared with another tool:
Warning.
yamldecodeimplements YAML 1.2 and does not accept all of YAML 1.1's extravagances. Anchors and references (&base,*base) do work; custom tags do not. If the file comes from another tool, test it in the console before trusting it.
6.3 base64 and the user_data limit
In AWS, user_data on an aws_launch_template expects base64 (there is a user_data_base64 on aws_instance, and the launch template's user_data attribute already requires it encoded). AWS's hard limit is 16 KB of encoded content. When a cloud-init template grows, base64gzip compresses before encoding:
resource "aws_launch_template" "web" {
# base64gzip = gzip + base64. cloud-init automatically decompresses
# gzip-compressed user_data.
user_data = base64gzip(templatefile("${path.module}/templates/cloud-init.yaml.tftpl", {
db_host = local.db_host
bucket = aws_s3_bucket.images.id
secret = aws_secretsmanager_secret.db.name
environment = var.environment
app_version = var.image_version
}))
}Checking the size before applying:
$ terraform console -var-file=dev.tfvars
> length(base64gzip(templatefile("templates/cloud-init.yaml.tftpl", { ... })))
2184
> length(base64encode(templatefile("templates/cloud-init.yaml.tftpl", { ... })))
7320From 7,320 down to 2,184 bytes. But remember what we said in 05-05: compressing is not the answer to a large user_data. It is a patch that buys time. A user_data brushing 16 KB is a user_data that should be a Packer image or a script downloaded from a bucket.
urlencode encodes a string for use in a URL, handy when building endpoints with parameters:
- Hashing and cryptography
| Function | What it returns | Legitimate use | Trap |
|---|---|---|---|
md5 |
Hexadecimal MD5 hash | Short derived names | Not cryptographically secure |
sha1 |
SHA-1 hash | Compatibility with old APIs | Same as MD5 |
sha256 / sha512 |
SHA-2 hash | Detecting content changes | None |
filemd5 / filesha256 |
Hash of a file without reading it whole into memory | etag of S3 objects |
The file must exist at plan time |
base64sha256 |
SHA-256 in base64 | Lambda's source_code_hash |
A different format from hexadecimal |
bcrypt |
bcrypt hash with a random salt | Almost none | Changes on every evaluation |
uuid |
Random v4 UUID | Almost none | Changes on every evaluation |
uuidv5 |
Deterministic v5 UUID | Stable derived identifiers | None |
rsadecrypt |
Decrypts with an RSA private key | Windows initial password | The state stores the result in the clear |
The filesha256 pattern for detecting changes
resource "aws_s3_object" "deploy_script" {
bucket = aws_s3_bucket.artifacts.id
key = "scripts/deploy.sh"
source = "${path.module}/scripts/deploy.sh"
# Without an etag, Terraform does not detect that the local file changed:
# it compares only the attributes it knows about, and "source" is a path
# that has not changed even though its contents have.
etag = filemd5("${path.module}/scripts/deploy.sh")
}This is a case where MD5 is mandatory rather than optional: S3 uses MD5 for its ETag, so filesha256 would be no use here. The choice of function is imposed by the API, not by security.
To force instance replacement when the template changes:
resource "aws_launch_template" "web" {
# ...
tags = merge(local.common_tags, {
# The hash of the rendered template as a tag: it changes the
# version name when the content changes, and that shows up
# in the plan.
TemplateHash = substr(sha256(local.rendered_cloud_init), 0, 12)
})
}The two functions that break idempotence
# ❌ NEVER do this
resource "aws_db_instance" "main" {
password = bcrypt(var.db_password) # changes on every plan
}
resource "aws_s3_bucket" "temporary" {
bucket = "ecomarket-${uuid()}" # changes on every plan
}bcrypt generates a fresh random salt on every evaluation, so its result is different in every plan. uuid() generates a random v4 UUID, with the same problem. The symptom is identical and unmistakable:
# aws_s3_bucket.temporary must be replaced
-/+ resource "aws_s3_bucket" "temporary" {
~ bucket = "ecomarket-3f2a..." -> "ecomarket-9c81..." # forces replacementA plan that proposes replacing a resource without anybody having touched anything. And if you apply it, the next plan proposes it again. The plan never converges, which on top of everything renders terraform plan -detailed-exitcode useless as a drift detector in the pipeline.
The alternatives:
# For unique names: random_pet or random_id, which store their value
# in the state and only change if their keepers change.
resource "random_pet" "suffix" {
length = 2
keepers = {
# It is only regenerated if the environment changes. With no keepers,
# it never changes.
environment = var.environment
}
}
# For a stable UUID: uuidv5, which is deterministic.
> uuidv5("dns", "ecomarket.example.com")
"9d1a4ba0-3e4b-5e2c-9b02-3a1f8c7d6e5a"
> uuidv5("dns", "ecomarket.example.com") # the same, always
"9d1a4ba0-3e4b-5e2c-9b02-3a1f8c7d6e5a"
# For passwords: random_password, which stores them in the state
# (encrypted, with the backend configured in 03-03) instead of
# regenerating them.
resource "random_password" "db" {
length = 32
special = true
override_special = "!#$%&*()-_=+[]{}<>:?"
}uuidv5 takes a namespace (dns, url, oid, x500 or a UUID of your own) and a name, and always produces the same UUID. It is the right function when an API demands a UUID but you want it to be reproducible.
- Date and time, and perpetual drift
| Function | What it returns | When it is evaluated |
|---|---|---|
timestamp() |
The current instant in RFC 3339 UTC | On every evaluation, plan and apply |
plantimestamp() |
The instant the plan started | Once per plan; the apply reuses the saved plan's value |
timeadd(t, d) |
t shifted by the duration d |
Deterministic |
timecmp(a, b) |
-1, 0 or 1 |
Deterministic |
formatdate(fmt, t) |
Date formatting | Deterministic |
> timestamp()
"2026-09-22T14:31:07Z"
> timeadd(timestamp(), "48h")
"2026-09-24T14:31:07Z"
> formatdate("YYYY-MM-DD", timestamp())
"2026-09-22"
> formatdate("DD/MM/YYYY hh:mm", "2026-09-22T14:31:07Z")
"22/09/2026 14:31"
> timecmp("2026-09-22T00:00:00Z", timestamp())
-1The perpetual drift trap
# ❌ The classic mistake
resource "aws_instance" "web" {
tags = merge(local.common_tags, {
CreatedAt = timestamp() # ← changes on EVERY plan
})
}The result: every plan proposes updating the tag, the plan is never clean, -detailed-exitcode always returns 2, and the drift-detection pipeline (module 8) screams every day. Worse: if the attribute forced replacement, the instance would be recreated on every apply.
plantimestamp() (Terraform 1.5+) fixes half the problem: it is evaluated once when the plan starts, and the apply of a saved plan reuses that value, so that the plan and the apply agree. But the next plan still yields a new value, so the drift persists.
The correct solution is a resource that freezes the instant in the state:
terraform {
required_providers {
time = {
source = "hashicorp/time"
version = "~> 0.11"
}
}
}
# Evaluated ONCE, when the resource is born. Its value lives in the state
# and never changes again.
resource "time_static" "creation" {}
resource "aws_instance" "web" {
tags = merge(local.common_tags, {
CreatedAt = time_static.creation.rfc3339
})
}And if you want it refreshed when something specific changes:
resource "time_static" "deployment" {
# It is only regenerated when the application version changes.
triggers = {
version = var.image_version
}
}The other alternative, if the timestamp is informational and you do not need it in the state:
resource "aws_instance" "web" {
tags = merge(local.common_tags, {
CreatedAt = timestamp()
})
lifecycle {
# Terraform writes the value on creation and then ignores its changes.
ignore_changes = [tags["CreatedAt"]]
}
}It works, but it is worse: it hides that tag's drift forever, including drift caused by somebody else.
Where timestamp() is fine: in values that are not stored in a resource's state, such as the name of a local log file or a final snapshot with a unique name:
resource "aws_db_instance" "main" {
# The final snapshot name is only used at destruction time. Because the
# attribute is not compared against the cloud, it does not generate
# drift... but it does show up in the plan, so in practice a stable
# value is preferable here too.
final_snapshot_identifier = "${local.prefix}-final-${formatdate("YYYYMMDDhhmmss", plantimestamp())}"
skip_final_snapshot = var.environment != "prod"
}
- Networking:
cidrsubnet bit by bit
cidrsubnet bit by bitThis is module 5's most concrete debt. Since 05-02, EcoMarket's subnets have come out of here:
private_subnets = { for i, zone in var.zones : zone => cidrsubnet(var.cidr, var.subnet_bits, i) }
public_subnets = { for i, zone in var.zones : zone => cidrsubnet(var.cidr, var.subnet_bits, i + 100) }With var.cidr = "10.20.0.0/16" and var.subnet_bits = 8. Let us see exactly what that does.
The signature
prefix: the block to be split, with its mask."10.20.0.0/16".new_bits: how many bits are added to the mask. The result will have mask/16 + 8 = /24.network_number: the value written into those new bits. It must fit: with 8 bits, between 0 and 255.
Bit by bit
10.20.0.0/16 in binary:
10 . 20 . 0 . 0 00001010 . 00010100 . 00000000 . 00000000 └────────── 16 fixed bits ─────┘└─ 16 free bits ─┘
With new_bits = 8, Terraform takes the next 8 bits — the third octet — and writes the network_number there. The last 8 are left free for hosts.
network_number |
Third octet (binary) | Resulting CIDR | Range |
|---|---|---|---|
0 |
00000000 |
10.20.0.0/24 |
10.20.0.0 – 10.20.0.255 |
1 |
00000001 |
10.20.1.0/24 |
10.20.1.0 – 10.20.1.255 |
2 |
00000010 |
10.20.2.0/24 |
10.20.2.0 – 10.20.2.255 |
100 |
01100100 |
10.20.100.0/24 |
10.20.100.0 – 10.20.100.255 |
101 |
01100101 |
10.20.101.0/24 |
10.20.101.0 – 10.20.101.255 |
102 |
01100110 |
10.20.102.0/24 |
10.20.102.0 – 10.20.102.255 |
256 |
does not fit in 8 bits | Error | prefix extension of 8 does not accommodate a subnet numbered 256 |
With subnet_bits = 8 and three zones, EcoMarket's subnets come out like this:
> { for i, z in ["eu-west-1a","eu-west-1b","eu-west-1c"] : z => cidrsubnet("10.20.0.0/16", 8, i) }
{
"eu-west-1a" = "10.20.0.0/24"
"eu-west-1b" = "10.20.1.0/24"
"eu-west-1c" = "10.20.2.0/24"
}
> { for i, z in ["eu-west-1a","eu-west-1b","eu-west-1c"] : z => cidrsubnet("10.20.0.0/16", 8, i + 100) }
{
"eu-west-1a" = "10.20.100.0/24"
"eu-west-1b" = "10.20.101.0/24"
"eu-west-1c" = "10.20.102.0/24"
}Why the 100 offset
Now, at last, the full justification that module 5 left as a single sentence. Suppose there were no offset and the public subnets ran consecutively after the private ones:
| Zones | Private | Public |
|---|---|---|
| 2 zones | 10.20.0.0/24, 10.20.1.0/24 |
10.20.2.0/24, 10.20.3.0/24 |
| 3 zones | 10.20.0.0/24, 10.20.1.0/24, 10.20.2.0/24 |
10.20.3.0/24, 10.20.4.0/24, 10.20.5.0/24 |
Notice what happens when you go from two zones to three: the first public subnet moves from 10.20.2.0/24 to 10.20.3.0/24. And changing a subnet's CIDR is a destruction:
# aws_subnet.public["eu-west-1a"] must be replaced
-/+ resource "aws_subnet" "public" {
~ cidr_block = "10.20.2.0/24" -> "10.20.3.0/24" # forces replacementDestroying a public subnet means destroying what is inside it: the NAT gateway, the elastic IPs, the load balancer. Adding an availability zone would take the platform down. With the 100 offset, adding a zone only adds two new subnets and moves none of the existing ones. That is the whole reason, and it is an excellent one.
The same reasoning applies to the order of var.zones: if somebody reorders the list, the indices change and the subnets move. That is why the for_each runs over a map keyed by zone rather than over a list, as you learned in 02-03.
cidrsubnets: several blocks of different sizes
cidrsubnet gives one block; cidrsubnets gives several, potentially of different sizes, assigned consecutively:
> cidrsubnets("10.20.0.0/16", 4, 4, 8, 8)
[
"10.20.0.0/20", # 4 new bits -> /20, 4096 addresses
"10.20.16.0/20", # the next available /20
"10.20.32.0/24", # 8 new bits -> /24, aligned after the two /20s
"10.20.33.0/24",
]It is the right function when the subnets have different sizes — a big one for containers, small ones for databases — and you want Terraform to work out the alignment:
locals {
# EcoMarket's addressing design, in a single pass:
# two /20s for the workloads and four /24s for services.
blocks = cidrsubnets(var.cidr, 4, 4, 8, 8, 8, 8)
workload_cidr_a = local.blocks[0]
workload_cidr_b = local.blocks[1]
db_cidr = local.blocks[2]
cache_cidr = local.blocks[3]
management_cidr = local.blocks[4]
reserved_cidr = local.blocks[5]
}Maintenance warning: cidrsubnets assigns by position, so inserting a block in the middle shifts all the following ones and destroys their subnets. If you are going to use it, leave reserved slots at the end from day one, like the reserved_cidr in the example.
cidrhost and cidrnetmask
> cidrhost("10.20.1.0/24", 10)
"10.20.1.10"
> cidrhost("10.20.1.0/24", 1)
"10.20.1.1"
> cidrhost("10.20.1.0/24", -2) # negative indices count from the end
"10.20.1.254"
> cidrnetmask("10.20.1.0/24")
"255.255.255.0"cidrhost is for fixed addresses inside a computed subnet:
locals {
# AWS reserves the first five addresses of every subnet:
# .0 network, .1 router, .2 DNS, .3 reserved, .255 broadcast.
# The first usable one is .4, so we assign from .10 onwards
# to leave some headroom.
bastion_ip = cidrhost(module.network.public_subnets["eu-west-1a"].cidr, 10)
# The VPC DNS resolver is always at .2 of the VPC's CIDR.
vpc_dns_ip = cidrhost(var.cidr, 2)
}cidrnetmask only makes sense with IPv4 and with old tools that expect a mask rather than a prefix. It fails with IPv6.
| Function | Returns | When to use it |
|---|---|---|
cidrsubnet(p, n, i) |
One child CIDR | Subnets of the same size, index controlled by you |
cidrsubnets(p, n...) |
List of child CIDRs | Different sizes, automatic alignment |
cidrhost(p, i) |
An IP inside the CIDR | A fixed IP: bastion, DNS, gateway |
cidrnetmask(p) |
Mask in decimal notation | Compatibility with old tools (IPv4 only) |
- Files and templates
| Function | What it does | When it is evaluated |
|---|---|---|
file(path) |
Reads a text file as a string | At plan time; the file must exist |
filebase64(path) |
Reads a binary file, encoded | At plan time |
fileexists(path) |
true if the file exists |
At plan time |
fileset(dir, pattern) |
Set of matching paths | At plan time |
templatefile(path, vars) |
Renders a template with variables | At plan time |
templatestring(str, vars) |
The same, but from a string (1.9+) | At plan time |
dirname / basename / pathexpand |
Path manipulation | Deterministic |
abspath |
Absolute path | Depends on the working directory |
The first three read at plan time, not at apply time. A file that a script generates during the apply does not exist when file() tries to read it, and the error is no file exists at .... It is the reason why "generate a file with local-exec and read it with file()" flows never work.
fileset: uploading a whole directory to a bucket
locals {
static_dir = "${path.module}/../../web/dist"
# fileset returns a SET of paths relative to the base directory.
# The "**" pattern walks subdirectories.
static_files = fileset(local.static_dir, "**/*")
# Map of extension to MIME type. S3 does not infer it: without this,
# the browser downloads the .css files instead of applying them.
mime_types = {
".html" = "text/html; charset=utf-8"
".css" = "text/css; charset=utf-8"
".js" = "application/javascript; charset=utf-8"
".json" = "application/json"
".svg" = "image/svg+xml"
".png" = "image/png"
".jpg" = "image/jpeg"
".webp" = "image/webp"
".woff2" = "font/woff2"
}
}
resource "aws_s3_object" "static" {
# One resource per file. The for_each key is the relative path,
# which is stable: if you add a file, the others do not move.
for_each = local.static_files
bucket = aws_s3_bucket.web.id
key = each.value
source = "${local.static_dir}/${each.value}"
# Without an etag, changing a file's contents generates no plan at all.
etag = filemd5("${local.static_dir}/${each.value}")
# regex extracts the extension; lookup gives a generic type if it is
# not in the map.
content_type = lookup(
local.mime_types,
try(regex("\\.[^.]+$", each.value), ""),
"application/octet-stream",
)
cache_control = startswith(each.value, "assets/") ? "public, max-age=31536000, immutable" : "public, max-age=300"
}Five decisions in that block:
for_eachover the set of paths instead ofcount: adding a file does not shift the others.etag = filemd5(...): without it, editing a.cssproduces no plan, becausesourceis a path that has not changed.- Explicit
content_type: S3 does not infer it from the name and serves everything asbinary/octet-stream. tryaroundregex: a file with no extension would fail the whole plan.- Differentiated
cache_control: assets with a hash in the name are cached for a year; HTML, for five minutes.
Scale warning.
filesetover a directory with thousands of files creates thousands of resources. The state grows, the plan takes minutes and theapplymakes one API call per file. Beyond a few hundred, the right approach is to sync withaws s3 syncfrom the pipeline and let Terraform manage only the bucket and its configuration. Terraform is not a content deployment tool.
templatefile taken apart
Signature:
It renders the file as a template, replacing the interpolations with values from the object. EcoMarket's template, templates/cloud-init.yaml.tftpl:
#cloud-config
package_update: true
write_files:
- path: /etc/ecomarket/app.env
permissions: '0640'
owner: ecomarket:ecomarket
content: |
ENVIRONMENT=${environment}
APP_VERSION=${app_version}
DB_HOST=${db_host}
DB_PORT=${db_port}
DB_NAME=ecomarket
DB_SECRET_NAME=${db_secret}
S3_BUCKET=${bucket}
AWS_REGION=${region}
- path: /etc/ecomarket/startup.sh
permissions: '0750'
content: |
#!/usr/bin/env bash
set -euo pipefail
# $${} escapes the $ so that the SHELL interprets it, not Terraform.
# Without the double $, Terraform would look for a variable named
# DB_SECRET_NAME in the template object and fail with "Invalid template interpolation".
SECRET=$(aws secretsmanager get-secret-value \
--secret-id "$${DB_SECRET_NAME}" \
--region "$${AWS_REGION}" \
--query SecretString --output text)
echo "DB_PASSWORD=$${SECRET}" >> /etc/ecomarket/app.env
chmod 0640 /etc/ecomarket/app.env
%{ for package in packages ~}
# Required package: ${package}
%{ endfor ~}
packages:
%{ for package in packages ~}
- ${package}
%{ endfor ~}
%{ if environment == "prod" ~}
# Production only: the full observability agent.
- amazon-cloudwatch-agent
%{ endif ~}
runcmd:
- [ /etc/ecomarket/startup.sh ]
- [ systemctl, enable, --now, ecomarket ]And the call:
locals {
cloud_init = templatefile("${path.module}/templates/cloud-init.yaml.tftpl", {
environment = var.environment
app_version = var.image_version
db_host = local.db_host
db_port = local.db_port
db_secret = aws_secretsmanager_secret.db.name
bucket = aws_s3_bucket.images.id
region = data.aws_region.current.name
packages = ["postgresql-client", "awscli", "jq"]
})
}The complete flow, from the template to the machine:
flowchart TD
P["cloud-init.yaml.tftpl<br/><i>template in the repository</i>"] --> T["templatefile(path, object)"]
V["Variables object<br/>db_host, bucket, secret,<br/>environment, region, packages"] --> T
T --> E1["${...} → interpolated by Terraform"]
T --> E2["$${...} → left literal<br/>for the SHELL"]
T --> E3["%{ for } / %{ if } → directives"]
E1 --> R["Rendered YAML"]
E2 --> R
E3 --> R
R --> B["base64gzip()"]
B --> U["launch template user_data<br/><i>16 KB limit</i>"]
U --> M["cloud-init on the instance"]
R -.->|"⚠️ left in the clear in<br/>the state and the plan"| S["terraform.tfstate"]
The five rules of templatefile:
| Rule | Detail |
|---|---|
| 1. The second argument is an object | Its keys are the names available inside the template. Nothing else is available |
| 2. There is no access to the outer scope | var.environment does not work inside the template: you have to pass it explicitly |
3. ${...} interpolates |
It accepts any HCL expression, functions included |
4. $${...} escapes |
It produces a literal ${...}. Essential for shell variables |
5. Directives are %{ ... } |
%{ if }, %{ for }, %{ endif }, %{ endfor }; the tilde ~ trims whitespace |
Rule 2 is the one that trips people up most. A template is a pure function: it only sees what you pass it. If adding a line to the template makes the plan fail with Invalid template interpolation value: there is no variable named "X", the answer is to add X to the call's object.
Rule 4 is what explains the $${DB_SECRET_NAME} in the example, and what we already mentioned in 05-05 without spelling it out. Inside the template, ${VAR} is resolved by Terraform; for a literal ${VAR} to reach the final file — which is what the shell needs — you write $${VAR}.
The tilde in %{ for package in packages ~} trims the whitespace surrounding the directive. Without it, each iteration leaves a blank line and the resulting YAML, although valid, is unreadable. With YAML, moreover, one extra line break in the wrong place can change the structure.
Checking the result before applying:
# Render the template and dump it to a file
$ terraform console -var-file=dev.tfvars <<'EOF' | sed 's/\\n/\n/g'
local.cloud_init
EOF
# Or better, a temporary output and jq
$ terraform output -raw rendered_cloud_init > /tmp/cloud-init.yaml
$ cloud-init schema --config-file /tmp/cloud-init.yaml
Valid schema /tmp/cloud-init.yamlWhen NOT to use templatefile
| Situation | Alternative |
|---|---|
| The output is JSON | jsonencode: it validates the syntax and lets you compose with for |
| The output is code-generated YAML | yamlencode: impossible to break the indentation |
| The template has more than 30 lines of conditional logic | The data should arrive already decided, not be decided in the template |
| The file is a complex configuration script | Packer or Ansible (05-05) |
| The template is not on disk | templatestring (section 12) |
| You are only substituting one or two variables | Direct interpolation in a <<-EOT string |
And a security warning inherited from module 5: whatever you render with templatefile ends up in the state and in the plan file, in the clear. If you pass a secret into the variables object, that secret is in the state. The correct pattern is still to pass the name of the secret and let the instance resolve the value with its own identity.
- Types and conversion
The to* family
| Function | Converts to | Fails if |
|---|---|---|
tostring |
String | The value is a collection |
tonumber |
Number | The string is not numeric |
tobool |
Boolean | It is not true/false/"true"/"false" |
tolist |
List | It is not a collection |
toset |
Set | It is not a collection; loses order and duplicates |
tomap |
Map | The values are not of a homogeneous type |
> tonumber("5432")
5432
> tonumber("five")
Error: Invalid function argument: cannot convert "five" to number
> toset(["a", "b", "a"])
toset([ "a", "b" ]) # duplicate removed, alphabetical order
> tolist(toset(["c", "a", "b"]))
["a", "b", "c"] # the original order is gone!Converting to a set and back is a classic source of surprises: a set has no order, and converting it back to a list gives you alphabetical order, not the order it was in.
type() is a debugging function, available only in terraform console:
try: module 5's debt
try evaluates its arguments in order and returns the first one that does not produce an error:
Real cases from EcoMarket:
locals {
# 1. Optional attribute of an input object.
cost_center = try(local.current.cost_center, "CC-GENERAL")
# 2. Output of a module that may not exist depending on the environment.
replica_endpoint = try(module.data.replica_endpoint, null)
# 3. Defensive decomposition of the database endpoint.
db_port = try(tonumber(split(":", module.data.endpoint)[1]), 5432)
# 4. File extension, for the MIME type map.
extension = try(regex("\\.[^.]+$", each.value), "")
}The two rules of try:
- It only catches type and access errors: a non-existent index, a missing attribute, an impossible conversion. It does not catch a provider error or an API failure.
- It must wrap small expressions. A
tryaround twenty lines turns any error — including a typo in a variable name — into the default value, silently. That is the worst possible use and it is very common.
# ❌ Bad: if there is a typo in "private_subnets", the result is []
# and nobody notices until the infrastructure comes out wrong.
subnet_ids = try([for z, s in module.network.privatte_subnets : s.id], [])
# ✅ Good: try only where absence is legitimate.
subnet_ids = [for z, s in module.network.private_subnets : s.id]can: try that returns a boolean
> can(tonumber("5432"))
true
> can(tonumber("five"))
false
> can(regex("^pr-\\d+$", terraform.workspace))
truecan is the validation function, and you will see it again in 06-05:
variable "cidr" {
type = string
validation {
# cidrnetmask fails if the value is not a valid IPv4 CIDR.
# can() turns that failure into false, which is what validation expects.
condition = can(cidrnetmask(var.cidr))
error_message = "The CIDR must be a valid IPv4 block, for example 10.20.0.0/16."
}
}
variable "contact_email" {
type = string
default = "[email protected]"
validation {
condition = can(regex("^[^@]+@[^@]+\\.[^@]+$", var.contact_email))
error_message = "The contact must be a valid email address."
}
}sensitive and nonsensitive
# Mark a computed value as sensitive, even if its source was not.
locals {
connection_string = sensitive(
"postgresql://ecomarket:${var.db_password}@${local.db_host}:${local.db_port}/ecomarket"
)
}
# Remove the sensitive mark from a part that is NOT sensitive.
output "db_host" {
# module.data.endpoint comes marked as sensitive because the module
# declared it that way, but the host name is not a secret:
# the secret is the password. nonsensitive unmarks it.
value = nonsensitive(split(":", module.data.endpoint)[0])
}Sensitivity propagates. If a sensitive value enters an expression, the entire result is sensitive. That is the correct default, and it is also what turns a jsonencode of a policy containing a sensitive value into an entirely masked policy in the plan, impossible to review.
nonsensitive is the escape valve, and it has to be used with judgement: only when you have verified that the specific part you are extracting is not secret. Wrapping an entire sensitive value in nonsensitive to "get rid of the warning" means exposing a secret in the plan and in the pipeline logs.
templatestring and templates that are not on disk
templatestring and templates that are not on diskTerraform 1.9 added templatestring, which renders a template coming from a string rather than a file:
Its reason for existing: until 1.9 there was no way to render a template that was not on disk at plan time. Now the template can come from a variable, a module parameter or a data source:
# The notice message template is maintained by the support team
# in an SSM parameter, not in the infrastructure repository.
data "aws_ssm_parameter" "notice_template" {
name = "/ecomarket/${var.environment}/notice-template"
}
locals {
notice_message = templatestring(data.aws_ssm_parameter.notice_template.value, {
environment = var.environment
url = "https://${module.app.load_balancer_dns}"
contact = "[email protected]"
})
}And its most elegant use: a template as a module variable, which lets whoever uses the module decide the format without the module having to carry template files for every case:
variable "name_template" {
description = "Template for resource names. Available variables: project, environment, component."
type = string
default = "$${project}-$${environment}-$${component}"
}
locals {
name = templatestring(var.name_template, {
project = var.project
environment = var.environment
component = var.component
})
}Notice the $${...} in the default value: inside a .tf, ${...} would be interpolated at the moment the variable is read. The double $ makes it reach templatestring literally.
| Function | Source of the template | Available since |
|---|---|---|
templatefile |
A file on disk, present at plan time | Always |
templatestring |
Any string, even a computed one | 1.9 |
A practical rule: if the template is in the repository, templatefile. If it comes from outside or is configurable, templatestring.
- Index table: what I need to do → which function to use
| I need to... | Function | Note |
|---|---|---|
| Compose a name with a fixed format | format, join |
format("%s-%s-%03d", ...) |
| Make a name comply with the cloud's rules | lower + replace + substr + trimsuffix |
Test the edge case in the console |
| Split an endpoint into host and port | split |
With try(tonumber(...), default) |
| Remove the trailing dot from an FQDN | trimsuffix |
AWS DNS names sometimes carry one |
| Check a prefix | startswith |
Better than substr(x,0,3) == "pr-" |
| Add tags to the common ones | merge |
The last argument wins |
| Join two CIDR lists without duplicates | distinct(concat(a, b)) |
The order is preserved |
| Cartesian product environment × zone | flatten with nested for, or setproduct |
Then to a map for for_each |
| A map value that may not exist | lookup(m, k, default) |
If it must exist, m[k] |
| The first non-empty value of several | coalesce |
It also discards "" |
Reference a resource with a conditional count |
one(resource[*].attr) |
Returns null if there is none |
| Limit the zones to the first three | slice(list, 0, 3) |
Combine with sort for stability |
| Spread N resources across M zones cyclically | element(zones, count.index) |
It wraps; careful outside this case |
| Check that a value is allowed | contains(list, value) |
For validation and precondition |
| Validate a condition over every element | alltrue([for ...]) |
alltrue([]) is true |
| Write an IAM policy | jsonencode |
Never a literal string |
| Read external JSON configuration | jsondecode(file(...)) |
The file must exist at plan time |
| Generate cloud-init from HCL | yamlencode |
Add #cloud-config by hand |
Encode user_data |
base64encode, base64gzip |
16 KB limit in AWS |
| Detect that a local file changed | filemd5 / filesha256 |
etag on aws_s3_object |
| A stable, unique identifier | random_pet / uuidv5 |
Never uuid() or bcrypt |
| A timestamp that does not drift | time_static |
Never timestamp() in an attribute |
| Compute subnets of the same size | cidrsubnet(cidr, bits, i) |
With an offset for the public ones |
| Compute subnets of different sizes | cidrsubnets(cidr, n...) |
Reserve slots at the end |
| A fixed IP inside a subnet | cidrhost(cidr, n) |
AWS reserves the first five |
| Upload a directory to a bucket | fileset + for_each |
Only up to a few hundred files |
| Render cloud-init with variables | templatefile |
$${} for shell variables |
| Render a template that comes from outside | templatestring |
1.9+ |
| Access something that may not exist | try(expr, default) |
Small expressions |
Validate an input in variable |
can(...) inside condition |
See 02-02 |
| Publish a non-secret part of a sensitive value | nonsensitive |
Only after verifying what you extract |
| Find out what type something is | type(...) in the console |
Console only |
- Type errors when composing functions
Five errors that come up again and again when chaining functions, with their real message and their cause.
14.1 A list of lists where a list is expected
Error: Invalid value for input variable The given value is not suitable for var.rules: element 0: string required.
Cause: two nested for expressions produce a list of lists. Solution: flatten.
14.2 A set where an indexable list is expected
Cause: fileset, toset and for_each produce sets, and a set cannot be indexed. fileset(...)[0] fails. Solution: tolist(...) first, or sort(tolist(...)) if you need a deterministic order.
14.3 A map with values of different types
Error: Invalid function argument Invalid value for "values" parameter: all arguments must have the same type.
Cause: a for that produces a map whose values are not homogeneous — some objects with three fields and others with four. It is very common when try is used inside the for and some branches return null while others return an object. Solution: guarantee that every branch returns the same shape, padding absent fields with null.
# ❌ The objects do not have the same shape
> { for e, c in var.environments : e => c.create_replica ? { replica = "yes", class = c.db_class } : { replica = "no" } }
# ✅ All the objects have the same fields
> { for e, c in var.environments : e => {
replica = c.create_replica ? "yes" : "no"
class = c.create_replica ? c.db_class : null
} }14.4 A number where a whole number is expected
Error: Invalid count argument The given "count" argument value is unsuitable: must be a whole number.
Cause: count = length(x) / 2 with an odd length(x). Solution: ceil or floor.
14.5 A value unknown at plan time
Error: Invalid for_each argument The "for_each" value depends on resource attributes that cannot be determined until apply.
Cause: the for_each depends on an attribute that does not exist yet — the ARN of a resource that is going to be created in this very apply. No function fixes this, because it is not a type problem but an evaluation-order one. Solution: make the for_each depend on values known at plan time (variables, locals derived from variables) and not on resource attributes. This limitation reappears in 06-05 with conditions, and its full diagnosis is in 09-02.
The debugging method
When a composed expression fails, take it apart from the inside out in the console:
# The expression that fails:
# { for c in flatten([for s in local.services : [for z in local.zones : {...}]]) : c.key => c }
# Step 1: what is in the inputs?
> local.services
["s3", "secretsmanager", "ssm", "ec2messages"]
> local.zones
["eu-west-1a", "eu-west-1b", "eu-west-1c"]
# Step 2: the inner for, for ONE service
> [for z in local.zones : { service = "s3", zone = z, key = "s3-${z}" }]
# Step 3: both for expressions, without flatten. Here you see the list of lists.
> [for s in local.services : [for z in local.zones : {...}]]
# Step 4: with flatten
> flatten([for s in local.services : [for z in local.zones : {...}]])
> length(flatten(...))
12
# Step 5: the outer for
> { for c in flatten(...) : c.key => c }Five steps of two seconds each versus five plan runs of half a minute. That difference is the whole lesson of section 1.
Common Mistakes and Tips
Using uuid() or bcrypt() in a resource attribute. They change on every evaluation, the plan never converges and -detailed-exitcode stops being useful for detecting drift. Use random_pet, random_password or uuidv5.
Using timestamp() in a tag. The same perpetual drift. time_static freezes the value in the state; plantimestamp() only fixes the consistency between plan and apply, not the drift.
Wrapping large expressions in try. It turns any error — a typo in a variable name included — into the default value, silently. try must surround the smallest possible expression.
Confusing lookup(m, k) with lookup(m, k, d). Without a third argument, lookup fails exactly like indexing and only adds noise. If the key must exist, use m[k]; if it may be missing, supply the third argument.
Expecting merge to deep merge. It is shallow: a nested map is replaced wholesale and the keys you do not repeat vanish. Terraform has no deepmerge.
Indexing the result of fileset or toset. A set has no indices. tolist() first, and sort() if the order matters.
Forgetting flatten with nested for expressions. The result is a list of lists and for_each fails with a message about types that never mentions the word flatten.
Forgetting the double $ on shell variables inside templatefile. The error is there is no variable named "X" and it points at the template. The fix is $${X}.
Using var.something inside a template. Templates only see what you pass in the second argument. There is no outer scope.
Passing a secret into templatefile's variables object. The rendered result lives in the state and in the plan file, in the clear. Pass the name of the secret.
file() over a file the apply generates. file is evaluated at plan time. A file created by local-exec does not exist yet.
fileset over a large directory. Thousands of resources, a huge state and a plan that takes minutes. Beyond a few hundred files, aws s3 sync from the pipeline.
Overusing nonsensitive. It is an escape valve for publishing a verifiably non-secret part, not a way to silence warnings. A nonsensitive over a complete connection string exposes the password in the plan and in the pipeline logs.
Tip: open the console before the editor. The reflex of testing an expression in terraform console before writing it into a .tf cuts the debugging loop from thirty seconds to two, and avoids unnecessary API calls.
Tip: when looking for a function, search by what you need to do, not by its name. The documentation's "related functions" section is the best index there is: if you arrived at lookup and what you wanted was coalesce, the link is right there.
Exercises
Exercise 1: the plan that never converges
A colleague has written this backup bucket module and complains that "Terraform wants to recreate the bucket on every apply" and that "the pipeline's drift detection warns every day even though nobody touches anything".
resource "aws_s3_bucket" "backups" {
bucket = "ecomarket-backups-${uuid()}"
tags = {
Project = "ecomarket"
CreatedAt = timestamp()
Verified = bcrypt(var.verification_token)
}
}
resource "aws_s3_object" "manifest" {
bucket = aws_s3_bucket.backups.id
key = "manifest.json"
source = "${path.module}/manifest.json"
}- Identify four distinct problems (three about convergence and one that makes a change go unnoticed).
- Rewrite the whole block fixing all four.
- Explain what you would tell your colleague about how to spot this kind of problem before applying.
Exercise 2: addressing for the new region
EcoMarket is opening in Milan with the block 10.40.0.0/16. The network design requested is:
- Three private application subnets, one per zone, of size
/22(so that plenty of containers fit). - Three public subnets, one per zone, of size
/24(they only host NAT gateways and the load balancer). - Three database subnets, one per zone, of size
/26. - Reserved space to grow without moving any of the above.
Requirements:
- Write the
localsthat compute the nine CIDRs, using the right function in each case and justifying the choice. - The CIDRs must not move if a fourth availability zone is added tomorrow.
- Compute, with Terraform functions, how many usable addresses each application subnet has in AWS.
- Write the console expression that verifies that no pair of subnets overlaps.
Exercise 3: Milan's cloud-init template
Write templates/cloud-init-milan.yaml.tftpl and its templatefile call so that the instance:
- Writes
/etc/ecomarket/app.envwith the environment, the region, the database host and port (broken out of theendpoint), the bucket name and the name of the secret. - Writes a script that reads the password with the instance's identity and appends it to the environment file.
- Installs a list of packages received as a variable.
- Additionally installs the observability agent only if the environment is
prod. - Is correctly encoded for an
aws_launch_template'suser_data, checking that it does not exceed 16 KB.
Point out in comments every place where the $${} escape is needed, and explain why.
Solutions
Solution 1
1. The four problems:
| # | Problem | Effect |
|---|---|---|
| 1 | uuid() in bucket |
A different name on every plan → forces replacement on every apply. The bucket is destroyed and recreated, losing the backups |
| 2 | timestamp() in tags.CreatedAt |
The tag changes on every plan → the plan is never clean, -detailed-exitcode is always 2 |
| 3 | bcrypt() in tags.Verified |
A fresh random salt on every evaluation → the same drift. And on top of that it stores a hash of a token in a tag, which is sensitive information in a field visible from the console |
| 4 | aws_s3_object with no etag |
Editing manifest.json produces no plan at all: source is a path that has not changed. The change goes unnoticed |
The first three are convergence; the fourth is the opposite: a real change that is not detected.
2. The corrected version:
# A unique and STABLE name: random_pet stores its value in the state.
# With no keepers, it never changes.
resource "random_pet" "backups_suffix" {
length = 2
}
# Creation instant frozen in the state.
resource "time_static" "backups_creation" {}
resource "aws_s3_bucket" "backups" {
bucket = "ecomarket-backups-${random_pet.backups_suffix.id}"
tags = merge(local.common_tags, {
Name = "${local.prefix}-backups"
CreatedAt = time_static.backups_creation.rfc3339
# The verification token does NOT go in a tag. If integrity needs
# verifying, use a deterministic hash of the CONTENT, not of the
# token, and somewhere not visible from the console.
})
lifecycle {
# A backup bucket must never be destroyable by accident.
# This matters more than everything above.
prevent_destroy = true
}
}
resource "aws_s3_object" "manifest" {
bucket = aws_s3_bucket.backups.id
key = "manifest.json"
source = "${path.module}/manifest.json"
# Without an etag, changing the file generates no plan. S3 uses MD5 for
# its ETag, so filemd5 here is mandatory rather than a choice.
etag = filemd5("${path.module}/manifest.json")
}3. How to spot it before applying:
- Run
terraform plantwice in a row without touching anything. If the second plan is not empty, there is a convergence problem. It is the cheapest check there is and it should be in the pipeline:
terraform apply -auto-approve
terraform plan -detailed-exitcode || echo "ERROR: the plan does not converge"- Search the code for non-deterministic functions:
- Review rule:
uuid(),bcrypt()andtimestamp()must never appear in a resource attribute. If they show up in a pull request, it is an automatic rejection.
Solution 2
1. The locals:
locals {
milan_cidr = "10.40.0.0/16"
zones = ["eu-south-1a", "eu-south-1b", "eu-south-1c"]
# ── Application: /22 = 16 + 6 new bits. Indices 0, 1, 2.
# With 6 bits there is room for 64 /22 blocks; we use 3 and leave 61 free.
# We use cidrsubnet (not cidrsubnets) because they are all the same
# size and we want to control the index explicitly: that way a zone's
# index does NOT depend on how many zones there are.
app_subnets = {
for i, z in local.zones : z => cidrsubnet(local.milan_cidr, 6, i)
}
# 10.40.0.0/22, 10.40.4.0/22, 10.40.8.0/22
# ── Public: /24 = 16 + 8 new bits. Offset from 100 onwards so that they
# do NOT collide with the application ones and so that adding a zone
# moves nothing.
public_subnets = {
for i, z in local.zones : z => cidrsubnet(local.milan_cidr, 8, i + 100)
}
# 10.40.100.0/24, 10.40.101.0/24, 10.40.102.0/24
# ── Database: /26 = 16 + 10 new bits. Offset from 800 onwards, which
# in 10 bits lands at 10.40.200.0/26 and the following ones.
db_subnets = {
for i, z in local.zones : z => cidrsubnet(local.milan_cidr, 10, i + 800)
}
# 10.40.200.0/26, 10.40.200.64/26, 10.40.200.128/26
}Justification of cidrsubnet over cidrsubnets: cidrsubnets assigns consecutive positions, so inserting a block in the middle shifts all the following ones and destroys their subnets. Since requirement 2 demands that nothing moves when a zone is added, explicit control of the index is needed, and only cidrsubnet gives you that.
2. Verifying requirement 2 (adding eu-south-1d as a fourth zone):
> { for i, z in ["eu-south-1a","eu-south-1b","eu-south-1c","eu-south-1d"] : z => cidrsubnet("10.40.0.0/16", 6, i) }
{
"eu-south-1a" = "10.40.0.0/22" # unchanged
"eu-south-1b" = "10.40.4.0/22" # unchanged
"eu-south-1c" = "10.40.8.0/22" # unchanged
"eu-south-1d" = "10.40.12.0/22" # new
}The three existing ones do not move because their index depends on their position in the list, not on the size of the list. The indispensable condition is that new zones are appended at the end of local.zones; if somebody reorders them alphabetically and a new zone ends up in the middle, the indices change and the subnets are destroyed. That is why it is worth pinning the order with an explicit map rather than relying on data.aws_availability_zones:
locals {
# Fixed index per zone: immune to reordering.
zone_index = {
"eu-south-1a" = 0
"eu-south-1b" = 1
"eu-south-1c" = 2
"eu-south-1d" = 3 # appended at the end, never in the middle
}
app_subnets = {
for z, i in local.zone_index : z => cidrsubnet(local.milan_cidr, 6, i)
}
}3. Usable addresses in a /22 subnet in AWS:
locals {
app_host_bits = 32 - tonumber(split("/", values(local.app_subnets)[0])[1]) # 32 - 22 = 10
app_addresses = pow(2, local.app_host_bits) # 1024
# AWS reserves 5 addresses per subnet: .0 network, .1 router, .2 DNS,
# .3 reserved for future use and the last one, broadcast.
app_usable = local.app_addresses - 5 # 1019
}4. Checking for overlaps in the console:
# All the CIDRs together
> local.all_cidrs = concat(
values(local.app_subnets),
values(local.public_subnets),
values(local.db_subnets),
)
# 1. None repeated (a necessary condition, not a sufficient one)
> length(local.all_cidrs) == length(distinct(local.all_cidrs))
true
# 2. All inside the VPC block: compare the first and last address
# of each subnet with those of the parent CIDR.
> alltrue([
for c in local.all_cidrs :
cidrhost(c, 0) >= cidrhost(local.milan_cidr, 0)
])
true
# 3. No pairwise overlaps: for every distinct pair, the first address
# of one cannot fall inside the range of the other.
# The exact check with Terraform functions is awkward because there
# is no "cidrcontains" function. The practical approach is to
# compare the numeric ranges of the third octets, or — better —
# use a precondition over the sorted list:
> sort(local.all_cidrs)
[
"10.40.0.0/22",
"10.40.100.0/24",
"10.40.101.0/24",
"10.40.102.0/24",
"10.40.200.0/26",
"10.40.200.128/26",
"10.40.200.64/26",
"10.40.4.0/22",
"10.40.8.0/22",
]Notice the order sort produces: it is lexicographic, not numeric, so 10.40.100.0/24 comes before 10.40.4.0/22. It is a reminder that sort sorts strings, and that for serious network checks the right answer is a network analysis tool or a test with terraform test, not a clever HCL expression.
Solution 3
templates/cloud-init-milan.yaml.tftpl:
#cloud-config
package_update: true
package_upgrade: false
packages:
%{ for package in packages ~}
- ${package}
%{ endfor ~}
%{ if environment == "prod" ~}
- amazon-cloudwatch-agent
%{ endif ~}
write_files:
# Point 1: the environment file, with no secret inside it.
- path: /etc/ecomarket/app.env
permissions: '0640'
owner: ecomarket:ecomarket
content: |
ENVIRONMENT=${environment}
AWS_REGION=${region}
DB_HOST=${db_host}
DB_PORT=${db_port}
DB_NAME=ecomarket
S3_BUCKET=${bucket}
# Only the NAME of the secret. The value is resolved by the instance
# with its IAM profile (see 05-02 and 05-05).
DB_SECRET_NAME=${db_secret}
# Point 2: the script that resolves the password at boot time.
- path: /etc/ecomarket/startup.sh
permissions: '0750'
owner: root:root
content: |
#!/usr/bin/env bash
set -euo pipefail
# $${} ESCAPE: everything that follows is a SHELL variable.
# Without the double $, Terraform would look for variables named
# "DB_SECRET_NAME", "AWS_REGION" and "SECRET" in the template
# object and would fail the plan with:
# "there is no variable named DB_SECRET_NAME"
source /etc/ecomarket/app.env
SECRET=$(aws secretsmanager get-secret-value \
--secret-id "$${DB_SECRET_NAME}" \
--region "$${AWS_REGION}" \
--query SecretString --output text)
# $${SECRET} escaped as well: it is a variable of the script.
PASSWORD=$(echo "$${SECRET}" | jq -r '.password')
umask 027
echo "DB_PASSWORD=$${PASSWORD}" >> /etc/ecomarket/app.env
chown ecomarket:ecomarket /etc/ecomarket/app.env
# Connectivity check before starting the service.
PGPASSWORD="$${PASSWORD}" psql \
-h "$${DB_HOST}" -p "$${DB_PORT}" -U ecomarket -d ecomarket \
-c 'SELECT 1' >/dev/null
runcmd:
- [ /etc/ecomarket/startup.sh ]
- [ systemctl, enable, --now, ecomarket ]The call:
locals {
# Defensive decomposition of the endpoint (section 3).
db_parts = split(":", module.data.endpoint)
db_host = local.db_parts[0]
db_port = try(tonumber(local.db_parts[1]), 5432)
milan_cloud_init = templatefile("${path.module}/templates/cloud-init-milan.yaml.tftpl", {
environment = var.environment
region = data.aws_region.current.name
db_host = local.db_host
db_port = local.db_port
bucket = aws_s3_bucket.images.id
# The NAME, not the value. Module 5's security point.
db_secret = aws_secretsmanager_secret.db.name
packages = ["postgresql-client", "awscli", "jq"]
})
}
resource "aws_launch_template" "web_milan" {
name_prefix = "${local.prefix}-web-"
image_id = data.aws_ami.ecomarket.id
instance_type = local.current.web_class
user_data = base64gzip(local.milan_cloud_init)
lifecycle {
create_before_destroy = true
# Point 5: checking AWS's 16 KB limit.
precondition {
condition = length(base64gzip(local.milan_cloud_init)) < 16384
error_message = format(
"The compressed user_data takes up %d bytes and AWS's limit is 16384. Move the configuration into the Packer image or into a script downloaded from the bucket.",
length(base64gzip(local.milan_cloud_init)),
)
}
}
}The $${} escapes, one by one:
| Location | Why |
|---|---|
$${DB_SECRET_NAME} |
A shell variable read with source. Terraform does not know it |
$${AWS_REGION} |
Likewise. Although region does exist in the object, here we want the one from the environment file |
$${SECRET} |
A local variable of the script, created at run time |
$${PASSWORD} |
Likewise |
$${DB_HOST}, $${DB_PORT} |
From the environment file |
The mnemonic rule: one $ if Terraform knows the value; two if the value only exists once the machine boots.
Verification before applying:
# Compressed and uncompressed size
$ terraform console -var-file=milan.tfvars
> length(base64gzip(local.milan_cloud_init))
2410
> length(base64encode(local.milan_cloud_init))
8120
# Validate the rendered YAML
$ terraform output -raw cloud_init_render > /tmp/ci.yaml
$ cloud-init schema --config-file /tmp/ci.yaml
Valid schema /tmp/ci.yamlThe lifecycle precondition is the safety net for when somebody adds three more packages a year from now and nobody remembers the limit. Preconditions are precisely the subject of 06-05.
Conclusion
Functions stop being a list to look things up in once they are organised by what you need to do and tested before being written.
terraform consoleis the central instrument, not a curiosity. It loads the directory's variables and state, lets you inspect module outputs and take expressions apart from the inside out. A two-second debugging loop versus a thirty-second one.- You cannot define your own functions. The alternatives, in order: a
localwith a descriptive name, a module with no resources when the transformation repeats across teams, and theprovider::functions that some providers have contributed since 1.8. mergeis the engine of EcoMarket's tagging in four layers — base, environment,.tfvarsextras, resource-specific — where the last argument wins. It is shallow: nested maps are replaced wholesale.flattenwith nestedforexpressions solves the Cartesian product environment × zone, service × zone, group × port. Without it,for_eachreceives a list of lists and fails.cidrsubnet(cidr, bits, i)writesiinto the bits following the mask. With10.20.0.0/16and 8 bits, the index lands in the third octet. EcoMarket's 100 offset exists so that adding an availability zone moves no existing subnet, because moving a CIDR means destroying the subnet and everything inside it.cidrsubnetsassigns by position, so inserting a block in the middle shifts the following ones. Reserve slots at the end from day one.templatefileis a pure function: it sees only the object you pass it, there is novar.*inside.$${}escapes for the shell,%{ if }and%{ for ~}are the directives, and whatever you render ends up in the state and in the plan file, in the clear.jsonencodefor IAM policies,yamlencodefor code-generated manifests,templatefilewhen the systems team maintains the file. Each has its own territory.uuid(),bcrypt()andtimestamp()break idempotence: they change on every evaluation, the plan never converges and drift detection stops working. Their replacements arerandom_pet/random_password,uuidv5andtime_static.trycatches type and access errors, not API failures, and it must wrap the smallest possible expression.canis its boolean version and is the basis of validations.nonsensitiveis an escape valve to be used with judgement, not a way to silence warnings.- The five recurring type errors — list of lists, indexed set, heterogeneous map, non-whole number and a value unknown at plan time — have concrete solutions, except the last, which is not a type problem but an evaluation-order one.
The next lesson, Dynamic Blocks, settles module 5's third debt. dynamic appeared three times with no explanation: in the dynamic "tag" of the AWS auto scaling group, which you have just seen again here fed by merge; in the dynamic "delegation" of the Azure subnets; and in the dynamic "cdn_policy" of the GCP global load balancer. You will see the complete syntax — for_each, iterator, labels, content — the table of what can and cannot be generated dynamically, nested dynamic blocks and their readability cost, and above all the criterion for deciding when a repeated block should really be a separate resource, as we already did with security group rules in module 5.
