forked from RijksICTGilde/zad-actions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction.yml
More file actions
388 lines (365 loc) · 14.5 KB
/
Copy pathaction.yml
File metadata and controls
388 lines (365 loc) · 14.5 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
# SPDX-License-Identifier: EUPL-1.2
name: 'Deploy to ZAD'
description: 'Deploy a container image to ZAD Operations Manager'
author: 'RijksICTGilde'
branding:
icon: 'upload-cloud'
color: 'blue'
inputs:
api-key:
description: 'ZAD API key (ZAD_API_KEY secret)'
required: true
project-id:
description: 'ZAD project identifier (e.g., regel-k4c)'
required: true
deployment-name:
description: 'Name of the deployment (e.g., pr-73, production)'
required: true
component:
description: 'Component reference (e.g., editor, api, my.service)'
required: true
image:
description: 'Full container image URI (e.g., ghcr.io/org/app:tag)'
required: true
clone-from:
description: 'Clone configuration from existing deployment (optional)'
required: false
default: ''
force-clone:
description: 'Force clone even if deployment exists (optional, default: false)'
required: false
default: 'false'
api-base-url:
description: 'ZAD Operations Manager API base URL'
required: false
default: 'https://operations-manager.rig.prd1.gn2.quattro.rijksapps.nl/api'
comment-on-pr:
description: 'Post/update a comment on the PR with the deployment URL'
required: false
default: 'false'
github-token:
description: 'GitHub token for PR commenting (defaults to automatic token)'
required: false
default: '${{ github.token }}'
comment-header:
description: 'Custom header for the PR comment (default: "## 🚀 Preview Deployment")'
required: false
default: '## 🚀 Preview Deployment'
wait-for-ready:
description: 'Wait for deployment to be reachable before continuing'
required: false
default: 'false'
health-endpoint:
description: 'Endpoint to check for readiness (e.g., /, /health)'
required: false
default: '/'
wait-timeout:
description: 'Maximum time to wait for deployment in seconds'
required: false
default: '300'
wait-interval:
description: 'Seconds between readiness checks'
required: false
default: '10'
qr-code:
description: 'Include QR code in PR comment for mobile access (generated locally via qrencode)'
required: false
default: 'false'
skip-bot-prs:
description: 'Skip deployment for PRs created by bots (dependabot, renovate, pre-commit-ci, etc.)'
required: false
default: 'true'
max-retries:
description: 'Maximum number of retries for transient ZAD API errors (0 to disable)'
required: false
default: '3'
retry-delay:
description: 'Initial retry delay in seconds (doubles each retry)'
required: false
default: '2'
path-suffix:
description: 'Path to append to the deployment URL (e.g. /docs/)'
required: false
default: ''
outputs:
url:
description: 'URL of the deployed application'
value: ${{ steps.deploy.outputs.url }}
skipped:
description: 'Whether deployment was skipped due to bot PR detection'
value: ${{ steps.bot-check.outputs.skipped == 'true' && 'true' || 'false' }}
runs:
using: 'composite'
steps:
- name: Check for bot PR
id: bot-check
if: inputs.skip-bot-prs == 'true' && (github.event_name == 'pull_request' || github.event_name == 'pull_request_target')
shell: bash
env:
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
PR_AUTHOR_TYPE: ${{ github.event.pull_request.user.type }}
run: |
KNOWN_BOTS=("dependabot[bot]" "renovate[bot]" "pre-commit-ci[bot]" "github-actions[bot]")
if [ "$PR_AUTHOR_TYPE" = "Bot" ]; then
echo "::notice::Skipping: PR author '$PR_AUTHOR' is a bot (type: $PR_AUTHOR_TYPE)"
echo "skipped=true" >> "$GITHUB_OUTPUT"
exit 0
fi
for bot in "${KNOWN_BOTS[@]}"; do
if [ "$PR_AUTHOR" = "$bot" ]; then
echo "::notice::Skipping: PR author '$PR_AUTHOR' is a known bot"
echo "skipped=true" >> "$GITHUB_OUTPUT"
exit 0
fi
done
echo "skipped=false" >> "$GITHUB_OUTPUT"
- name: Deploy to ZAD
id: deploy
if: steps.bot-check.outputs.skipped != 'true'
shell: bash
env:
ZAD_API_KEY: ${{ inputs.api-key }}
PROJECT_ID: ${{ inputs.project-id }}
DEPLOYMENT_NAME: ${{ inputs.deployment-name }}
COMPONENT: ${{ inputs.component }}
IMAGE: ${{ inputs.image }}
CLONE_FROM: ${{ inputs.clone-from }}
FORCE_CLONE: ${{ inputs.force-clone }}
API_BASE_URL: ${{ inputs.api-base-url }}
MAX_RETRIES: ${{ inputs.max-retries }}
RETRY_DELAY: ${{ inputs.retry-delay }}
PATH_SUFFIX: ${{ inputs.path-suffix }}
run: |
# Validate inputs FIRST (before logging)
# Allow alphanumeric, hyphens, underscores, and dots
if ! echo "$PROJECT_ID" | grep -qE '^[a-zA-Z0-9._-]+$'; then
echo "Error: project-id contains invalid characters (allowed: a-z, A-Z, 0-9, ., _, -)"
exit 1
fi
if ! echo "$DEPLOYMENT_NAME" | grep -qE '^[a-zA-Z0-9._-]+$'; then
echo "Error: deployment-name contains invalid characters (allowed: a-z, A-Z, 0-9, ., _, -)"
exit 1
fi
if ! echo "$COMPONENT" | grep -qE '^[a-zA-Z0-9._-]+$'; then
echo "Error: component contains invalid characters (allowed: a-z, A-Z, 0-9, ., _, -)"
exit 1
fi
if [ -n "$CLONE_FROM" ] && ! echo "$CLONE_FROM" | grep -qE '^[a-zA-Z0-9._-]+$'; then
echo "Error: clone-from contains invalid characters (allowed: a-z, A-Z, 0-9, ., _, -)"
exit 1
fi
if ! echo "$MAX_RETRIES" | grep -qE '^[0-9]+$'; then
echo "Error: max-retries must be a non-negative integer"
exit 1
fi
if ! echo "$RETRY_DELAY" | grep -qE '^[0-9]+$'; then
echo "Error: retry-delay must be a non-negative integer"
exit 1
fi
# Now safe to log validated inputs
echo "Deploying to ZAD..."
echo "Project: $PROJECT_ID"
echo "Deployment: $DEPLOYMENT_NAME"
echo "Component: $COMPONENT"
echo "Image: $IMAGE"
if [ -n "$CLONE_FROM" ]; then
echo "Cloning config from: $CLONE_FROM (force: $FORCE_CLONE)"
fi
# Build the request payload
if [ -n "$CLONE_FROM" ]; then
FORCE_CLONE_BOOL="false"
if [ "$FORCE_CLONE" = "true" ]; then
FORCE_CLONE_BOOL="true"
fi
PAYLOAD=$(jq -n \
--arg name "$DEPLOYMENT_NAME" \
--arg ref "$COMPONENT" \
--arg image "$IMAGE" \
--arg clone "$CLONE_FROM" \
--argjson force "$FORCE_CLONE_BOOL" \
'{
deploymentName: $name,
cloneFrom: $clone,
forceClone: $force,
components: [{
reference: $ref,
image: $image
}]
}')
else
PAYLOAD=$(jq -n \
--arg name "$DEPLOYMENT_NAME" \
--arg ref "$COMPONENT" \
--arg image "$IMAGE" \
'{
deploymentName: $name,
components: [{
reference: $ref,
image: $image
}]
}')
fi
# Retry helper: curl_with_retry URL [curl_args...]
# Uses MAX_RETRIES and RETRY_DELAY from environment.
# Sets FINAL_HTTP_CODE and FINAL_BODY after completion.
curl_with_retry() {
local url="$1"; shift
local attempt=0
local delay="$RETRY_DELAY"
while true; do
local response
response=$(curl -s -w "\n%{http_code}" --max-time 60 "$@" "$url")
FINAL_HTTP_CODE=$(echo "$response" | tail -n1)
FINAL_BODY=$(echo "$response" | sed '$d')
# Success
if [ "$FINAL_HTTP_CODE" -ge 200 ] && [ "$FINAL_HTTP_CODE" -lt 300 ]; then
return 0
fi
# Determine if retryable
local retryable=false
if [ "$FINAL_HTTP_CODE" -eq 000 ] || [ "$FINAL_HTTP_CODE" -eq 429 ]; then
retryable=true
elif [ "$FINAL_HTTP_CODE" -ge 500 ] && [ "$FINAL_HTTP_CODE" -le 504 ]; then
retryable=true
fi
if [ "$retryable" = "true" ] && [ "$attempt" -lt "$MAX_RETRIES" ]; then
attempt=$((attempt + 1))
echo "::warning::Transient error (HTTP $FINAL_HTTP_CODE), retrying in ${delay}s (attempt $attempt/$MAX_RETRIES)..."
sleep "$delay"
delay=$((delay * 2))
continue
fi
# Non-retryable or retries exhausted
return 1
done
}
# Make the API call with retry logic
# Safe to retry: upsert-deployment is idempotent (same payload = same result)
if curl_with_retry "$API_BASE_URL/projects/$PROJECT_ID/:upsert-deployment" \
-X POST \
-H "X-API-Key: $ZAD_API_KEY" \
-H "Content-Type: application/json" \
-d "$PAYLOAD"; then
echo "Deployment successful (HTTP $FINAL_HTTP_CODE)"
echo "$FINAL_BODY" | jq . 2>/dev/null || echo "$FINAL_BODY"
# Construct the URL (standard ZAD URL pattern)
URL="https://${COMPONENT}-${DEPLOYMENT_NAME}-${PROJECT_ID}.rig.prd1.gn2.quattro.rijksapps.nl"
if [ -n "$PATH_SUFFIX" ]; then
URL="${URL%/}/${PATH_SUFFIX#/}"
fi
echo "url=$URL" >> "$GITHUB_OUTPUT"
echo "Deployed to: $URL"
else
if [ "$FINAL_HTTP_CODE" -eq 000 ]; then
echo "::error::Deployment failed: Unable to connect to ZAD API"
echo "::error::This could be a network issue or the API may be unavailable"
echo "::error::Please verify the API URL: $API_BASE_URL"
elif [ "$FINAL_HTTP_CODE" -eq 401 ]; then
echo "::error::Deployment failed: Authentication failed (HTTP 401)"
echo "::error::Please verify your ZAD_API_KEY secret is correct and not expired"
elif [ "$FINAL_HTTP_CODE" -eq 403 ]; then
echo "::error::Deployment failed: Access denied (HTTP 403)"
echo "::error::Your API key may not have permission for project '$PROJECT_ID'"
elif [ "$FINAL_HTTP_CODE" -eq 404 ]; then
echo "::error::Deployment failed: Project not found (HTTP 404)"
echo "::error::Please verify project-id '$PROJECT_ID' exists in ZAD"
elif [ "$FINAL_HTTP_CODE" -ge 500 ]; then
echo "::error::Deployment failed: ZAD API server error (HTTP $FINAL_HTTP_CODE) after retries"
echo "$FINAL_BODY"
else
echo "::error::Deployment failed (HTTP $FINAL_HTTP_CODE)"
echo "$FINAL_BODY"
fi
exit 1
fi
- name: Wait for deployment to be ready
if: steps.bot-check.outputs.skipped != 'true' && inputs.wait-for-ready == 'true'
shell: bash
env:
DEPLOYMENT_URL: ${{ steps.deploy.outputs.url }}
HEALTH_ENDPOINT: ${{ inputs.health-endpoint }}
WAIT_TIMEOUT: ${{ inputs.wait-timeout }}
WAIT_INTERVAL: ${{ inputs.wait-interval }}
run: |
URL="${DEPLOYMENT_URL}${HEALTH_ENDPOINT}"
echo "Waiting for $URL to be ready..."
ELAPSED=0
while [ "$ELAPSED" -lt "$WAIT_TIMEOUT" ]; do
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "$URL" || echo "000")
if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 400 ]; then
echo "Deployment is ready (HTTP $HTTP_CODE)"
exit 0
fi
echo "Waiting... (HTTP $HTTP_CODE, ${ELAPSED}s elapsed)"
sleep "$WAIT_INTERVAL"
ELAPSED=$((ELAPSED + WAIT_INTERVAL))
done
echo "::error::Deployment did not become ready within ${WAIT_TIMEOUT}s"
exit 1
- name: Generate QR code
id: qr
if: >-
steps.bot-check.outputs.skipped != 'true'
&& inputs.qr-code == 'true'
&& inputs.comment-on-pr == 'true'
&& github.event_name == 'pull_request'
shell: bash
env:
DEPLOYMENT_URL: ${{ steps.deploy.outputs.url }}
run: |
sudo apt-get install -y qrencode >/dev/null 2>&1 || true
if command -v qrencode &> /dev/null; then
QR_TEXT=$(qrencode -t UTF8 -m 0 -l L -o - "$DEPLOYMENT_URL")
# Use delimiter for multi-line output
EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
{
echo "html<<$EOF"
printf '<details>\n<summary>📱 Scan to open on mobile</summary>\n\n```\n'
echo "$QR_TEXT"
printf '```\n\n</details>'
echo ""
echo "$EOF"
} >> "$GITHUB_OUTPUT"
else
echo "Warning: qrencode not available, skipping QR code"
fi
- name: Comment on PR
if: steps.bot-check.outputs.skipped != 'true' && inputs.comment-on-pr == 'true' && github.event_name == 'pull_request'
shell: bash
env:
GH_TOKEN: ${{ inputs.github-token }}
DEPLOYMENT_URL: ${{ steps.deploy.outputs.url }}
COMMENT_HEADER: ${{ inputs.comment-header }}
PR_NUMBER: ${{ github.event.pull_request.number }}
GITHUB_REPOSITORY: ${{ github.repository }}
QR_HTML: ${{ steps.qr.outputs.html }}
run: |
# Build the comment body
COMMENT_BODY="${COMMENT_HEADER}"$'\n\n'
COMMENT_BODY+="Your changes have been deployed to a preview environment:"$'\n\n'
COMMENT_BODY+="**URL:** ${DEPLOYMENT_URL}"$'\n\n'
if [ -n "$QR_HTML" ]; then
COMMENT_BODY+="${QR_HTML}"$'\n\n'
fi
COMMENT_BODY+="This deployment will be automatically cleaned up when the PR is closed."
# Check for existing comment from this action (identified by header)
EXISTING_COMMENT_ID=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \
--jq ".[] | select(.body | startswith(\"${COMMENT_HEADER}\")) | .id" \
2>/dev/null | head -n1 || echo "")
if [ -n "$EXISTING_COMMENT_ID" ]; then
# Update existing comment
echo "Updating existing PR comment (ID: $EXISTING_COMMENT_ID)"
gh api "repos/${GITHUB_REPOSITORY}/issues/comments/${EXISTING_COMMENT_ID}" \
-X PATCH \
-f body="$COMMENT_BODY" \
--silent
echo "PR comment updated"
else
# Create new comment
echo "Creating new PR comment"
gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \
-X POST \
-f body="$COMMENT_BODY" \
--silent
echo "PR comment created"
fi