-
Notifications
You must be signed in to change notification settings - Fork 2
468 lines (410 loc) · 20.1 KB
/
Copy pathdeploy.yml
File metadata and controls
468 lines (410 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
name: Deploy to AWS ECS
on:
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+-*'
concurrency:
group: deploy-production
cancel-in-progress: false
# The workflow only talks to AWS; contents: read is all checkout needs.
permissions:
contents: read
env:
AWS_REGION: eu-west-1
ECR_REGISTRY: 525984396332.dkr.ecr.eu-west-1.amazonaws.com
ECR_REPOSITORY: b10cks/cms
ECS_CLUSTER: nb-clients01
ECS_SERVICE: b10cks-cms
ECS_TASK_DEFINITION: b10cks-cms
PHP_VERSION: '8.5'
VITE_S3_BUCKET: ${{ secrets.VITE_S3_BUCKET }}
DOCS_S3_BUCKET: b10cks-production-docs
DOCS_CLOUDFRONT_DISTRIBUTION_ID: E2DCMG9O2W1BIA
jobs:
# Same gate as release.yml: a calver tag can land on any commit, and without
# this a red one would deploy straight to production. Reuses tests.yml so the
# gate cannot drift from what runs on pull requests.
test:
uses: ./.github/workflows/tests.yml
# The deploy job's own Discord notification never runs when the gate fails
# (the job is skipped, not failed), so a blocked deploy would otherwise be
# silent outside the Actions UI.
notify-blocked:
needs: test
if: failure()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Post blocked-deploy notification to Discord
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_URL }}
run: |
VERSION="${GITHUB_REF#refs/tags/v}"
PAYLOAD=$(jq -n \
--arg title "🚫 Deployment Blocked — Tests Failed" \
--arg description "**Project:** https://github.com/b10cks/cms
**Version:** \`${VERSION}\`
The test suite failed, so this tag was not deployed.
${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" \
--arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" \
'{
"embeds": [{
"title": $title,
"description": $description,
"color": 15158332,
"timestamp": $timestamp
}]
}')
curl -H "Content-Type: application/json" \
-d "$PAYLOAD" \
"$DISCORD_WEBHOOK"
deploy:
needs: test
runs-on: ubuntu-latest
# must leave room for a worst-case docs build (2 × 5 min timeout) and a
# worst-case rollback (3 min smoke retries + 10 min services-stable wait)
# on top of the normal ~10 min pipeline
timeout-minutes: 40
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0 # Fetch all history for commit comparison
- name: Extract version from tag
id: version
run: |
VERSION=${GITHUB_REF#refs/tags/v}
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.3.14
- name: Setup PHP
uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # 2.37.2
with:
php-version: ${{ env.PHP_VERSION }}
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, redis
tools: composer:v2
- name: Install production Composer dependencies
run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --no-dev
- name: Restore committed OpenAPI specs
# composer's post-autoload-dump runs `artisan docs:generate`, which
# regenerates docs/public/specs without a real app environment; the
# degenerate output sends the vitepress-openapi spec parser into an
# infinite loop during docs SSR. The committed specs are the source
# of truth for CI builds.
run: git checkout -- docs/public/specs
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6.2.3
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}
- name: Cache Bun dependencies
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Build frontend
run: bun run build
env:
NODE_ENV: production
- name: Build docs
id: docs
# vitepress repeatedly hangs in the SSR render phase in this job
# (fine in isolation) — bound it, retry once, and never block the
# app deploy on it: on failure we skip docs publishing instead.
run: |
if timeout 300 bun run docs:build || {
echo "::warning::docs build failed or timed out — retrying once"
rm -rf public/docs
timeout 300 bun run docs:build
}; then
echo "built=true" >> $GITHUB_OUTPUT
else
echo "::warning::docs build failed twice — deploying without docs update"
echo "built=false" >> $GITHUB_OUTPUT
fi
env:
NODE_ENV: production
APP_URL: ${{ vars.APP_FRONTEND_URL || 'https://app.b10cks.com' }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2.1.7
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
- name: Check for existing image
id: image-exists
# tags are immutable — a re-run after a partial failure must not
# re-push the tag its first attempt already published
env:
IMAGE_TAG: main-${{ steps.version.outputs.version }}
run: |
if aws ecr describe-images \
--repository-name ${{ env.ECR_REPOSITORY }} \
--image-ids imageTag=$IMAGE_TAG >/dev/null 2>&1; then
echo "::notice::${IMAGE_TAG} already in ECR — skipping build and push"
echo "exists=true" >> $GITHUB_OUTPUT
else
echo "exists=false" >> $GITHUB_OUTPUT
fi
- name: Build and push Docker image
if: steps.image-exists.outputs.exists != 'true'
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
with:
context: .
push: true
tags: ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:main-${{ steps.version.outputs.version }}
build-args: |
APP_VERSION=${{ steps.version.outputs.version }}
cache-from: type=registry,ref=${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:cache
cache-to: type=registry,ref=${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:cache,mode=max
provenance: false
- name: Download current task definition
id: current-task-def
# This runs before the new revision is registered, so taskDefinitionArn
# here is the revision production is serving right now. It is captured as
# an output because it is the rollback target and it cannot be recovered
# later: after the deploy the family's newest revision is the broken one,
# and "newest minus one" is wrong whenever a revision was registered but
# never deployed.
run: |
aws ecs describe-task-definition \
--task-definition ${{ env.ECS_TASK_DEFINITION }} \
--query taskDefinition > task-definition.json
echo "previous-arn=$(jq -r '.taskDefinitionArn' task-definition.json)" >> $GITHUB_OUTPUT
- name: Update task definition with new image
id: task-def
uses: aws-actions/amazon-ecs-render-task-definition@138c24f321fdbdf7edee4a685519d253cae2cdea # v1.9.0
with:
task-definition: task-definition.json
container-name: ${{ env.ECS_TASK_DEFINITION }}
image: ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:main-${{ steps.version.outputs.version }}
- name: Download reverb task definition
run: |
aws ecs describe-task-definition \
--task-definition b10cks-reverb \
--query taskDefinition > reverb-task-definition.json
- name: Update reverb task definition with new image
id: reverb-task-def-image
uses: aws-actions/amazon-ecs-render-task-definition@138c24f321fdbdf7edee4a685519d253cae2cdea # v1.9.0
with:
task-definition: reverb-task-definition.json
container-name: b10cks-reverb
image: ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:main-${{ steps.version.outputs.version }}
- name: Switch reverb task definition to supervisord config
id: reverb-task-def
run: |
jq '.containerDefinitions[0].entryPoint = ["/usr/bin/supervisord", "-c", "/etc/supervisord-reverb.conf", "-n"]' \
${{ steps.reverb-task-def-image.outputs.task-definition }} > reverb-task-definition-final.json
echo "task-definition=reverb-task-definition-final.json" >> $GITHUB_OUTPUT
- name: Sync static assets to S3
run: |
aws s3 sync public/build/ "s3://${{ env.VITE_S3_BUCKET }}/build" \
--delete \
--cache-control "max-age=7776000,s-maxage=604800,public"
- name: Publish docs to S3
if: steps.docs.outputs.built == 'true'
run: |
# HTML gets short-lived cache (invalidated below), hashed assets long-lived
aws s3 sync public/docs/ "s3://${{ env.DOCS_S3_BUCKET }}/docs" \
--delete \
--exclude "*.html" \
--cache-control "max-age=7776000,s-maxage=604800,public"
aws s3 sync public/docs/ "s3://${{ env.DOCS_S3_BUCKET }}/docs" \
--exclude "*" \
--include "*.html" \
--cache-control "max-age=0,s-maxage=604800,public,must-revalidate"
- name: Invalidate docs CloudFront cache
if: steps.docs.outputs.built == 'true'
run: |
aws cloudfront create-invalidation \
--distribution-id ${{ env.DOCS_CLOUDFRONT_DISTRIBUTION_ID }} \
--paths "/docs*"
- name: Deploy CMS service to Amazon ECS
uses: aws-actions/amazon-ecs-deploy-task-definition@c465972ecbd160473f22e683363b422a5412a3de # v2.6.3
with:
task-definition: ${{ steps.task-def.outputs.task-definition }}
service: ${{ env.ECS_SERVICE }}
cluster: ${{ env.ECS_CLUSTER }}
wait-for-service-stability: true
wait-for-minutes: 10
# wait-for-service-stability only proves the ECS health check answers. That
# route touches no controller, no space and no token, so a deploy where
# every delivery request 500s still counts as stable (v2026.9.7-513f02b0).
# This step exercises the real thing: token auth, space binding, controller
# construction, query, resource serialisation.
- name: Smoke check delivery API
id: smoke
timeout-minutes: 5
env:
SMOKE_TOKEN: ${{ secrets.SMOKE_TEST_TOKEN }}
API_HOST: ${{ secrets.SMOKE_TEST_API_HOST || 'api.b10cks.com' }}
run: |
set -euo pipefail
# A skipped check that renders green is worse than no check, so an
# unset token is a hard failure, not a soft skip.
if [ -z "${SMOKE_TOKEN}" ]; then
echo "::error::SMOKE_TEST_TOKEN is not set. Add a delivery token (blx_…) as a repository secret; the smoke check cannot verify this deploy without one."
exit 1
fi
# Defeating the CDN: the delivery API sits behind CloudFront and a
# cached 200 would hide a dead origin. We pin a unique `rv`. That is the
# app's own revision parameter (EnsureRevision accepts any value and
# only redirects when it is absent), and the whole caching scheme is
# built on rv being part of the CloudFront cache key, so it is
# guaranteed to be forwarded and to miss. A random cache-buster param
# could be dropped by the cache policy's query-string allow list, and
# CloudFront ignores a `Cache-Control: no-cache` request header.
# Documented for exactly this use in docs/concepts/access-tokens.md.
#
# rv also varies per attempt: CloudFront caches 5xx responses for a
# short window by default, so a retry on a fixed rv could replay the
# failure we are trying to let settle.
attempt=1
max_attempts=5
delay=15
while true; do
rv="${GITHUB_RUN_ID}${GITHUB_RUN_ATTEMPT}$(date +%s)"
status=0
code=$(curl -sS -o response.json -w '%{http_code}' \
--connect-timeout 5 --max-time 20 \
-H 'accept: application/json' \
"https://${API_HOST}/api/v1/contents?per_page=1&rv=${rv}&token=${SMOKE_TOKEN}") || status=$?
if [ "${status}" -ne 0 ]; then
# curl exits non-zero on connection refused, DNS failure and timeout.
# Without capturing it, `set -e` would abort before the retry loop.
reason="curl exit ${status} (connection error or timeout)"
elif [ "${code}" != "200" ]; then
reason="HTTP ${code}"
elif ! jq -e '(.data | type) == "array" and .rv != null' response.json >/dev/null 2>&1; then
# A 200 carrying an error envelope, an empty body or an HTML error
# page must fail. `.rv` comes from the bound space, which is the
# thing that was null in the outage.
reason="unexpected body: $(head -c 300 response.json | tr -d '\n')"
else
echo "::notice::Delivery API healthy on attempt ${attempt} ($(jq '.data | length' response.json) item(s), rv $(jq -r '.rv' response.json))"
exit 0
fi
echo "::warning::Smoke check attempt ${attempt}/${max_attempts} failed: ${reason}"
if [ "${attempt}" -ge "${max_attempts}" ]; then
echo "::error::Delivery API smoke check failed after ${max_attempts} attempts: ${reason}"
exit 1
fi
attempt=$((attempt + 1))
sleep "${delay}"
done
# Only the CMS service rolls back. It is the one the smoke check covers.
# Reverb is deployed after the check (see below), so a failed check leaves
# it untouched on the previous image rather than needing its own rollback.
- name: Roll back CMS service to previous task definition
id: rollback
if: failure() && steps.smoke.outcome == 'failure'
env:
PREVIOUS_TASK_DEF: ${{ steps.current-task-def.outputs.previous-arn }}
run: |
set -euo pipefail
echo "::error::Rolling ${{ env.ECS_SERVICE }} back to ${PREVIOUS_TASK_DEF}"
aws ecs update-service \
--cluster ${{ env.ECS_CLUSTER }} \
--service ${{ env.ECS_SERVICE }} \
--task-definition "${PREVIOUS_TASK_DEF}" \
--force-new-deployment >/dev/null
# Wait, so the run does not report "rolled back" while the old tasks are
# still starting. Bounded by the waiter itself: 40 polls, 15s apart.
aws ecs wait services-stable \
--cluster ${{ env.ECS_CLUSTER }} \
--services ${{ env.ECS_SERVICE }}
echo "::notice::Rollback complete — ${{ env.ECS_SERVICE }} is stable on ${PREVIOUS_TASK_DEF}"
# After the smoke check: if the CMS rolls back, Reverb must not be left
# running the image that was just rejected.
- name: Deploy Reverb service to Amazon ECS
uses: aws-actions/amazon-ecs-deploy-task-definition@c465972ecbd160473f22e683363b422a5412a3de # v2.6.3
with:
task-definition: ${{ steps.reverb-task-def.outputs.task-definition }}
service: b10cks-reverb
cluster: ${{ env.ECS_CLUSTER }}
wait-for-service-stability: false
- name: Get commits since last release
id: commits
# Also on failure: the Discord embed reads "Changes since <tag>" and a
# rolled-back deploy is exactly when knowing what shipped matters.
if: always()
run: |
# Get the previous tag
PREVIOUS_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
if [ -z "$PREVIOUS_TAG" ]; then
# If no previous tag, get all commits
COMMITS=$(git log --pretty=format:"• %s" --no-merges)
else
# Get commits between previous tag and current
COMMITS=$(git log ${PREVIOUS_TAG}..HEAD --pretty=format:"• %s" --no-merges)
fi
COMMITS=$(echo -n "$COMMITS" | base64 | tr -d '\n')
echo "commits=${COMMITS}" >> $GITHUB_OUTPUT
echo "previous_tag=${PREVIOUS_TAG:-'Initial Release'}" >> $GITHUB_OUTPUT
- name: Post deployment notification to Discord
if: always()
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_URL }}
run: |
# A rollback is not a generic red failure: the tag is not live, but
# production is. It gets its own colour and wording so nobody has to
# open the run to find out which of the two happened.
ROLLBACK="${{ steps.rollback.outcome }}"
NOTE=""
if [ "$ROLLBACK" == "success" ]; then
COLOR="15105570" # Orange
STATUS="↩️ Deployment Rolled Back"
NOTE="\n\n**The delivery API smoke check failed after deploy.** ${{ env.ECS_SERVICE }} was rolled back to the previous task definition and is stable. This version is NOT live.\n${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
elif [ "$ROLLBACK" == "failure" ]; then
COLOR="10038562" # Dark red
STATUS="🚨 Rollback Failed — Check Production Now"
NOTE="\n\n**The smoke check failed and the automatic rollback did not complete.** The delivery API may still be down. Inspect the ${{ env.ECS_SERVICE }} service in ECS.\n${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
elif [ "${{ job.status }}" == "success" ]; then
COLOR="3066993" # Green
STATUS="✅ Deployment Successful"
else
COLOR="15158332" # Red
STATUS="❌ Deployment Failed"
fi
# Use jq to properly escape the commits for JSON
COMMITS=$(echo "${{ steps.commits.outputs.commits }}" | base64 --decode)
DESCRIPTION=$(echo -e "**Project:** https://github.com/b10cks/cms\n**Version:** \`${{ steps.version.outputs.version }}\`${NOTE}\n\n**Changes since ${{ steps.commits.outputs.previous_tag }}:**\n${COMMITS}")
# Truncate if too long (Discord has a 4096 char limit for description)
if [ ${#DESCRIPTION} -gt 3800 ]; then
DESCRIPTION=$(echo "${DESCRIPTION:0:3800}... (truncated)")
fi
# Create JSON payload with proper escaping
PAYLOAD=$(jq -n \
--arg title "$STATUS" \
--arg description "$DESCRIPTION" \
--arg color "$COLOR" \
--arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" \
--arg footer_text "Commit: ${{ steps.version.outputs.short_sha }}" \
'{
"embeds": [{
"title": $title,
"description": $description,
"color": $color|tonumber,
"timestamp": $timestamp,
"footer": {
"text": $footer_text
}
}]
}')
# Send to Discord
curl -H "Content-Type: application/json" \
-d "$PAYLOAD" \
$DISCORD_WEBHOOK
if [ ${{ job.status }} == 'success' ]; then
echo "✅ Deployment successful for version ${{ steps.version.outputs.version }}"
else
echo "❌ Deployment failed for version ${{ steps.version.outputs.version }}"
fi