Subscribe

Variables, outputs, locals and for_each without copy-paste

Turning three copy-pasted S3 buckets into one resource with for_each, with typed variables, validation blocks, locals, outputs and a tfvars file per environment, plus why I pick for_each over count.

Variables, outputs, locals and for_each without copy-paste

Every Terraform project I've seen starts the same way. You need a bucket, so you write a resource. Then you need another one, so you copy the block and change two words. Then a third. A month later someone changes the tags on two of them and forgets the third.

In this blog we will take three copy-pasted S3 buckets and turn them into one resource with for_each, driven by typed variables, with a couple of validation rules, some locals, outputs and one .tfvars file per environment. Level: beginner. You should know plan and apply from the first hands-on post. I used Terraform 1.17.1 and AWS provider 6.73.0.

The buckets belong to shorty, the small URL shortener that a lot of the tutorials here build. The design post has the background, but you don't need it for this one.

The copy-paste version

Here is where we start. Three buckets for the dev environment: logs, uploads, backups. Only backups has versioning.

resource "aws_s3_bucket" "logs" {
  bucket = "shorty-dev-logs-111122223333"
  tags = {
    Project     = "shorty"
    Environment = "dev"
  }
}

resource "aws_s3_bucket" "uploads" {
  bucket = "shorty-dev-uploads-111122223333"
  tags = {
    Project     = "shorty"
    Environment = "dev"
  }
}

resource "aws_s3_bucket" "backups" {
  bucket = "shorty-dev-backups-111122223333"
  tags = {
    Project     = "shorty"
    Environment = "dev"
  }
}

resource "aws_s3_bucket_versioning" "backups" {
  bucket = aws_s3_bucket.backups.id
  versioning_configuration {
    status = "Enabled"
  }
}

It validates fine. It even works. But "dev" is written six times and the account ID three times, and making a prod copy means copying the whole file and running find and replace. This is actually the kind of file where one copy always gets missed.

Variables

First, the things that change between environments become variables. Put them in variables.tf.

variable "region" {
  type    = string
  default = "ap-south-1"
}

variable "project" {
  type    = string
  default = "shorty"
}

variable "environment" {
  type        = string
  description = "Which environment this is: dev, staging or prod."

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be one of dev, staging or prod."
  }
}

variable "buckets" {
  description = "Buckets to create, keyed by a short name."
  type = map(object({
    versioning  = optional(bool, false)
    expire_days = optional(number)
  }))

  validation {
    condition     = alltrue([for k in keys(var.buckets) : can(regex("^[a-z0-9-]+$", k))])
    error_message = "Bucket keys may only use lowercase letters, digits and hyphens."
  }
}

environment has no default on purpose. If you forget to say which environment, Terraform asks, and I'd rather be asked than end up in the wrong one.

buckets is the interesting one. It's a map where each key is a short bucket name and each value is an object with settings. optional(bool, false) means you can leave versioning out and it becomes false. optional(number) with no default becomes null. That keeps the tfvars files short, you only write what's different.

The validation blocks run during plan, before anything is created. Bucket names can't have capital letters, so the second rule catches Logs early instead of letting AWS reject it halfway through an apply.

Locals

Locals are named values computed inside the config. Use them for anything you'd otherwise repeat or that needs a bit of logic.

data "aws_caller_identity" "current" {}

locals {
  name_prefix = "${var.project}-${var.environment}"
  account_id  = data.aws_caller_identity.current.account_id

  common_tags = {
    Project     = var.project
    Environment = var.environment
    ManagedBy   = "terraform"
  }

  versioned = { for name, b in var.buckets : name => b if b.versioning }
  expiring  = { for name, b in var.buckets : name => b if b.expire_days != null }
}

The account ID comes from the AWS API now, not typed by hand. versioned and expiring are filtered copies of var.buckets, using a for expression with an if. You'll see why in a minute.

The tags go to the provider through default_tags, so every resource gets them without a tags line.

provider "aws" {
  region = var.region

  default_tags {
    tags = local.common_tags
  }
}

for_each

Now the three bucket blocks become one.

resource "aws_s3_bucket" "this" {
  for_each = var.buckets

  bucket = "${local.name_prefix}-${each.key}-${local.account_id}"
}

resource "aws_s3_bucket_versioning" "this" {
  for_each = local.versioned

  bucket = aws_s3_bucket.this[each.key].id

  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "this" {
  for_each = local.expiring

  bucket = aws_s3_bucket.this[each.key].id

  rule {
    id     = "expire"
    status = "Enabled"

    filter {}

    expiration {
      days = each.value.expire_days
    }
  }
}

for_each takes a map (or a set of strings) and makes one instance per key. Inside the block, each.key is the key (logs) and each.value is the object. The versioning resource loops over local.versioned, so it only exists for buckets that asked for it. Same for the lifecycle rule. This is the pattern I use most: one big map as input, filtered maps in locals, one resource per thing.

Outputs

Outputs are what the project gives back, on screen after apply and to other tools with terraform output -json.

output "bucket_names" {
  description = "Bucket name for each key in var.buckets."
  value       = { for name, b in aws_s3_bucket.this : name => b.bucket }
}

output "bucket_arns" {
  value = [for b in aws_s3_bucket.this : b.arn]
}

I like outputting a map keyed the same way as the input. Whoever reads it (a script, another Terraform project) can ask for bucket_names["uploads"] and not care about the order.

One tfvars file per environment

dev.tfvars:

environment = "dev"

buckets = {
  logs = {
    expire_days = 14
  }
  uploads = {}
  backups = {
    versioning = true
  }
}

prod.tfvars:

environment = "prod"

buckets = {
  logs = {
    expire_days = 90
  }
  uploads = {
    versioning = true
  }
  backups = {
    versioning  = true
    expire_days = 365
  }
}

Then pick file at plan time.

terraform plan -var-file=dev.tfvars

I didn't want real buckets for this post, so I ran the plans against moto, a local AWS mock with fake credentials, whose account ID I set to the usual 111122223333 placeholder. This is the dev plan, cut down to the parts that matter.

  # aws_s3_bucket.this["backups"] will be created
      + bucket                      = "shorty-dev-backups-111122223333"
  # aws_s3_bucket.this["logs"] will be created
      + bucket                      = "shorty-dev-logs-111122223333"
  # aws_s3_bucket.this["uploads"] will be created
      + bucket                      = "shorty-dev-uploads-111122223333"
  # aws_s3_bucket_lifecycle_configuration.this["logs"] will be created
  # aws_s3_bucket_versioning.this["backups"] will be created

Plan: 5 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + bucket_names = {
      + backups = "shorty-dev-backups-111122223333"
      + logs    = "shorty-dev-logs-111122223333"
      + uploads = "shorty-dev-uploads-111122223333"
    }

Look at the addresses: aws_s3_bucket.this["logs"]. The key is part of the address. With prod.tfvars the same code planned 7 resources, because prod has versioning on two buckets and expiry on two.

And the validation rule, when I passed an environment that doesn't exist:

terraform plan -var-file=dev.tfvars -var environment=qa
Error: Invalid value for variable

  on variables.tf line 11:
  11: variable "environment" {
    ├────────────────
    │ var.environment is "qa"

environment must be one of dev, staging or prod.

Nothing even reached AWS itself. That's the nice part of validation, the mistake fails in a second.

Checking locals with terraform console

When a for expression gets confusing, I test it in terraform console before planning. It works offline for things like this.

echo 'local.versioned' | terraform console -var-file=dev.tfvars
{
  "backups" = {
    "expire_days" = tonumber(null)
    "versioning" = true
  }
}

That tonumber(null) is how console shows a null number. It's the optional(number) with no default, doing what it said.

count vs for_each

You could write the buckets with count and a list instead.

variable "bucket_names" {
  type    = list(string)
  default = ["logs", "uploads", "backups"]
}

resource "aws_s3_bucket" "this" {
  count  = length(var.bucket_names)
  bucket = "shorty-dev-${var.bucket_names[count.index]}-111122223333"
}

The addresses become aws_s3_bucket.this[0], [1], [2]. Now remove uploads from the middle of the list. backups moves from index 2 to index 1, and Terraform compares by index, so it thinks [1] changed its name from uploads to backups and [2] disappeared. A bucket name change forces a replace. So it plans to destroy and recreate a bucket that you didn't touch, and S3 won't even delete a bucket that still has objects in it. Quite messy.

With for_each the address is this["backups"] before and after, so removing uploads only removes uploads.

I still use count for one thing only: an on/off switch. count = var.enable_nat ? 1 : 0 is the shortest way to say "create this or don't". For anything with more than one real item, for_each with a map.

Where this goes next

The buckets here still use local state, and dev and prod share one state file if you run both from the same folder. Don't do that for real. The S3 state post moves the state off the laptop, and keeping environments apart gets its own post later in this series.

Next time you're about to copy a resource block, write the map instead.