Skip to content

Environment Spinup

Everything needed to bring up rag-sample in an AWS account for the first time: Phase 1 (once per account) prepares the account and the CI deploy identity; Phase 2 (once per environment) creates the environment. Deployment model: RAG001 · Environments and CI.

Current deployment status for every item below (what’s automated vs. manual, what’s still a known gap) is tracked in the canonical deployment plan.

Phase 1 — Account readiness (once per AWS account)

Section titled “Phase 1 — Account readiness (once per AWS account)”
  • AWS account with billing enabled; AWS CLI v2; Terraform 1.11+
  • IAM user or role with full IAM and S3 permissions (temporary — bootstrap creates least-privilege deploy roles that replace the need for this)
  • GitHub repository access to ArunskiOrg/rag-sample-app

1. Enable required AWS services and verify quotas

Section titled “1. Enable required AWS services and verify quotas”

Verify Lambda, Aurora, API Gateway, CloudFront, S3, Secrets Manager, CloudWatch, Bedrock, and IAM aren’t disabled by a Service Control Policy. Bedrock enables serverless foundation models automatically, but Anthropic models (Claude) require a one-time usage form via the Bedrock console before first use (RAG007).

Raise these via the Service Quotas console if restricted:

ServiceQuota nameDefaultNeed
RDS (Aurora)DB clusters402 (one per env)
RDS (Aurora)Data API maximum concurrent cluster-secret pairs30≥ 2 (RAG011)
LambdaConcurrent executions10001000
VPCVPCs per Region52 (one per env)
Terminal window
export AWS_ACCESS_KEY_ID=<YOUR_ACCESS_KEY>
export AWS_SECRET_ACCESS_KEY=<YOUR_SECRET_KEY>
export AWS_REGION=<YOUR_REGION>
aws sts get-caller-identity # verify

3. Set account-specific values in terraform.tfvars

Section titled “3. Set account-specific values in terraform.tfvars”

Each Terraform root reads account-specific inputs from a gitignored terraform.tfvars:

Terminal window
git clone https://github.com/ArunskiOrg/rag-sample-app.git
cd rag-sample-app
# in each of infra/bootstrap/, infra/roots/qa/, infra/roots/prod/:
cp terraform.tfvars.example terraform.tfvars
# set aws_account_id (all three); in roots/qa and roots/prod also set
# lambda_package_s3_bucket / lambda_package_s3_key; in bootstrap also set
# alert_email and bedrock_budget_services (see step 6)

Terraform loads terraform.tfvars automatically — no source step needed. If a TLS-intercepting antivirus/proxy breaks Terraform locally, see infra/README.md’s cert-trust section for the TF_SSL_CERT_FILE workaround.

bootstrap creates the Terraform state bucket, the Lambda-package bucket, the GitHub Actions OIDC identity provider, and the per-environment deploy roles (rag-sample-qa-deploy-role, plus rag-sample-prod-deploy-role only when enable_prod = true, which stays false until #28 — least-privilege, scoped by the cicd module, which also creates each env’s rag-sample-<env>-stack-role-boundary), plus the rag-sample-alerts topic, its policy, the email subscription and the two spend budgets (step 6). Its own state has to live somewhere before the bucket it creates exists, so this very first apply in a new account needs -backend=false (the make tf-bootstrap-* targets always target the S3 backend, so they don’t fit this one special case — use raw terraform here, from inside infra/bootstrap):

Terminal window
cd infra/bootstrap
terraform init -backend=false # first run only: bucket doesn't exist yet
terraform plan # review before applying
terraform apply

Then migrate local state into the remote backend:

Terminal window
terraform init -migrate-state

If migration doesn’t happen automatically (e.g. running non-interactively with -input=false), push state explicitly — safe here only because the remote state is empty on a freshly created bucket:

Terminal window
terraform state push terraform.tfstate

Confirm with terraform state list (expect a non-empty list) and aws s3 ls s3://rag-sample-terraform-state/, then delete the local terraform.tfstate/.backup files.

For any later change to infra/bootstrap or the cicd module, re-run make tf-bootstrap-apply manually — no workflow applies bootstrap automatically, ever. This has bitten real changes before (see the deployment plan’s operational note).

5. Wire the deploy identity into GitHub Actions

Section titled “5. Wire the deploy identity into GitHub Actions”

Read the outputs from the apply above:

Terminal window
terraform output qa_deploy_role_arn
terraform output prod_deploy_role_arn # only after enable_prod = true (#28)

Set, on the ArunskiOrg/rag-sample-app repo:

Config itemTypeValue
AWS_QA_DEPLOY_ROLE_ARNRepo secretqa_deploy_role_arn output
AWS_QA_ACCOUNT_IDRepo variablethe account ID from step 2 — supplies TF_VAR_aws_account_id for the allowed_account_ids guard, kept out of git
AWS_PROD_DEPLOY_ROLE_ARNRepo secretprod_deploy_role_arn output, absent until enable_prod = true (Prod is frozen until #28; see the deployment plan)

Each role’s trust policy only admits a GitHub Actions job from this repo running in the matching environment:<env> — the deploy workflow jobs declare environment: qa (or prod) so their OIDC token subject matches. No long-lived AWS keys are used anywhere in CI.

Bootstrap creates the alert channel and the D-4 budgets: the rag-sample-alerts SNS topic with an email subscription, a $5/day budget on the Bedrock services, and a $40/month account budget (#385). Step 4’s apply creates them from the alert_email and bedrock_budget_services values set in step 3. A new account has no Bedrock spend for Cost Explorer to list, so start bedrock_budget_services from the shape in infra/bootstrap/terraform.tfvars.example (Amazon Bedrock plus the model’s (Amazon Bedrock Edition) name) and check it with the runbook’s step 7 after the first usage day. After the apply, confirm the subscription from the email AWS sends. The spend and abuse runbook has the Cost Explorer query for the service names, the test notification, and the kill switch.

Terminal window
aws sts get-caller-identity
aws s3 ls s3://rag-sample-terraform-state/
aws bedrock list-inference-profiles \
--query 'inferenceProfileSummaries[?contains(inferenceProfileId,`haiku`)].inferenceProfileId' --output text

The generation model is invoked through a cross-region inference profile, so use list-inference-profiles, requiring bedrock:ListInferenceProfiles.

Also confirm the profile’s routed regions still match the hardcoded list in rag-sample-app’s infra/modules/api/main.tf (for region in ["us-east-1", "us-east-2", "us-west-2"] in the Bedrock Resource block of aws_iam_role_policy.lambda):

Terminal window
aws bedrock get-inference-profile \
--inference-profile-identifier us.anthropic.claude-haiku-4-5-20251001-v1:0 \
--query 'models[].modelArn' --output text

This call needs bedrock:GetInferenceProfile. Each returned ARN names the region it routes to. A region not in the hardcoded list is not granted by the IAM policy, and shows up only as an intermittent runtime AccessDenied on the requests Bedrock happens to route there.

A successful listing shows that the profile exists in the region; it does NOT show that the account has model access granted (the one-time Anthropic usage form, step 1 above), nor that the API Lambda role grants both ARN forms. The end-to-end check is a real invocation under the deployed role — the post-deploy smoke test covers this. If that returns AccessDeniedException despite the profile listing, check model access and then the IAM resource ARNs.

Bootstrap uses S3-native state locking — an empty s3 ls on a fresh bucket is expected. And the .tflock object only exists transiently during an operation.


Phase 2 — First deploy to an environment (once per environment)

Section titled “Phase 2 — First deploy to an environment (once per environment)”

Prerequisite: Phase 1 complete for this account.

Pushing to main after Phase 1 is done triggers qa-deploy.yml, which builds the Lambda package, plans, and applies the entire QA stack automatically — end to end, confirmed working as of run 29606689902. On a new environment’s first run the smoke check fails by design; steps 2 and 3 resolve it.

Once AWS_QA_DEPLOY_ROLE_ARN and AWS_QA_ACCOUNT_ID are set (Phase 1, step 5), any merge to main runs the full pipeline: lint → IaC security scan → test → secret scan → build & publish the Lambda package → Terraform plan → Terraform apply → deploy Lambda code → build & deploy the frontend → post-deploy smoke check. Watch it in the Actions tab. Infracost runs only on the Terraform PR, in terraform.yml, where it posts the cost comment and asserts the fixed-price ceiling for both roots (RAG021).

Expect creation of: VPC + subnets + security group (network module), Aurora Serverless v2 cluster + instance (data module), Secrets Manager secrets, Lambda functions (rag-sample-qa-api, rag-sample-qa-authorizer), API Gateway HTTP API (POST /query authorizer-protected, GET /healthz unauthenticated; no catch-all route), CloudFront distribution + S3 bucket (frontend module; the Build & Deploy Frontend (QA) job populates the bucket from the built SPA after the apply and invalidates CloudFront — QA only, Prod has no equivalent, see the deployment plan).

Note the Terraform outputs from the apply job’s logs — api_endpoint, cloudfront_domain, s3_bucket_name — needed below.

RDS names the cluster’s master secret when the cluster is created, so the QA deploy role cannot read it until bootstrap names it. On the first deploy the smoke check fails with AccessDenied on the Data API call. Set the ARN in infra/bootstrap/terraform.tfvars and re-apply bootstrap, from the root of the rag-sample-app checkout:

Terminal window
terraform -chdir=infra/roots/qa output -raw db_secret_arn
terraform -chdir=infra/roots/qa output -raw db_cluster_arn
# set qa_db_secret_arn (and qa_db_cluster_arn, for the eval role) in infra/bootstrap/terraform.tfvars
make tf-bootstrap-apply

Repeat this step whenever the cluster is replaced, since a new cluster gets a new secret. Prod follows the same steps with prod_db_secret_arn after its first apply.

Aurora QA is in a private VPC with no direct TCP path from local to the cluster, and no CI job runs migrations. rag-migrate (the local CLI, connects via psycopg) cannot reach it. Apply the schema over the RDS Data API - run from the rag-sample-app checkout:

Terminal window
cd backend
# Data-API descriptor from the QA root outputs
export DB_CLUSTER_ARN=$(terraform -chdir=../infra/roots/qa output -raw db_cluster_arn)
export DB_SECRET_ARN=$(terraform -chdir=../infra/roots/qa output -raw db_secret_arn)
export DB_NAME=$(terraform -chdir=../infra/roots/qa output -raw db_name)
uv run rag-migrate-dataapi
# Expected: Applied migrations: 0001_init, 0002_api_keys

The runner shares the schema_migrations ledger with rag-migrate, so re-running is a no-op; a cluster resuming from a 0-ACU floor may reject the first call and need one re-run. Full reference: the app repo’s docs/runbooks/schema-migrations.md.

Verify pgvector is installed:

Terminal window
aws rds-data execute-statement \
--resource-arn "$DB_CLUSTER_ARN" --secret-arn "$DB_SECRET_ARN" --database "$DB_NAME" \
--sql "SELECT extname FROM pg_extension WHERE extname = 'vector';" \
--query 'records[0][0].stringValue' --output text
# Expected: vector

On a new environment, re-run QA Deploy now; the smoke check should pass.

rag-key and rag-ingest hit QA Aurora from a workstation over the RDS Data API, the same path as rag-migrate-dataapi in step 3.

  • Keys: make key-issue ENV=qa RECIPIENT=<recipient> prints the database it acted on; key-list and key-revoke take the same ENV, defaulting to local. See “Issuing a key for a deployed environment” in the app repo’s API service runbook.
  • Ingestion: rag-ingest uses the Data API when the cluster ARN, secret ARN, and database name are all set, and falls back to DATABASE_URL otherwise. It reads either CLUSTER_ARN/SECRET_ARN/DATABASE_NAME or the DB_CLUSTER_ARN/DB_SECRET_ARN/DB_NAME names exported in step 3, so those exports suffice. It has no ENV-aware make target.

After ingestion, verify chunk count: aws rds-data execute-statement --resource-arn "$DB_CLUSTER_ARN" --secret-arn "$DB_SECRET_ARN" --database "$DB_NAME" --sql "SELECT COUNT(*) FROM chunks WHERE embedding IS NOT NULL;" --query 'records[0][0].longValue' --output text (expect > 0). See the ingestion pipeline runbook for CLI reference.

Terminal window
API_ENDPOINT=<api_endpoint from the apply output>
# Health check — no auth required (GET /healthz route)
curl -sf "$API_ENDPOINT/healthz" | jq .
# Expected: {"status": "ok"}
# Query without auth — must return 401
curl -s -o /dev/null -w "%{http_code}" "$API_ENDPOINT/query" \
-X POST -H "Content-Type: application/json" -d '{"question": "test"}'
# Expected: 401

The authorized /query path needs a valid bearer token from step 4 — test it once key issuance against QA is available.

6. Verify observability and auth-header scrubbing

Section titled “6. Verify observability and auth-header scrubbing”
Terminal window
# Authorizer log group retention (TF-managed, 30-day)
aws logs describe-log-groups \
--log-group-name-prefix /aws/lambda/rag-sample-qa-authorizer \
--query 'logGroups[0].retentionInDays' --output text
# Expected: 30
# Auth header must never appear in logs
LOG_GROUP=/aws/lambda/rag-sample-qa-api
STREAM=$(aws logs describe-log-streams --log-group-name "$LOG_GROUP" \
--order-by LastEventTime --descending --max-items 1 \
--query 'logStreams[0].logStreamName' --output text)
aws logs get-log-events --log-group-name "$LOG_GROUP" --log-stream-name "$STREAM" \
--query 'events[*].message' --output text | grep -i "authorization"
# Expected: no output

If Authorization appears in any log line, stop — do not proceed to Prod until #62 is verified.

Open the CloudWatch alarms console and confirm the environment’s rag-sample-<env>-* alarms are OK after the smoke test (see the spend and abuse runbook).

Terminal window
aws budgets describe-budgets --account-id <ACCOUNT_ID> \
--query 'Budgets[].{Name:BudgetName,Limit:BudgetLimit.Amount,Unit:BudgetLimit.Unit,Period:TimeUnit}' \
--output table
aws cloudwatch describe-alarms --alarm-name-prefix rag-sample-<env>- \
--query 'MetricAlarms[].{Name:AlarmName,State:StateValue}' --output table

Expected: rag-sample-bedrock-daily (5 USD DAILY) and rag-sample-monthly (40 USD MONTHLY), and four rag-sample-<env>- alarms (api-invocations, api-errors, authorizer-duration, db-awake-12h). The spend and abuse runbook explains each.

Aurora auto-pauses. For full teardown:

Terminal window
cd infra/roots/qa
terraform destroy

The Lambda zip in S3 is not managed by Terraform — not removed by destroy:

Terminal window
aws s3 rm s3://<lambda_package_s3_bucket>/<lambda_package_s3_key>