DevOps Hive

Patterns / Release

Run staging and production from one OpenTofu configuration

Apply the same configuration twice with two variable files, so staging is a real copy of production instead of a hand-built lookalike. A name prefix and default tags keep the two sets of resources apart.

  1. One configuration
  2. staging.tfvars
  3. Apply to staging
  4. production.tfvars
  5. Apply to production

How it works

  1. Why two folders drift apart

    The usual start is to copy the production folder, rename it staging and edit a few values. Within months the two differ in ways nobody remembers, and a change that passed in staging fails in production. If both come from the same files, the only differences are the ones written down in two short variable files.

  2. Put every difference in a variable file

    staging.tfvars and production.tfvars each set the environment name and the few values that should differ, such as sizes or how long test data is kept. Everything else is shared. A validation rule rejects any environment name other than staging or production, which catches typos before anything is created.

  3. Prefix every name and tag every resource

    One local value builds the prefix from the project and environment, and every resource name starts with it. Default tags on the provider add Project and Environment to everything without tagging each resource by hand. That also lets you split the AWS bill by environment.

  4. Keep the two states separate

    This is the mistake that hurts: applying production.tfvars against staging's state makes OpenTofu rename or replace staging's resources into production ones. Give each environment its own state, with a workspace per environment as shown here or a separate backend key. The configuration includes a check that fails the plan when the selected workspace and the environment do not match.

  5. Scope permissions to the environment

    Each environment gets its own bucket and its own KMS key to encrypt it. The app role's policy names only those two, so staging code cannot touch production files even in a shared account. Separate AWS accounts give a harder boundary and are worth moving to later. The same configuration works there unchanged.

  6. Release in order

    Apply to staging first with tofu apply -var-file=staging.tfvars, test, then switch workspace and apply the same commit with production.tfvars. Read the plan each time. A production plan that wants to replace or destroy something you did not change is the signal to stop.

What you set

project
Short name of the product For example web-app
environment
staging or production, set in each variable file For example staging
uploads_expiry_days
Days to keep uploads, 0 keeps them forever For example 30

What it costs to run

The resources in this example cost a little over $1 a month for each environment: $1 for the KMS key, IAM roles are free and S3 charges about $0.02 per GB stored. In a real setup the cost is whatever your stack costs, twice, less whatever you save by giving staging smaller sizes. Estimate.

The configuration

# Staging and production from one configuration.
#
# The same files are applied twice, once per environment, with a different
# variable file and a different state each time:
#
#   staging.tfvars                    production.tfvars
#   ----------------------------      ------------------------------
#   project             = "web-app"   project             = "web-app"
#   environment         = "staging"   environment         = "production"
#   uploads_expiry_days = 30          uploads_expiry_days = 0
#
#   tofu workspace select -or-create staging
#   tofu apply -var-file=staging.tfvars
#
#   tofu workspace select -or-create production
#   tofu apply -var-file=production.tfvars
#
# What this creates, in each environment:
#   - a KMS key of its own that encrypts the uploads
#   - a private S3 bucket for uploads
#   - an IAM role for the app that can use that environment's bucket and key
#     only
# Every name starts with "<project>-<environment>" and every resource is
# tagged with both, so the two sets never collide.

terraform {
  required_version = ">= 1.6.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.region

  # Applied to every resource this provider creates. You do not have to
  # remember to tag each one, and the bill can be split by Environment.
  default_tags {
    tags = {
      Project     = var.project
      Environment = var.environment
      ManagedBy   = "opentofu"
    }
  }
}

variable "region" {
  description = "AWS region to deploy into."
  type        = string
  default     = "us-east-1"
}

variable "project" {
  description = "Short name of the product, lowercase with hyphens."
  type        = string
}

variable "environment" {
  description = "Which copy this is. Comes from the variable file."
  type        = string

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

variable "app_service_principal" {
  description = "AWS service that runs the app and assumes its role."
  type        = string
  default     = "tasks.apprunner.amazonaws.com"
}

variable "uploads_expiry_days" {
  description = "Delete uploads after this many days. 0 keeps them forever. Use a number in staging so test data does not pile up."
  type        = number
  default     = 0
}

data "aws_caller_identity" "current" {}

locals {
  # The one place the naming rule lives. Every resource name starts with it.
  prefix = "${var.project}-${var.environment}"

  # Differences between environments are decided here, in one place, from
  # the environment name. Resources below do not test var.environment.
  is_production = var.environment == "production"
}

# Stops the most expensive mistake: applying production.tfvars while the
# staging workspace is selected, which would rename staging's resources.
# Remove this block if you separate state with backend keys instead of
# workspaces.
check "workspace_matches_environment" {
  assert {
    condition     = terraform.workspace == var.environment || terraform.workspace == "default"
    error_message = "Selected workspace does not match var.environment. Run: tofu workspace select ${var.environment}"
  }
}

# --- Bucket ------------------------------------------------------------------

# Bucket names are global across all AWS accounts, so the account ID goes in
# the name to keep it unique.
resource "aws_s3_bucket" "uploads" {
  bucket = "${local.prefix}-uploads-${data.aws_caller_identity.current.account_id}"

  # Staging can be torn down with files still in it. Production cannot.
  force_destroy = !local.is_production
}

resource "aws_s3_bucket_public_access_block" "uploads" {
  bucket                  = aws_s3_bucket.uploads.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# One key per environment. A role that is not allowed to use this key cannot
# read the files, even if a bucket permission is opened by mistake.
resource "aws_kms_key" "uploads" {
  description         = "Encrypts uploads for ${local.prefix}"
  enable_key_rotation = true

  # Days AWS waits before deleting the key after a destroy. Files encrypted
  # with a deleted key cannot be read again, so production waits the longest.
  deletion_window_in_days = local.is_production ? 30 : 7
}

resource "aws_kms_alias" "uploads" {
  name          = "alias/${local.prefix}-uploads"
  target_key_id = aws_kms_key.uploads.key_id
}

resource "aws_s3_bucket_server_side_encryption_configuration" "uploads" {
  bucket = aws_s3_bucket.uploads.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.uploads.arn
    }

    # One data key per bucket instead of one KMS request per file, which keeps
    # the KMS request cost low.
    bucket_key_enabled = true
  }
}

# Production keeps old versions of each file. Staging does not need them.
resource "aws_s3_bucket_versioning" "uploads" {
  bucket = aws_s3_bucket.uploads.id

  versioning_configuration {
    status = local.is_production ? "Enabled" : "Suspended"
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "uploads" {
  count  = var.uploads_expiry_days > 0 ? 1 : 0
  bucket = aws_s3_bucket.uploads.id

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

    filter {}

    expiration {
      days = var.uploads_expiry_days
    }
  }
}

# --- App role ----------------------------------------------------------------

data "aws_iam_policy_document" "trust" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = [var.app_service_principal]
    }
  }
}

resource "aws_iam_role" "app" {
  name               = "${local.prefix}-app"
  assume_role_policy = data.aws_iam_policy_document.trust.json
}

# The policy names this environment's bucket and key. The staging app cannot
# read or write production files, even though both live in one account.
data "aws_iam_policy_document" "app" {
  statement {
    sid       = "ListUploads"
    effect    = "Allow"
    actions   = ["s3:ListBucket"]
    resources = [aws_s3_bucket.uploads.arn]
  }

  statement {
    sid       = "ReadWriteUploads"
    effect    = "Allow"
    actions   = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"]
    resources = ["${aws_s3_bucket.uploads.arn}/*"]
  }

  # S3 uses the key on the app's behalf: a data key to write, decrypt to read.
  statement {
    sid       = "UseUploadsKey"
    effect    = "Allow"
    actions   = ["kms:GenerateDataKey", "kms:Decrypt"]
    resources = [aws_kms_key.uploads.arn]
  }
}

resource "aws_iam_role_policy" "app" {
  name   = "uploads"
  role   = aws_iam_role.app.id
  policy = data.aws_iam_policy_document.app.json
}

output "environment" {
  description = "Environment this state belongs to."
  value       = var.environment
}

output "uploads_bucket" {
  description = "Bucket for this environment's uploads."
  value       = aws_s3_bucket.uploads.bucket
}

output "app_role_arn" {
  description = "Role for this environment's app."
  value       = aws_iam_role.app.arn
}

Works with OpenTofu 1.6 or later, and with Terraform. Read it before you apply it: it creates real resources in your account.

Written by DevOps Hive. Last updated 2026-11-27.