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)”Prerequisites
Section titled “Prerequisites”- 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:
| Service | Quota name | Default | Need |
|---|---|---|---|
| RDS (Aurora) | DB clusters | 40 | 2 (one per env) |
| RDS (Aurora) | Data API maximum concurrent cluster-secret pairs | 30 | ≥ 2 (RAG011) |
| Lambda | Concurrent executions | 1000 | 1000 |
| VPC | VPCs per Region | 5 | 2 (one per env) |
2. Configure local AWS credentials
Section titled “2. Configure local AWS credentials”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 # verify3. 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:
git clone https://github.com/ArunskiOrg/rag-sample-app.gitcd 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.
4. Apply the bootstrap root
Section titled “4. Apply the bootstrap root”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):
cd infra/bootstrapterraform init -backend=false # first run only: bucket doesn't exist yetterraform plan # review before applyingterraform applyThen migrate local state into the remote backend:
terraform init -migrate-stateIf 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:
terraform state push terraform.tfstateConfirm 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:
terraform output qa_deploy_role_arnterraform output prod_deploy_role_arn # only after enable_prod = true (#28)Set, on the ArunskiOrg/rag-sample-app repo:
| Config item | Type | Value |
|---|---|---|
AWS_QA_DEPLOY_ROLE_ARN | Repo secret | qa_deploy_role_arn output |
AWS_QA_ACCOUNT_ID | Repo variable | the 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_ARN | Repo secret | prod_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.
6. Set up billing alarms
Section titled “6. Set up billing alarms”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.
7. Verify account readiness
Section titled “7. Verify account readiness”aws sts get-caller-identityaws s3 ls s3://rag-sample-terraform-state/aws bedrock list-inference-profiles \ --query 'inferenceProfileSummaries[?contains(inferenceProfileId,`haiku`)].inferenceProfileId' --output textThe 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):
aws bedrock get-inference-profile \ --inference-profile-identifier us.anthropic.claude-haiku-4-5-20251001-v1:0 \ --query 'models[].modelArn' --output textThis 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.
1. Push to main
Section titled “1. Push to main”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.
2. Grant the deploy role its DB secret
Section titled “2. Grant the deploy role its DB secret”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:
terraform -chdir=infra/roots/qa output -raw db_secret_arnterraform -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.tfvarsmake tf-bootstrap-applyRepeat 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.
3. Run the schema migration
Section titled “3. Run the schema migration”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:
cd backend
# Data-API descriptor from the QA root outputsexport 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_keysThe 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:
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: vectorOn a new environment, re-run QA Deploy now; the smoke check should pass.
4. Corpus ingestion and API key issuance
Section titled “4. Corpus ingestion and API key issuance”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-listandkey-revoketake the sameENV, defaulting to local. See “Issuing a key for a deployed environment” in the app repo’s API service runbook. - Ingestion:
rag-ingestuses the Data API when the cluster ARN, secret ARN, and database name are all set, and falls back toDATABASE_URLotherwise. It reads eitherCLUSTER_ARN/SECRET_ARN/DATABASE_NAMEor theDB_CLUSTER_ARN/DB_SECRET_ARN/DB_NAMEnames exported in step 3, so those exports suffice. It has noENV-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.
5. Smoke test the API
Section titled “5. Smoke test the API”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 401curl -s -o /dev/null -w "%{http_code}" "$API_ENDPOINT/query" \ -X POST -H "Content-Type: application/json" -d '{"question": "test"}'# Expected: 401The 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”# 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 logsLOG_GROUP=/aws/lambda/rag-sample-qa-apiSTREAM=$(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 outputIf 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).
7. Verify cost alarms
Section titled “7. Verify cost alarms”aws budgets describe-budgets --account-id <ACCOUNT_ID> \ --query 'Budgets[].{Name:BudgetName,Limit:BudgetLimit.Amount,Unit:BudgetLimit.Unit,Period:TimeUnit}' \ --output tableaws cloudwatch describe-alarms --alarm-name-prefix rag-sample-<env>- \ --query 'MetricAlarms[].{Name:AlarmName,State:StateValue}' --output tableExpected: 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.
Next steps
Section titled “Next steps”- QA is now ready for integration testing; CI auto-deploys on every future merge to
main— see Ongoing Deployment. - Prod has no automated pipeline. Review the Prod promotion checklist and the deployment plan before doing anything toward Prod.
Teardown
Section titled “Teardown”Aurora auto-pauses. For full teardown:
cd infra/roots/qaterraform destroyThe Lambda zip in S3 is not managed by Terraform — not removed by destroy:
aws s3 rm s3://<lambda_package_s3_bucket>/<lambda_package_s3_key>© 2026 Benjamin Arunski