grada-run 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/bin/cli.js +1 -1
  2. package/package.json +1 -1
  3. package/src/commands/add.js +93 -11
  4. package/src/commands/alerts.js +66 -30
  5. package/src/commands/apply.js +61 -9
  6. package/src/commands/db/backup.js +1 -2
  7. package/src/commands/db/connect.js +10 -4
  8. package/src/commands/db/enable-vector.js +19 -6
  9. package/src/commands/db/import.js +114 -22
  10. package/src/commands/db/migrate.js +76 -72
  11. package/src/commands/db/restore.js +38 -6
  12. package/src/commands/destroy.js +20 -3
  13. package/src/commands/diagnose.js +40 -21
  14. package/src/commands/doctor.js +4 -2
  15. package/src/commands/domain.js +20 -2
  16. package/src/commands/drift.js +2 -1
  17. package/src/commands/eject.js +13 -2
  18. package/src/commands/gc.js +100 -3
  19. package/src/commands/init.js +75 -9
  20. package/src/commands/logs.js +3 -1
  21. package/src/commands/mcp.js +2 -1
  22. package/src/commands/rollback.js +54 -5
  23. package/src/commands/secrets.js +224 -57
  24. package/src/commands/status.js +4 -1
  25. package/src/commands/sync-ai.js +4 -3
  26. package/src/commands/wake.js +45 -1
  27. package/src/data/action-pins.js +26 -0
  28. package/src/utils/addons.js +9 -6
  29. package/src/utils/ai-rules.js +3 -2
  30. package/src/utils/backup.js +16 -2
  31. package/src/utils/command.js +20 -0
  32. package/src/utils/db-tunnel.js +15 -5
  33. package/src/utils/detector.js +8 -0
  34. package/src/utils/ecs-runner.js +16 -3
  35. package/src/utils/frameworks.js +14 -2
  36. package/src/utils/generator.js +21 -13
  37. package/src/utils/prompts.js +20 -4
  38. package/src/utils/resolvers.js +9 -7
  39. package/src/utils/revision-discovery.js +19 -7
  40. package/templates/docker/nestjs.Dockerfile +2 -2
  41. package/templates/docker/nextjs.Dockerfile +3 -3
  42. package/templates/docker/node.Dockerfile +2 -2
  43. package/templates/docker/nuxt.Dockerfile +2 -2
  44. package/templates/docker/static.Dockerfile +1 -1
  45. package/templates/docker/svelte.Dockerfile +2 -2
  46. package/templates/github/deploy-lambda.yml +55 -12
  47. package/templates/github/deploy-static.yml +4 -3
  48. package/templates/github/deploy.yml +96 -13
  49. package/templates/github/drift.yml +74 -5
  50. package/templates/github/preview-lambda.yml +143 -13
  51. package/templates/github/preview.yml +141 -13
  52. package/templates/github/teardown.yml +77 -12
  53. package/templates/terraform/addons/s3.tf +33 -0
  54. package/templates/terraform/backend.tf +7 -0
  55. package/templates/terraform/database-mysql.tf +5 -1
  56. package/templates/terraform/database.tf +5 -1
  57. package/templates/terraform/oidc.tf +3 -2
  58. package/templates/terraform/secrets.tf +6 -4
  59. package/templates/terraform/worker.tf +7 -0
@@ -26,10 +26,11 @@ jobs:
26
26
  deploy:
27
27
  name: Build & Deploy
28
28
  runs-on: ubuntu-latest
29
+ timeout-minutes: 60
29
30
 
30
31
  steps:
31
32
  - name: Checkout Code
32
- uses: actions/checkout@v4
33
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
33
34
 
34
35
  # --- 1. IaC SECURITY SCAN ---
35
36
  - name: Scan Terraform for Misconfigurations
@@ -53,18 +54,39 @@ jobs:
53
54
  echo '```' >> $GITHUB_STEP_SUMMARY
54
55
  fi
55
56
 
56
- # --- 2. INFRASTRUCTURE SYNC (The New Marketplace Action) ---
57
- - name: Apply Infrastructure Changes
58
- uses: grada-run/grada-action@v1
57
+ # --- 2. AWS AUTH (job-level credentials for every step below) ---
58
+ - name: Configure AWS credentials
59
+ id: aws-creds
60
+ uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
61
+ continue-on-error: true
59
62
  with:
60
- aws-region: ${{ env.AWS_REGION }}
61
63
  role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
62
- terraform-dir: 'terraform'
64
+ aws-region: ${{ env.AWS_REGION }}
63
65
 
64
- # --- 3. BUILD & PUSH ---
66
+ # Deploy never skips: a failed assume fails the run with the
67
+ # bootstrap pointer (BUG-138).
68
+ - name: Interpret credential failure
69
+ if: steps.aws-creds.outcome == 'failure'
70
+ run: |
71
+ echo "::error::AWS credential assumption failed — if the stack was never provisioned, bootstrap it first (npx grada-run apply); otherwise check terraform/oidc.tf trust."
72
+ exit 1
73
+
74
+ # --- 3. ECR BOOTSTRAP ---
75
+ # The image is pushed BEFORE the full apply (the function must never
76
+ # point at an unpushed tag), but the repository itself is
77
+ # Terraform-managed — so it is bootstrapped with a targeted apply
78
+ # first. Idempotent on existing stacks.
79
+ - name: Bootstrap ECR repository
80
+ working-directory: ./terraform
81
+ run: |
82
+ terraform init -input=false
83
+ terraform workspace select default
84
+ terraform apply -target=aws_ecr_repository.app -auto-approve -input=false
85
+
86
+ # --- 4. BUILD ---
65
87
  - name: Login to Amazon ECR
66
88
  id: login-ecr
67
- uses: aws-actions/amazon-ecr-login@v2
89
+ uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2
68
90
 
69
91
  - name: Build Docker image
70
92
  id: build-image
@@ -78,8 +100,8 @@ jobs:
78
100
  docker build --platform linux/amd64 -t $ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG .
79
101
  docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
80
102
 
81
- # --- 4. CONTAINER SECURITY SCAN ---
82
- - name: Scan Container for Vulnerabilities (SARIF Output)
103
+ # --- 5. CONTAINER SECURITY SCAN ---
104
+ - name: Scan Container for Vulnerabilities (table summary)
83
105
  uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
84
106
  with:
85
107
  image-ref: '${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:latest'
@@ -100,8 +122,9 @@ jobs:
100
122
  echo '```' >> $GITHUB_STEP_SUMMARY
101
123
  fi
102
124
 
103
- # --- 5. DEPLOY ---
125
+ # --- 6. PUSH ---
104
126
  - name: Push image to Amazon ECR
127
+ id: push
105
128
  env:
106
129
  ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
107
130
  IMAGE_TAG: latest
@@ -111,6 +134,17 @@ jobs:
111
134
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
112
135
  echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG" >> $GITHUB_OUTPUT
113
136
 
137
+ # --- 7. INFRASTRUCTURE SYNC (The New Marketplace Action) ---
138
+ # Runs AFTER the push: the function image tags exist by the time the
139
+ # function is created or updated.
140
+ - name: Apply Infrastructure Changes
141
+ uses: grada-run/grada-action@12227808ae4caafaec1041319645586a1132fc57 # v1
142
+ with:
143
+ aws-region: ${{ env.AWS_REGION }}
144
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
145
+ terraform-dir: 'terraform'
146
+
147
+ # --- 8. DEPLOY ---
114
148
  # Each code push deploys the immutable SHA-tagged image to the Lambda
115
149
  # function, so every ECR tag stays a redeployable rollback point (and
116
150
  # `latest` is never the deploy artifact of record).
@@ -125,7 +159,7 @@ jobs:
125
159
  --function-name ${{ env.LAMBDA_FUNCTION }} \
126
160
  --region ${{ env.AWS_REGION }}
127
161
 
128
- # --- 6. CACHE INVALIDATION ---
162
+ # --- 9. CACHE INVALIDATION ---
129
163
  # New code means new HTML: clear the CDN so deploys go live
130
164
  # immediately instead of serving stale pages until TTL expiry.
131
165
  - name: Invalidate CloudFront
@@ -142,3 +176,12 @@ jobs:
142
176
  --distribution-id "$DIST_ID" \
143
177
  --paths "/*" \
144
178
  --region ${{ env.AWS_REGION }}
179
+
180
+ # A cancelled apply/destroy can strand the S3 state lockfile: point
181
+ # at recovery instead of leaving the next run to fail obscurely
182
+ # (BUG-194). Generic by necessity — the lock ID only exists in the
183
+ # follow-up run's own error.
184
+ - name: Cancellation recovery note
185
+ if: cancelled()
186
+ run: |
187
+ echo "::warning::This run was cancelled while Terraform may have held the state lock. If the next run fails with 'Error acquiring the state lock', run terraform force-unlock <LOCK_ID> (the ID is printed in that error) inside ./terraform — or delete the .tflock object beside the state file in S3 — then re-run."
@@ -26,10 +26,11 @@ jobs:
26
26
  deploy:
27
27
  name: Build & Deploy
28
28
  runs-on: ubuntu-latest
29
+ timeout-minutes: 30
29
30
 
30
31
  steps:
31
32
  - name: Checkout Code
32
- uses: actions/checkout@v4
33
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
33
34
 
34
35
  # --- 1. IaC SECURITY SCAN ---
35
36
  - name: Scan Terraform for Misconfigurations
@@ -55,7 +56,7 @@ jobs:
55
56
 
56
57
  # --- 2. INFRASTRUCTURE SYNC (The New Marketplace Action) ---
57
58
  - name: Apply Infrastructure Changes
58
- uses: grada-run/grada-action@v1
59
+ uses: grada-run/grada-action@12227808ae4caafaec1041319645586a1132fc57 # v1
59
60
  with:
60
61
  aws-region: ${{ env.AWS_REGION }}
61
62
  role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
@@ -63,7 +64,7 @@ jobs:
63
64
 
64
65
  # --- 3. BUILD ---
65
66
  - name: Setup Node.js
66
- uses: actions/setup-node@v4
67
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
67
68
  with:
68
69
  node-version: '22'
69
70
  cache: 'npm'
@@ -30,10 +30,11 @@ jobs:
30
30
  deploy:
31
31
  name: Build & Deploy
32
32
  runs-on: ubuntu-latest
33
+ timeout-minutes: 60
33
34
 
34
35
  steps:
35
36
  - name: Checkout Code
36
- uses: actions/checkout@v4
37
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
37
38
 
38
39
  # --- 1. IaC SECURITY SCAN ---
39
40
  - name: Scan Terraform for Misconfigurations
@@ -57,18 +58,39 @@ jobs:
57
58
  echo '```' >> $GITHUB_STEP_SUMMARY
58
59
  fi
59
60
 
60
- # --- 2. INFRASTRUCTURE SYNC (The New Marketplace Action) ---
61
- - name: Apply Infrastructure Changes
62
- uses: grada-run/grada-action@v1
61
+ # --- 2. AWS AUTH (job-level credentials for every step below) ---
62
+ - name: Configure AWS credentials
63
+ id: aws-creds
64
+ uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
65
+ continue-on-error: true
63
66
  with:
64
- aws-region: ${{ env.AWS_REGION }}
65
67
  role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
66
- terraform-dir: 'terraform'
68
+ aws-region: ${{ env.AWS_REGION }}
67
69
 
68
- # --- 3. BUILD & PUSH ---
70
+ # Deploy never skips: a failed assume fails the run with the
71
+ # bootstrap pointer (BUG-138).
72
+ - name: Interpret credential failure
73
+ if: steps.aws-creds.outcome == 'failure'
74
+ run: |
75
+ echo "::error::AWS credential assumption failed — if the stack was never provisioned, bootstrap it first (npx grada-run apply); otherwise check terraform/oidc.tf trust."
76
+ exit 1
77
+
78
+ # --- 3. ECR BOOTSTRAP ---
79
+ # The image is pushed BEFORE the full apply (fresh stacks must never
80
+ # start tasks on an unpushed tag), but the repository itself is
81
+ # Terraform-managed — so it is bootstrapped with a targeted apply
82
+ # first. Idempotent on existing stacks.
83
+ - name: Bootstrap ECR repository
84
+ working-directory: ./terraform
85
+ run: |
86
+ terraform init -input=false
87
+ terraform workspace select default
88
+ terraform apply -target=aws_ecr_repository.app -auto-approve -input=false
89
+
90
+ # --- 4. BUILD ---
69
91
  - name: Login to Amazon ECR
70
92
  id: login-ecr
71
- uses: aws-actions/amazon-ecr-login@v2
93
+ uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2
72
94
 
73
95
  - name: Build Docker image
74
96
  id: build-image
@@ -80,8 +102,8 @@ jobs:
80
102
  docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG .
81
103
  docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
82
104
 
83
- # --- 4. CONTAINER SECURITY SCAN ---
84
- - name: Scan Container for Vulnerabilities (SARIF Output)
105
+ # --- 5. CONTAINER SECURITY SCAN ---
106
+ - name: Scan Container for Vulnerabilities (table summary)
85
107
  uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
86
108
  with:
87
109
  image-ref: '${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:latest'
@@ -102,8 +124,9 @@ jobs:
102
124
  echo '```' >> $GITHUB_STEP_SUMMARY
103
125
  fi
104
126
 
105
- # --- 5. DEPLOY ---
127
+ # --- 6. PUSH ---
106
128
  - name: Push image to Amazon ECR
129
+ id: push
107
130
  env:
108
131
  ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
109
132
  IMAGE_TAG: latest
@@ -113,6 +136,18 @@ jobs:
113
136
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
114
137
  echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG" >> $GITHUB_OUTPUT
115
138
 
139
+ # --- 7. INFRASTRUCTURE SYNC (The New Marketplace Action) ---
140
+ # Runs AFTER the push: by the time apply moves tasks onto `:latest`,
141
+ # the tag exists. A gate failure below can therefore never strand
142
+ # the service on an unpullable revision.
143
+ - name: Apply Infrastructure Changes
144
+ uses: grada-run/grada-action@12227808ae4caafaec1041319645586a1132fc57 # v1
145
+ with:
146
+ aws-region: ${{ env.AWS_REGION }}
147
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
148
+ terraform-dir: 'terraform'
149
+
150
+ # --- 8. DEPLOY ---
116
151
  # Each code push registers a new task definition revision pinned to the
117
152
  # immutable SHA-tagged image, so `rollback` always has history to
118
153
  # return to (and `latest` is never overwritten in place as the deploy
@@ -145,6 +180,27 @@ jobs:
145
180
  --force-new-deployment \
146
181
  --region ${{ env.AWS_REGION }}
147
182
 
183
+ # update-service returns before the rollout finishes: wait for
184
+ # stability, then verify PRIMARY actually runs the registered
185
+ # revision — a circuit-breaker rollback re-stabilizes on the OLD
186
+ # revision, which the wait alone would report green.
187
+ - name: Wait for web rollout
188
+ run: |
189
+ aws ecs wait services-stable \
190
+ --cluster ${{ env.ECS_CLUSTER }} \
191
+ --services ${{ env.ECS_SERVICE }} \
192
+ --region ${{ env.AWS_REGION }}
193
+ PRIMARY_TD=$(aws ecs describe-services \
194
+ --cluster ${{ env.ECS_CLUSTER }} \
195
+ --services ${{ env.ECS_SERVICE }} \
196
+ --query 'services[0].deployments[?status==`PRIMARY`].taskDefinition' \
197
+ --output text \
198
+ --region ${{ env.AWS_REGION }})
199
+ if [ "$PRIMARY_TD" != "${{ steps.register-task-def.outputs.task-arn }}" ]; then
200
+ echo "Web rollout of ${{ steps.register-task-def.outputs.task-arn }} did not stick (PRIMARY runs $PRIMARY_TD) — the deployment failed or rolled back." >&2
201
+ exit 1
202
+ fi
203
+
148
204
  # The background worker ships the same image as web, so it gets the
149
205
  # same SHA-pinned revision treatment — otherwise it would run stale
150
206
  # code forever while web moves on. Skipped on workerless projects.
@@ -178,7 +234,25 @@ jobs:
178
234
  --force-new-deployment \
179
235
  --region ${{ env.AWS_REGION }}
180
236
 
181
- # --- 6. CACHE INVALIDATION ---
237
+ - name: Wait for worker rollout
238
+ if: hashFiles('terraform/worker.tf') != ''
239
+ run: |
240
+ aws ecs wait services-stable \
241
+ --cluster ${{ env.ECS_CLUSTER }} \
242
+ --services ${{ env.ECS_WORKER_SERVICE }} \
243
+ --region ${{ env.AWS_REGION }}
244
+ PRIMARY_TD=$(aws ecs describe-services \
245
+ --cluster ${{ env.ECS_CLUSTER }} \
246
+ --services ${{ env.ECS_WORKER_SERVICE }} \
247
+ --query 'services[0].deployments[?status==`PRIMARY`].taskDefinition' \
248
+ --output text \
249
+ --region ${{ env.AWS_REGION }})
250
+ if [ "$PRIMARY_TD" != "${{ steps.register-worker-task-def.outputs.task-arn }}" ]; then
251
+ echo "Worker rollout of ${{ steps.register-worker-task-def.outputs.task-arn }} did not stick (PRIMARY runs $PRIMARY_TD) — the deployment failed or rolled back." >&2
252
+ exit 1
253
+ fi
254
+
255
+ # --- 9. CACHE INVALIDATION ---
182
256
  # New code means new HTML: clear the CDN so deploys go live
183
257
  # immediately instead of serving stale pages until TTL expiry.
184
258
  - name: Invalidate CloudFront
@@ -194,4 +268,13 @@ jobs:
194
268
  aws cloudfront create-invalidation \
195
269
  --distribution-id "$DIST_ID" \
196
270
  --paths "/*" \
197
- --region ${{ env.AWS_REGION }}
271
+ --region ${{ env.AWS_REGION }}
272
+
273
+ # A cancelled apply/destroy can strand the S3 state lockfile: point
274
+ # at recovery instead of leaving the next run to fail obscurely
275
+ # (BUG-194). Generic by necessity — the lock ID only exists in the
276
+ # follow-up run's own error.
277
+ - name: Cancellation recovery note
278
+ if: cancelled()
279
+ run: |
280
+ echo "::warning::This run was cancelled while Terraform may have held the state lock. If the next run fails with 'Error acquiring the state lock', run terraform force-unlock <LOCK_ID> (the ID is printed in that error) inside ./terraform — or delete the .tflock object beside the state file in S3 — then re-run."
@@ -17,19 +17,38 @@ jobs:
17
17
  drift:
18
18
  name: Detect Terraform drift
19
19
  runs-on: ubuntu-latest
20
+ timeout-minutes: 30
20
21
 
21
22
  steps:
22
23
  - name: Checkout Code
23
- uses: actions/checkout@v4
24
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
24
25
 
25
26
  - name: Configure AWS Credentials
26
- uses: aws-actions/configure-aws-credentials@v4
27
+ id: aws-creds
28
+ uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
29
+ continue-on-error: true
27
30
  with:
28
31
  role-to-assume: {{ROLE_ARN}}
29
32
  aws-region: ${{ env.AWS_REGION }}
30
33
 
34
+ # A missing role means the stack is absent (never provisioned or
35
+ # destroyed): skip loud instead of bursting red assume noise. Any
36
+ # other assume failure fails loud with both cases named (BUG-138).
37
+ - name: Interpret credential failure
38
+ if: steps.aws-creds.outcome == 'failure'
39
+ run: |
40
+ ROLE_ARN="{{ROLE_ARN}}"
41
+ TOKEN="$(curl -fsSL -H "Authorization: bearer ${ACTIONS_ID_TOKEN_REQUEST_TOKEN}" "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=sts.amazonaws.com" | jq -r '.value')"
42
+ ERR="$(aws sts assume-role-with-web-identity --role-arn "$ROLE_ARN" --role-session-name grada-preflight --web-identity-token "$TOKEN" 2>&1)" || true
43
+ if echo "$ERR" | grep -qiE 'NoSuchEntity|does not exist|cannot be found'; then
44
+ echo "::notice::AWS role $ROLE_ARN does not exist — the stack was likely never provisioned or was destroyed. Skipping this run (re-bootstrap with: npx grada-run apply)."
45
+ else
46
+ echo "::error::AWS credential assumption failed. Either the role is missing (stack absent — re-bootstrap with: npx grada-run apply) or the OIDC trust does not cover this run (check terraform/oidc.tf). Raw error: $ERR"
47
+ exit 1
48
+ fi
49
+
31
50
  - name: Setup Terraform
32
- uses: hashicorp/setup-terraform@v3
51
+ uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3
33
52
  with:
34
53
  # The wrapper mangles -detailed-exitcode; raw codes (0/1/2) are the signal.
35
54
  terraform_wrapper: false
@@ -41,10 +60,11 @@ jobs:
41
60
  # -detailed-exitcode: 0 = no changes, 1 = error, 2 = drift detected.
42
61
  - name: Terraform Plan
43
62
  id: plan
63
+ if: steps.aws-creds.outcome == 'success'
44
64
  working-directory: ./terraform
45
65
  run: |
46
66
  set +e
47
- terraform plan -detailed-exitcode -no-color -out=tfplan > plan-full.txt 2>&1
67
+ terraform plan -input=false -detailed-exitcode -no-color -out=tfplan > plan-full.txt 2>&1
48
68
  EXITCODE=$?
49
69
  echo "exitcode=$EXITCODE" >> "$GITHUB_OUTPUT"
50
70
  if [ "$EXITCODE" != "1" ]; then
@@ -54,6 +74,9 @@ jobs:
54
74
  fi
55
75
  echo "### Drift plan (exit $EXITCODE)" >> "$GITHUB_STEP_SUMMARY"
56
76
  head -50 plan.txt >> "$GITHUB_STEP_SUMMARY"
77
+ # Exit 2 (drift) stays green — the issue below tracks it. Exit 1
78
+ # (plan ERROR) must fail the run instead of going green-silent.
79
+ if [ "$EXITCODE" = "1" ]; then exit 1; fi
57
80
 
58
81
  # A plan on never-applied infrastructure also exits 2 (everything
59
82
  # "to add") — that is not drift. Skip the issue/Slack alarm when
@@ -73,7 +96,7 @@ jobs:
73
96
 
74
97
  - name: Report drift as GitHub Issue
75
98
  if: (steps.plan.outputs.exitcode == '2' || steps.plan.outputs.exitcode == '0') && steps.state.outputs.empty != 'true'
76
- uses: actions/github-script@v7
99
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
77
100
  with:
78
101
  script: |
79
102
  const fs = require('fs');
@@ -113,6 +136,52 @@ jobs:
113
136
  await github.rest.issues.createComment({ owner, repo, issue_number: existing.number, body: `✅ Drift resolved on \`${new Date().toISOString()}\` ([run](${runUrl})).` });
114
137
  await github.rest.issues.update({ owner, repo, issue_number: existing.number, state: 'closed' });
115
138
  }
139
+ // A 0/2 verdict means the check itself works: close any stale
140
+ // check-failure issue left by an earlier red run.
141
+ const { data: failed } = await github.rest.issues.listForRepo({ owner, repo, state: 'open', labels: 'iac-drift-check-failed' });
142
+ if (failed[0]) {
143
+ await github.rest.issues.createComment({ owner, repo, issue_number: failed[0].number, body: `✅ Drift check healthy again on \`${new Date().toISOString()}\` ([run](${runUrl})); closing.` });
144
+ await github.rest.issues.update({ owner, repo, issue_number: failed[0].number, state: 'closed' });
145
+ }
146
+
147
+ # Plan errors (exit 1) fail the run (see the plan step) AND leave a
148
+ # trackable issue under their own label — never green-silent.
149
+ - name: Report drift check failure as GitHub Issue
150
+ if: failure() && steps.plan.outputs.exitcode == '1'
151
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
152
+ with:
153
+ script: |
154
+ const fs = require('fs');
155
+ const { owner, repo } = context.repo;
156
+ const label = 'iac-drift-check-failed';
157
+ const runUrl = `https://github.com/${owner}/${repo}/actions/runs/${context.runId}`;
158
+ let diff = '';
159
+ try {
160
+ diff = fs.readFileSync('terraform/plan.txt', 'utf8');
161
+ } catch (error) {
162
+ diff = '(plan output unavailable)';
163
+ }
164
+ if (diff.length > 30000) {
165
+ diff = `${diff.slice(0, 30000)}\n... (truncated, see ${runUrl})`;
166
+ }
167
+ try {
168
+ await github.rest.issues.getLabel({ owner, repo, name: label });
169
+ } catch (error) {
170
+ if (error.status === 404) {
171
+ await github.rest.issues.createLabel({ owner, repo, name: label, color: 'd93f0b', description: 'Terraform drift check itself errored (plan exit 1)' });
172
+ } else {
173
+ throw error;
174
+ }
175
+ }
176
+ const { data: open } = await github.rest.issues.listForRepo({ owner, repo, state: 'open', labels: label });
177
+ const existing = open[0];
178
+ const body = `## ❌ Drift Check Failed\n\nThe scheduled drift check errored on \`${new Date().toISOString()}\` ([workflow run](${runUrl})) — this is a check failure, not drift.\n\n\`\`\`terraform\n${diff}\n\`\`\`\n\nFix the check (credentials, backend, syntax) and the issue closes on the next green run.`;
179
+ if (existing) {
180
+ await github.rest.issues.createComment({ owner, repo, issue_number: existing.number, body: `Check still failing on \`${new Date().toISOString()}\` ([run](${runUrl})).\n\n\`\`\`terraform\n${diff}\n\`\`\`` });
181
+ await github.rest.issues.update({ owner, repo, issue_number: existing.number, body });
182
+ } else {
183
+ await github.rest.issues.create({ owner, repo, title: '❌ IaC Drift Check Failed', labels: [label], body });
184
+ }
116
185
 
117
186
  - name: Notify Slack
118
187
  if: steps.plan.outputs.exitcode == '2' && steps.state.outputs.empty != 'true'
@@ -1,12 +1,17 @@
1
1
  name: Ephemeral PR Preview
2
2
 
3
3
  on:
4
- pull_request:
4
+ # pull_request_target (not pull_request): this file comes from the base
5
+ # branch, so a fork PR cannot delete the same-repo guard below to reach
6
+ # the admin CI role (BUG-140). The PR head is checked out explicitly by
7
+ # SHA in the guarded step instead.
8
+ pull_request_target:
5
9
  types: [opened, synchronize, reopened]
6
10
 
7
11
  # One runner per PR: rapid pushes cancel superseded previews instead of
8
- # overlapping applies on the same workspace. Shares its group with
9
- # teardown.yml, which queues (never cancels) behind an in-flight deploy.
12
+ # overlapping applies on the same workspace. Teardown runs in its own
13
+ # group (a reopen must never cancel an in-flight destroy); the state
14
+ # lock serializes the destroy/apply race instead (see -lock-timeout).
10
15
  concurrency:
11
16
  group: preview-${{ github.event.pull_request.number }}
12
17
  cancel-in-progress: true
@@ -15,6 +20,7 @@ env:
15
20
  AWS_REGION: {{REGION}}
16
21
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
17
22
  WORKSPACE: pr-${{ github.event.pull_request.number }}
23
+ CF_COMMENT: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-cdn
18
24
 
19
25
  permissions:
20
26
  id-token: write
@@ -24,23 +30,54 @@ permissions:
24
30
  jobs:
25
31
  deploy-preview:
26
32
  name: Provision Preview Environment
33
+ # Same-repo PRs only: fork code must never execute with the admin CI
34
+ # role or production secrets. Trustworthy because this file comes from
35
+ # base (see trigger above). Public repos needing fork previews should
36
+ # gate this job behind an environment with required reviewers instead
37
+ # of deleting the guard.
38
+ if: github.event.pull_request.head.repo.full_name == github.repository
27
39
  runs-on: ubuntu-latest
40
+ timeout-minutes: 45
28
41
 
29
42
  steps:
30
- - name: Checkout Code
31
- uses: actions/checkout@v4
43
+ - name: Checkout PR head
44
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
45
+ with:
46
+ # Pinned SHA (not a ref name): the exact head this event fired
47
+ # for, immune to ref moves between event and checkout.
48
+ ref: ${{ github.event.pull_request.head.sha }}
32
49
 
33
50
  - name: Configure AWS credentials
34
- uses: aws-actions/configure-aws-credentials@v4
51
+ id: aws-creds
52
+ uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
53
+ continue-on-error: true
35
54
  with:
36
55
  role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
37
56
  aws-region: ${{ env.AWS_REGION }}
38
57
 
58
+ # A missing role means the stack is absent (never provisioned or
59
+ # destroyed): skip loud instead of bursting red assume noise. Any
60
+ # other assume failure fails loud with both cases named (BUG-138).
61
+ - name: Interpret credential failure
62
+ if: steps.aws-creds.outcome == 'failure'
63
+ run: |
64
+ ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role"
65
+ TOKEN="$(curl -fsSL -H "Authorization: bearer ${ACTIONS_ID_TOKEN_REQUEST_TOKEN}" "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=sts.amazonaws.com" | jq -r '.value')"
66
+ ERR="$(aws sts assume-role-with-web-identity --role-arn "$ROLE_ARN" --role-session-name grada-preflight --web-identity-token "$TOKEN" 2>&1)" || true
67
+ if echo "$ERR" | grep -qiE 'NoSuchEntity|does not exist|cannot be found'; then
68
+ echo "::notice::AWS role $ROLE_ARN does not exist — the stack was likely never provisioned or was destroyed. Skipping this run (re-bootstrap with: npx grada-run apply)."
69
+ else
70
+ echo "::error::AWS credential assumption failed. Either the role is missing (stack absent — re-bootstrap with: npx grada-run apply) or the OIDC trust does not cover this run (check terraform/oidc.tf). Raw error: $ERR"
71
+ exit 1
72
+ fi
73
+
39
74
  - name: Login to Amazon ECR
75
+ if: steps.aws-creds.outcome == 'success'
40
76
  id: login-ecr
41
- uses: aws-actions/amazon-ecr-login@v2
77
+ uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2
42
78
 
43
79
  - name: Build and Push Docker image
80
+ if: steps.aws-creds.outcome == 'success'
44
81
  env:
45
82
  ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
46
83
  run: |
@@ -49,18 +86,22 @@ jobs:
49
86
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:${{ env.WORKSPACE }}
50
87
 
51
88
  - name: Setup Terraform
52
- uses: hashicorp/setup-terraform@v3
89
+ uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3
53
90
 
54
91
  - name: Terraform Init & Apply
55
92
  id: tf-apply
93
+ if: steps.aws-creds.outcome == 'success'
56
94
  working-directory: ./terraform
57
95
  run: |
58
96
  terraform init -input=false
59
97
  # Create or select the workspace specific to this PR
60
98
  terraform workspace select -or-create ${{ env.WORKSPACE }}
61
- terraform apply -auto-approve
99
+ # Teardown runs in its own group (see teardown.yml): a reopen
100
+ # during teardown waits on the state lock instead of racing it.
101
+ terraform apply -auto-approve -input=false -lock-timeout=10m
62
102
 
63
103
  - name: Deploy PR image to the preview function
104
+ if: steps.aws-creds.outcome == 'success'
64
105
  env:
65
106
  ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
66
107
  run: |
@@ -76,18 +117,107 @@ jobs:
76
117
  --region ${{ env.AWS_REGION }}
77
118
 
78
119
  - name: Read preview URL
120
+ if: steps.aws-creds.outcome == 'success'
79
121
  working-directory: ./terraform
80
122
  run: |
81
123
  API_URL=$(terraform output -raw api_gateway_url)
82
124
  echo "PREVIEW_URL=$API_URL" >> $GITHUB_ENV
83
125
 
126
+ # Every push redeploys the preview: clear its CDN so new HTML shows
127
+ # immediately instead of serving stale pages until TTL expiry.
128
+ - name: Invalidate CloudFront
129
+ if: steps.aws-creds.outcome == 'success'
130
+ run: |
131
+ DIST_ID=$(aws cloudfront list-distributions \
132
+ --query "DistributionList.Items[?Comment=='${{ env.CF_COMMENT }}'].Id | [0]" \
133
+ --output text \
134
+ --region ${{ env.AWS_REGION }})
135
+ if [ -z "$DIST_ID" ] || [ "$DIST_ID" = "None" ]; then
136
+ echo "CloudFront distribution '${{ env.CF_COMMENT }}' not found." >&2
137
+ exit 1
138
+ fi
139
+ aws cloudfront create-invalidation \
140
+ --distribution-id "$DIST_ID" \
141
+ --paths "/*" \
142
+ --region ${{ env.AWS_REGION }}
143
+
144
+ # One sticky comment per PR (updated in place), never a new
145
+ # comment per push — and a failed run overwrites the green URL
146
+ # instead of leaving it standing as truth (BUG-190).
84
147
  - name: Comment PR
85
- uses: actions/github-script@v7
148
+ if: steps.aws-creds.outcome == 'success'
149
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
86
150
  with:
87
151
  script: |
88
- github.rest.issues.createComment({
152
+ const marker = '<!-- grada-preview -->';
153
+ const body = `${marker}\n🚀 **Preview Environment Deployed!**\n\nYour ephemeral AWS Lambda environment is live at:\n[${process.env.PREVIEW_URL}](${process.env.PREVIEW_URL})\n\n_This environment will be automatically destroyed when the PR is merged or closed._\n\n---\n<div align="right"><sup>☁️ Generated by <a href="https://github.com/grada-run/grada">Grada</a></sup></div>`;
154
+ const { data: comments } = await github.rest.issues.listComments({
89
155
  issue_number: context.issue.number,
90
156
  owner: context.repo.owner,
91
157
  repo: context.repo.repo,
92
- body: `🚀 **Preview Environment Deployed!**\n\nYour ephemeral AWS Lambda environment is live at:\n[${process.env.PREVIEW_URL}](${process.env.PREVIEW_URL})\n\n_This environment will be automatically destroyed when the PR is merged or closed._\n\n---\n<div align="right"><sup>☁️ Generated by <a href="https://github.com/grada-run/grada">Grada</a></sup></div>`
93
- })
158
+ });
159
+ const existing = comments.find((comment) => comment.body?.includes(marker));
160
+ if (existing) {
161
+ await github.rest.issues.updateComment({
162
+ owner: context.repo.owner,
163
+ repo: context.repo.repo,
164
+ comment_id: existing.id,
165
+ body,
166
+ });
167
+ } else {
168
+ await github.rest.issues.createComment({
169
+ issue_number: context.issue.number,
170
+ owner: context.repo.owner,
171
+ repo: context.repo.repo,
172
+ body,
173
+ });
174
+ }
175
+
176
+ - name: Report preview failure on PR
177
+ if: failure()
178
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
179
+ with:
180
+ script: |
181
+ const marker = '<!-- grada-preview -->';
182
+ const runUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
183
+ const body = `${marker}\n❌ **Preview Environment Failed**\n\nThe preview deployment for this PR failed — the URL below (if any) is stale. See the [workflow run](${runUrl}) for details.`;
184
+ const { data: comments } = await github.rest.issues.listComments({
185
+ issue_number: context.issue.number,
186
+ owner: context.repo.owner,
187
+ repo: context.repo.repo,
188
+ });
189
+ const existing = comments.find((comment) => comment.body?.includes(marker));
190
+ if (existing) {
191
+ await github.rest.issues.updateComment({
192
+ owner: context.repo.owner,
193
+ repo: context.repo.repo,
194
+ comment_id: existing.id,
195
+ body,
196
+ });
197
+ } else {
198
+ await github.rest.issues.createComment({
199
+ issue_number: context.issue.number,
200
+ owner: context.repo.owner,
201
+ repo: context.repo.repo,
202
+ body,
203
+ });
204
+ }
205
+
206
+ # A cancelled apply can strand the S3 state lockfile: point at
207
+ # recovery instead of leaving the next run to fail obscurely
208
+ # (BUG-194). Generic by necessity — the lock ID only exists in the
209
+ # follow-up run's own error.
210
+ - name: Cancellation recovery note
211
+ if: cancelled()
212
+ run: |
213
+ echo "::warning::This run was cancelled while Terraform may have held the state lock. If the next run fails with 'Error acquiring the state lock', run terraform force-unlock <LOCK_ID> (the ID is printed in that error) inside ./terraform — or delete the .tflock object beside the state file in S3 — then re-run."
214
+
215
+ # Fork PRs skip the privileged job above loudly instead of silently:
216
+ # no credentials are issued and no preview is provisioned.
217
+ fork-notice:
218
+ name: Fork PR notice
219
+ if: github.event.pull_request.head.repo.full_name != github.repository
220
+ runs-on: ubuntu-latest
221
+ timeout-minutes: 5
222
+ steps:
223
+ - run: echo "PR previews run for same-repo pull requests only — fork PR #${{ github.event.pull_request.number }} skipped (no AWS credentials issued)."