Terraform for a Help Desk: One Module, Two Provider Blocks (AWS and LocalStack), Checked in Python Before Plan
The Help Desk needs a tickets queue, a dead-letter queue and an attachments bucket, in AWS and on a laptop. One Terraform module builds all three; two thin root folders differ only in the provider block, Python writes their settings (only 4 keys differ) and a check catches encrypt renamed to encrypted before plan.
What you will learn
- Explain plan, apply and state, and why each target keeps its own state
- Write a Terraform module like a function: variables in, resources inside, outputs back
- Call the same module from an AWS root and a LocalStack root that differ only in the provider block
- Generate the settings in Python and catch a renamed key before terraform plan
Before you start
- Cloud-Agnostic Architecture: The Portability Layers
- Basic Python
- What a message queue is
Our Help Desk app needs a few cloud pieces. In production they live in AWS, and for development we want the same pieces on a laptop. In this article we write them once, as a Terraform module, and build them in both places. Five words carry the whole thing: module, variables, outputs, provider and LocalStack.
The project files for this lesson are in the community, free to join.
Two copies of the same Help Desk
The Help Desk needs three pieces: a tickets queue, a dead-letter queue for tickets that keep failing, and a bucket for attachments.
If you click the laptop copy together by hand, small things slip. Say the laptop queue keeps tickets for one day instead of four. Now the two copies behave differently, and nobody notices until something breaks. So we write the pieces once, in a file, and build both copies from that file. Click it twice and the copies drift. Write it once and they match.
Terraform in one picture
Terraform reads files ending in .tf that describe what should exist.
- plan compares your files with the state, Terraform's record of what it already built. The first time the state is empty, so plan says three things will be added: the bucket, the dead-letter queue and the tickets queue.
- apply creates them and writes them into the state.
- Change one value in the file later, and plan shows just that one change, not three new things.
Plan shows the difference. Apply makes it real. State remembers.
A module is a function
The easiest way to think about a Terraform module is a Python function. Its parameters are variables, its body is its resources, and its return values are outputs. And just like a function, you can call it from two places: one caller for AWS, one for the laptop.
The module inputs: variables.tf
The module lives in modules/helpdesk. Its inputs are in variables.tf:
# Inputs of the Help Desk module.
variable "name" {
type = string
}
variable "env" {
type = string
}
variable "encrypt" {
type = bool
}
variable "retention_s" {
type = number
default = 345600 # 4 days
}
variable "max_receive" {
type = number
default = 5
}
variable "force_destroy" {
type = bool
default = false
}
name, env and encrypt have no default, so they are required and every caller must pass them. The other three are optional. retention_s defaults to 345,600 seconds; divide by 86,400 seconds in a day and that's 4 days. No default means the caller must decide.
The module body: main.tf
# What the Help Desk needs: a bucket and two queues.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
resource "aws_s3_bucket" "attachments" {
bucket = "${var.name}-${var.env}-attachments"
force_destroy = var.force_destroy
}
resource "aws_sqs_queue" "dlq" {
name = "${var.name}-${var.env}-tickets-dlq"
}
resource "aws_sqs_queue" "tickets" {
name = "${var.name}-${var.env}-tickets"
message_retention_seconds = var.retention_s
sqs_managed_sse_enabled = var.encrypt
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.dlq.arn
maxReceiveCount = var.max_receive
})
}
Notice what is missing at the top: no region, no keys. The module says it needs the AWS provider, version 5, but it doesn't choose where it runs. Resource names are built from the inputs, such as helpdesk-dev-attachments. The tickets queue takes its retention and encryption from the inputs, and its redrive policy links it to the dead-letter queue: after 5 failed receives, a ticket moves there. The module never says where. It only says what.
The module outputs: outputs.tf
# What the app needs to know after apply.
output "bucket" {
value = aws_s3_bucket.attachments.bucket
}
output "queue_name" {
value = aws_sqs_queue.tickets.name
}
output "queue_url" {
value = aws_sqs_queue.tickets.url
}
Outputs are the module's return value: the names the app needs after apply.
Two root folders, one difference
Each target gets a small root folder under envs. Here is the AWS one:
# Target 1: the real AWS account.
locals {
cfg = jsondecode(file("${path.module}/helpdesk.json"))
}
provider "aws" {
region = local.cfg.region
}
module "helpdesk" {
source = "../../modules/helpdesk"
name = local.cfg.name
env = local.cfg.env
encrypt = local.cfg.encrypt
retention_s = local.cfg.retention_s
max_receive = local.cfg.max_receive
force_destroy = local.cfg.force_destroy
}
output "queue_name" {
value = module.helpdesk.queue_name
}
And the local one. Only the provider block is different:
provider "aws" {
region = local.cfg.region
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_requesting_account_id = true
s3_use_path_style = true
endpoints {
s3 = "http://localhost:4566"
sqs = "http://localhost:4566"
}
}
It points S3 and SQS at localhost:4566. That's LocalStack, a program that imitates AWS services on your own machine. LocalStack accepts dummy keys, so the local folder uses test and skips the credential check. The locals block and the module call are the same as in the AWS folder, line for line. Both folders read their settings from a helpdesk.json next to them.
One place for the settings: settings.py
Those JSON files are generated from Python, so the values live in one place:
"""One source of Help Desk settings for both targets."""
SHARED = {
"name": "helpdesk",
"retention_s": 345600, # 4 days
"max_receive": 5,
}
TARGETS = {
"aws": {
"region": "eu-west-1",
"env": "prod",
"encrypt": True,
"force_destroy": False,
},
"local": {
"region": "us-east-1",
"env": "dev",
"encrypt": False,
"force_destroy": True,
},
}
Local runs as dev with encryption off and force_destroy on, so you can throw it away. make_config.py merges shared and target values and writes one file per folder:
"""Write envs/<target>/helpdesk.json from settings."""
import json
from pathlib import Path
from settings import SHARED, TARGETS
def build(target):
return {**SHARED, **TARGETS[target]}
if __name__ == "__main__":
for target in TARGETS:
cfg = build(target)
path = Path("envs", target, "helpdesk.json")
path.write_text(json.dumps(cfg, indent=2))
out = path.as_posix()
print(f"{target}: {len(cfg)} keys -> {out}")
a, b = build("aws"), build("local")
diff = sorted(k for k in a if a[k] != b[k])
print("differs:", ", ".join(diff))
aws: 7 keys -> envs/aws/helpdesk.json
local: 7 keys -> envs/local/helpdesk.json
differs: encrypt, env, force_destroy, region
Seven keys per file, three shared plus four per target, and only four differ.
Check the inputs before plan
A small Python check reads the module's own variables.tf with a regular expression. A block with a default is optional; one without is required. Then two set differences per target: required minus passed gives missing keys, and passed minus everything known gives unknown keys.
"""Check each target's JSON against the module."""
import json
import re
from pathlib import Path
MOD = Path("modules", "helpdesk")
VAR = re.compile(r'variable "(\w+)" \{(.*?)\n\}', re.S)
RES = re.compile(r'resource "(\w+)" "(\w+)"')
ROOT_ONLY = {"region"} # used by the provider block
def module_inputs():
text = (MOD / "variables.tf").read_text()
req, opt = set(), set()
for name, body in VAR.findall(text):
(opt if "default" in body else req).add(name)
return req, opt
def check(cfg, req, opt):
keys = set(cfg) - ROOT_ONLY
missing = sorted(req - keys)
unknown = sorted(keys - req - opt)
return missing, unknown
if __name__ == "__main__":
req, opt = module_inputs()
print("required:", ", ".join(sorted(req)))
print("optional:", ", ".join(sorted(opt)))
for t in ("aws", "local"):
path = Path("envs", t, "helpdesk.json")
cfg = json.loads(path.read_text())
missing, unknown = check(cfg, req, opt)
ok = not (missing or unknown)
print(f"{t}: {'ok' if ok else 'FAIL'}")
found = RES.findall((MOD / "main.tf").read_text())
print(f"module resources: {len(found)}")
for kind, name in found:
print(f" {kind}.{name}")
required: encrypt, env, name
optional: force_destroy, max_receive, retention_s
aws: ok
local: ok
module resources: 3
aws_s3_bucket.attachments
aws_sqs_queue.dlq
aws_sqs_queue.tickets
region is left out of the check because the provider block uses it, not the module. The three resources listed are the same three that plan will propose.
One renamed key
Now someone renames encrypt to encrypted:
"""A renamed key is caught before terraform plan."""
from check_inputs import check, module_inputs
from make_config import build
cfg = build("local")
cfg["encrypted"] = cfg.pop("encrypt") # the typo
req, opt = module_inputs()
missing, unknown = check(cfg, req, opt)
print("missing:", missing)
print("unknown:", unknown)
missing: ['encrypt']
unknown: ['encrypted']
One typo, two clear symptoms, caught in a second. Terraform would stop too, but only later, at plan, with an error about a missing attribute.
Plan and apply, twice
The -chdir option tells Terraform which root folder to use:
terraform -chdir=envs/local init
terraform -chdir=envs/local plan
terraform -chdir=envs/local apply
terraform -chdir=envs/aws init
terraform -chdir=envs/aws plan
terraform -chdir=envs/aws apply
The three resources appear in LocalStack, and the same three appear in the AWS account. The laptop gets helpdesk-dev-tickets and production gets helpdesk-prod-tickets.
Each folder keeps its own state. Never share one state between targets, or a change meant for the laptop can delete something in production.
The app does not change
The Help Desk talks to the queue through the AWS SDK. One function builds the client settings from the environment:
"""The Help Desk finds its queue from environment."""
def sqs_kwargs(env):
"""Same code for AWS and for LocalStack."""
kw = {"region_name": env["AWS_REGION"]}
url = env.get("AWS_ENDPOINT_URL")
if url:
kw["endpoint_url"] = url
return kw
# Values a deploy step copies from terraform output
TARGET_ENV = {
"aws": {
"AWS_REGION": "eu-west-1",
"HELPDESK_QUEUE": "helpdesk-prod-tickets",
},
"local": {
"AWS_REGION": "us-east-1",
"AWS_ENDPOINT_URL": "http://localhost:4566",
"HELPDESK_QUEUE": "helpdesk-dev-tickets",
},
}
if __name__ == "__main__":
for target, env in TARGET_ENV.items():
print(f"{target}:")
for key, value in sqs_kwargs(env).items():
print(f" {key} = {value}")
print(f" queue = {env['HELPDESK_QUEUE']}")
aws:
region_name = eu-west-1
queue = helpdesk-prod-tickets
local:
region_name = us-east-1
endpoint_url = http://localhost:4566
queue = helpdesk-dev-tickets
For AWS there's no endpoint variable, so the SDK uses the normal AWS address. For local, the deploy step sets the endpoint, and the queue name comes from the Terraform output. The app code is the same; only the environment says where. This is the "infrastructure" seam from Cloud-Agnostic Architecture: The Portability Layers in real files.
Trade-offs
- LocalStack is a stand-in. It's fast and needs no cloud account, but it doesn't match every AWS behaviour, so production changes still get a careful plan review.
- Two different clouds means two modules. If you truly need AWS and another provider, the resource types differ. Keep the same inputs and outputs, and write one module per provider behind that contract.
- One state per target, always.
If an interviewer asks how you keep environments the same, you can say: one module with a clear contract of inputs and outputs; each environment is a thin root folder with its own provider block and its own state; for local work, the same module points at LocalStack.
Recap
| Piece | Job |
|---|---|
modules/helpdesk | Variables in, 3 resources inside, outputs back, no provider settings |
envs/aws, envs/local | Thin roots: same module call, different provider block, own state |
settings.py + make_config.py | One source of values; only 4 of 7 keys differ |
check_inputs.py | Missing and unknown keys caught before plan |
app_config.py | Same app code; the environment says where the queue is |
Try it yourself
Add a visibility_timeout_s variable with a default to the module and pass it to the tickets queue. Run check_inputs.py: which group does it land in? Then remove the default and run it again without adding the key to settings.py. What does the check print?
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
