Skip to content

Terraform Layout

Context

A single-operator AWS demo of a RAG Pipeline

Tech Stack

  • Lambda (FastAPI/Mangum)
  • Aurora Serverless v2
  • S3/CloudFront SPA
  • Bedrock Haiku-class generation model
  • Bedrock Guardrails

Environments

  • QA and Prod
  • separate VPCs under one account

Documentation Context

  • RAG001: two-VPC model and named the module/root structure
  • RAG010: what the VPC must not contain
  • RAG011: Aurora connection
  • This document records how the Terraform layout is configured to make those decisions structural.

Layout overview

state backend

composed into

Per-environment roots

qa/

prod/

Child modules · dependency order

network

data

api

frontend

infra/bootstrap

S3 state bucket (S3-native locking)

S3 Lambda package bucket

GitHub OIDC provider + per-env deploy roles (cicd module)

Three tiers:

  • a one-time bootstrap root
  • a set of reusable child modules
  • two thin per-environment roots that compose those modules

Five child modules, each owning one concern: network, data, api, and frontend compose the environment roots; cicd is composed by infra/bootstrap/. Module outputs are the only cross-module data path; no module reads another module’s state by lookup.

Environment root, per environment (infra/roots/qa/ and infra/roots/prod/): each composes the same four modules. The only meaningful difference between them is the set of input values. The infra/bootstrap/ root is separate: it provisions the state bucket, the Lambda package bucket, the GitHub Actions OIDC provider, and each environment’s deploy role, and is never part of the per-env plan/apply cycle. Remote state is backed by S3 with S3-native locking.

Environment roots

infra/roots/qa/ and infra/roots/prod/ have identical structure:

infra/
  roots/
    qa/
      main.tf                   # provider config and module composition
      variables.tf              # env-specific input declarations
      outputs.tf                # surface useful ARNs / URLs
      terraform.tfvars.example  # committed values; copied to terraform.tfvars (gitignored)
      backend.tf                # S3 backend config, keyed to qa
    prod/
      (same structure)

Each root calls its four modules in dependency order: network → data → api → frontend. Module outputs are passed as inputs to downstream modules directly as module references.

QA and Prod differ only by these input values, set as variable defaults or in terraform.tfvars:

InputQAProd
envqaprod
domain_namerag.benarunski.comrag-prod.benarunski.com
lambda_package_s3_keyrag-sample/qa/lambda.ziprag-sample/prod/lambda.zip
llm_model_idCandidate model during a soak; otherwise the Prod valueCurrent model (RAG007)
llm_temperatureThe candidate’s value during a soak; otherwise the Prod valueThe current model’s value; default 0.0. null sends no temperature
llm_effortThe candidate’s value during a soak; otherwise the Prod valueThe current model’s value; default null, which sends no effort level

env = "prod" also turns on Aurora deletion protection and a final snapshot in the data module. Both roots use the network module’s default vpc_cidr (10.0.0.0/16) and the data module’s fixed 0–1 ACU scaling range. lambda_package_s3_key takes effect only when each Lambda is created: both functions ignore later s3_bucket/s3_key changes, and code deploys run out-of-band.

Modules

Current and future modules follow the same pattern: create modules/<name>/, define inputs and outputs, call it from both roots with the same module-output wiring, add any new IAM actions to the deploy-role policy in the cicd module, and re-apply infra/bootstrap/ manually.

Each module is described in more detail here.

modules/network

Scope: VPC, one private subnet per availability zone (at least two), Aurora DB subnet group, Aurora security group. Nothing else.

  • Inputs: env, vpc_cidr (default 10.0.0.0/16), availability_zones (default us-east-1a, us-east-1b)
  • Outputs: vpc_id, private_subnet_ids, aurora_sg_id, db_subnet_group_name

The module contains no aws_internet_gateway, aws_nat_gateway, or aws_vpc_endpoint resources. For RAG010 - no IGW, no NAT, code review keeps IGW/NAT/endpoints out; a NAT Gateway or PrivateLink endpoint also trips the RAG021 Infracost ceiling.

The Aurora security group allows inbound traffic from the VPC CIDR. Nothing else runs in the VPC today, so the rule admits NO TRAFFIC; it’s in place for a future in-VPC workload.

modules/data

Scope: Aurora Serverless v2 cluster and instance, cluster parameter group, KMS key for storage encryption. The master credential is RDS-managed, so RDS owns its Secrets Manager secret.

  • Inputs: env, db_subnet_group_name (from network), security_group_id (from network), master_username, backup_retention_period
  • Outputs: cluster_arn, cluster_endpoint, cluster_identifier, database_name, secret_arn, kms_key_arn

The module outputs cluster_endpoint, but neither root passes it on. The api module takes only cluster_arn, secret_arn, and database_name from data, and declares no endpoint, host, or port input, so the application Lambdas have nothing to build a connection string from. This enforces RAG011 - RDS Data API as the sole network path at the api module’s interface. Prevents psycopg connections from application Lambdas (on purpose).

modules/api

Scope: API and Authorizer Lambda functions, their execution roles (each carrying the env’s stack role boundary from cicd), CloudWatch log groups, KMS key for the API and authorizer log groups; HTTP API with CORS configuration, the Lambda authorizer, Lambda integration, routes, $default stage with auto-deploy, a stage default throttle and per-route throttles, and invoke permissions.

  • Inputs: env, cluster_arn (from data), secret_arn (from data), permissions_boundary_arn (the env’s stack role boundary, built from the account id), database_name (from data), lambda_package_s3_bucket, lambda_package_s3_key, allowed_origins, throttle_rate_limit, throttle_burst_limit, embedding_model_id, llm_model_id, llm_temperature, llm_effort, log_level, log_retention_days
  • Outputs: api_endpoint, lambda_function_name, lambda_function_arn, authorizer_function_name, authorizer_function_arn, api_log_group_name

Neither Lambda sets vpc_config, and neither execution role has VPC-attachment permissions (ec2:CreateNetworkInterface etc.), so neither Lambda can reach the cluster’s private subnets over TCP. This enforces RAG011 through the Lambda configuration and IAM, complementing the interface-level enforcement described under data.

Caching is set to authorizer_result_ttl_in_seconds = 0 per RAG009 — the decrement-on-call model is incompatible with any cached allow. Hard-coded to preclude overrides.

modules/frontend

Scope: S3 bucket for SPA assets, CloudFront distribution with S3 and API origins, origin access control, SPA-routing CloudFront function, security response headers policy, ACM certificate (through the aws.us_east_1 provider the roots pass in), Route 53 validation and alias records.

  • Inputs: env, domain_name, hosted_zone_id, api_endpoint (from api)
  • Outputs: cloudfront_domain, site_url, s3_bucket_name, s3_bucket_arn, cloudfront_distribution_id

modules/cicd

Scope: one environment’s GitHub Actions OIDC deploy role, its permission policy, and the permissions boundary (rag-sample-<env>-stack-role-boundary) required by every role created by the deploy role. Composed per environment by infra/bootstrap/, not by the environment roots (see State backend).

  • Inputs: env, github_repo, oidc_provider_arn, state_bucket_arn, lambda_packages_bucket_arn, domain_name, hosted_zone_id
  • Outputs: deploy_role_arn, deploy_role_name, stack_role_boundary_arn

State backend

infra/bootstrap/ is applied manually. It provisions:

  • the S3 bucket that holds Terraform state: versioned, encrypted, public-access block, old versions expire after 90 days
  • the S3 bucket that holds Lambda deployment packages, shared by both environments
  • the GitHub Actions OIDC provider
  • each environment’s deploy role, its permission policy, and its stack role boundary, through the cicd module

Bootstrap’s first apply uses local state in infra/bootstrap/terraform.tfstate, because the bucket does not exist yet. That state is then moved to S3 (spin-up guide, step 4).

The deploy role determines access to the state file: GitHub Actions assumes the environment’s role during plan/apply.

Structural guarantees

Enforcement of structural constraints outlined in ADRs:

  • RAG010 (no IGW or NAT): the network module contains none of those resource types and has no input variable that conditionalizes their creation. A NAT Gateway or PrivateLink endpoint also trips the RAG021 Infracost ceiling.
  • RAG011 (Data API as sole application data path): enforced at two levels: the api module accepts no connection endpoint input, and its Lambdas have no vpc_config and execution roles with no VPC-attachment permissions.
  • RAG009 (no authorizer caching): TTL is hard-coded to 0 in the api module.

Single-environment blast radius. QA and Prod use separate state keys (rag-sample/<env>/terraform.tfstate), separate S3-native lock files, and separate deploy roles. A terraform apply in infra/roots/qa/ reads and writes only QA’s state and lock, and changes only resources in QA’s state. The deploy roles also limit storage, Lambda, CloudFront distribution and CloudFront function access to their own environment: each role reads and writes objects only under its own rag-sample/<env>/ key prefix in the shared state and Lambda package buckets, creates, configures and deletes only rag-sample-<env>-* buckets, manages only Lambda functions named rag-sample-<env>-*, reaches only CloudFront distributions tagged with its environment and Project = rag-sample (plus any distribution with no Environment tag and no other Project tag, which it can tag into its environment), and manages only CloudFront functions named rag-sample-<env>-*. Other grants reach both environments, among them the regional services (ec2, kms, apigateway, logs, cloudwatch, xray); the threat model T4 lists every such residual that can change or delete the other environment’s resources or read its secrets. Read-only metadata grants, such as Route 53 record reads in the shared hosted zone and shared-bucket metadata, are not listed. The shared state bucket is a dependency of both environments.

Accidental cross-env reads. No module uses terraform_remote_state or a data source keyed to the other environment’s state or resources. Module wiring is local: outputs from one module call become inputs to the next within the same root. There is no mechanism for infra/roots/prod/main.tf to read a value out of infra/roots/qa/’s state. This is a structural property of the layout, not a policy.

State file conflicts. S3-native locking (use_lockfile) prevents concurrent applies to the same environment. The GitHub Actions workflow runs plan and apply in serial steps within a single job; two simultaneous workflow runs for the same environment would race on the lock, and the losing runner exits with a lock error rather than silently corrupting state. The .tflock object includes the runner identity and timestamp, which the operator can use to force-unlock after a failed run if needed.

  • ADRs: RAG001 (env topology), RAG009 (API auth), RAG010 (no IGW/NAT), RAG011 (Data API only)
  • Network topology — VPC, subnet, and Aurora security group detail this layout provisions
  • Infrastructure — deployment topology and per-environment resource inventory
  • Environments & CI — how these roots are planned and applied through the pipeline
  • architecture/_deployments.c4 — LikeC4 deployment model
  • Issues: #19 (Feature), #20 state bootstrap, #21 VPC, #22 Aurora, #23 Lambda, #24 API Gateway, #25 Secrets/IAM