-
Notifications
You must be signed in to change notification settings - Fork 0
512 lines (455 loc) · 21.5 KB
/
astrid-deploy-template.yml
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
name: Deploy template
on:
workflow_call:
inputs:
target_production_server_nickname:
required: true
type: string
full_app_url:
required: true
type: string
app_port:
required: true
type: string
secrets:
staging_ssh_key:
required: true
production_project_secrets:
required: false
sshgateway_ssh_key:
required: true
argand_ssh_key:
required: false
env:
STAGING_SERVER_HOST: 178.79.188.16
SSH_GATEWAY_HOST: sshgateway.computing.dundee.ac.uk
ARGAND_HOST: argand
DEPLOY_SSH_USER: deploy-user
# Syntax for workflow names is: job-name-in-caller-workflow / job-name-in-this-workflow https://stackoverflow.com/questions/71240338/
STAGING_WORKFLOW_NAME: Environments / Staging
PRODUCTION_WORKFLOW_NAME: Environments / Production
SLACK_CHANNEL_ID: C072R6HPW21
COMMAND_TIMEOUT: 30m
jobs:
deploy-staging:
name: "Staging"
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
# Note: currently hardcoded to check only the argand server
- name: Check subdomain and port uniqueness
id: domain-and-port-checks
run: |
deployed_services=$(curl -s http://resource-lister.amfws.arg.tech/get-sites)
services_with_matching_repo_name=$(echo $deployed_services | jq '.[] | select(.repository == "${{ github.event.repository.name }}")')
services_with_matching_domain=$(echo $deployed_services | jq '.[] | select(.domain == "${{ inputs.full_app_url }}")')
services_with_matching_port=$(echo $deployed_services | jq '.[] | select(.port == "${{ inputs.app_port }}")')
if [[ -n "$services_with_matching_repo_name" ]]
then
echo "INFO: Found an existing deployment for this repository";
if [[ -n "$services_with_matching_port" && "$services_with_matching_repo_name" != "$services_with_matching_port" ]]; then
echo "::error::Port has been changed to one occupied by a different service";
exit 1;
fi
if [[ "$services_with_matching_repo_name" != "$services_with_matching_domain" ]]; then
echo "::error::Attempted to change the subdomain";
exit 1;
fi
else
echo "INFO: Did not find an existing deployment for this repository";
if [[ -n "$services_with_matching_domain" || -n "$services_with_matching_port" ]]; then
echo "::error::Port or subdomain occupied by an existing service";
exit 1;
fi
fi
echo "INFO: No issues found";
- name: Pull latest code
uses: appleboy/[email protected]
with:
host: ${{ env.STAGING_SERVER_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.staging_ssh_key }}
script: |
cd ~/repos
if [ ! -d "${{ github.event.repository.name }}" ]; then
git clone [email protected]:arg-tech/${{ github.event.repository.name }}.git
echo "Repository cloned"
fi
cd "${{ github.event.repository.name }}"
echo "Deleting the local branch in case an old branch with the same name exists"
git checkout main
git branch -D ${{ github.head_ref }}
git fetch
git checkout ${{ github.head_ref }}
git reset --hard HEAD
git merge '@{u}'
echo "Repository pulled and updated"
- name: Check if up-to-date with main
if: github.base_ref == 'main'
uses: appleboy/[email protected]
with:
host: ${{ env.STAGING_SERVER_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.staging_ssh_key }}
script: |
cd ~/repos/${{ github.event.repository.name }}
if ! git merge-base --is-ancestor origin/main ${{ github.event.pull_request.head.sha }};
then echo "This branch is not up to date with main. It must be brought up to date so that staging is representative of production."; exit 1;
fi
echo "This branch is up to date with main and can be safely merged."
- name: Create project secrets
if: ${{ env.ARE_SECRETS_PRESENT == 'true' }}
env:
ARE_SECRETS_PRESENT: ${{ secrets.production_project_secrets != '' }}
SECRETS: ${{ secrets.production_project_secrets }}
uses: appleboy/[email protected]
with:
host: ${{ env.STAGING_SERVER_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.staging_ssh_key }}
envs: SECRETS
script: |
cd ~/repos/${{ github.event.repository.name }}
mkdir -p .secrets && cd "$_"
i=1
while secret=$(echo "$SECRETS" | cut -d "&" -f $i) ; [ -n "$secret" ] ;do
i=$((i+1))
key=$(echo "$secret" | cut -d "=" -f 1)
value=$(echo "$secret" | cut -d "=" -f 2)
echo "$value" > "$key".txt
break
done
- name: Build containers
uses: appleboy/[email protected]
with:
host: ${{ env.STAGING_SERVER_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.staging_ssh_key }}
command_timeout: ${{env.COMMAND_TIMEOUT}}
script: |
cd ~/repos/${{ github.event.repository.name }}
docker compose up -d --build
- name: Convert production subdomain to staging subdomain
id: convert-subdomain
run: |
staging_domain=$(echo "${{ inputs.full_app_url }}" | sed 's/rae/rae.amfws-staging/')
echo "staging_domain=$staging_domain" >> "$GITHUB_OUTPUT"
echo "Staging domain is: $staging_domain"
- name: Provision new subdomain
uses: appleboy/[email protected]
with:
host: ${{ env.STAGING_SERVER_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.staging_ssh_key }}
script: |
full_domain=${{ steps.convert-subdomain.outputs.staging_domain }}
if [ -f "/etc/nginx/sites-available/$full_domain" ]; then
existing_config_repo=$(grep -oP '(?<=Subdomain for repo: ).*' /etc/nginx/sites-available/$full_domain)
if [ "$existing_config_repo" != "${{ github.event.repository.name }}" ]; then
echo "A different repository ($existing_config_repo) uses this domain. Choose another domain or contact IWG."
exit 1
fi
fi
nginx_config="
# Below comment is used by the CI/CD pipeline, do not edit or remove
# Subdomain for repo: ${{ github.event.repository.name }}
server {
listen 443 ssl;
include snippets/self-signed.conf;
include snippets/ssl-params.conf;
server_name $full_domain;
location / {
proxy_set_header X-Forwarded-For \$remote_addr;
proxy_set_header Host \$http_host;
proxy_pass \"http://127.0.0.1:${{ inputs.app_port }}\";
}
}"
file_path="/etc/nginx/sites-available/$full_domain"
echo "$nginx_config" > "$file_path"
ln -sf "$file_path" "/etc/nginx/sites-enabled/"
sudo nginx -t
if [ $? -eq 0 ]; then
sudo nginx -s reload
echo "Success: nginx configuration reloaded"
else
echo "Error: nginx configuration test failed. Please contact IWG."
exit 1
fi
- name: Get build details URL
uses: actions/github-script@v7
continue-on-error: true
if: always()
id: get-job-url
with:
script: |
const { data: workflow_run } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: context.runId
});
html_url = workflow_run.jobs.find((job) => job.name === "${{env.STAGING_WORKFLOW_NAME}}").html_url
html_url += "?pr=${{github.event.pull_request.number}}"
console.log(`URL is ${html_url}`)
return html_url
result-encoding: string
- name: Compose ending message
id: compose-ending-message
if: always()
uses: actions/github-script@v7
with:
result-encoding: string
script: |
console.log(`Job status: ${{ job.status }}`)
const message = (`${{ job.status }}` === 'failure')
? `
**Build (#${{github.run_number}}) failed to deploy to staging** ❌
\- Please check the [build log](${{steps.get-job-url.outputs.result}}) for details.
**Note:** Once you correct the error, simply push the new commit to the same branch and it will automatically re-deploy to staging.
` : `
**New build (#${{github.run_number}}) deployed to staging** 🚧
\- Test it on the staging URL: [${{steps.convert-subdomain.outputs.staging_domain}}](http://${{steps.convert-subdomain.outputs.staging_domain}})
\- If you update the PR or create another one, a new build will be created, replacing this one
\- [View build log](${{steps.get-job-url.outputs.result}})
**Note:** If this PR is to main, only authorized users will be allowed to merge. Once merged to main, the build will be promoted to the production server. Ensure the staging build works correctly before merging.
`
return message;
- name: Comment on PR
if: always()
uses: actions/github-script@v7
with:
script: |
const message = `${{steps.compose-ending-message.outputs.result}}`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: message
});
# https://app.slack.com/block-kit-builder https://www.text-utils.com/json-formatter/
- name: Post update to Slack
if: always()
uses: slackapi/[email protected]
with:
channel-id: ${{env.SLACK_CHANNEL_ID}}
payload: >
{"blocks":[{"type":"section","text":{"type":"mrkdwn","text":"_Update in repository ${{ github.event.repository.name }}_"}},{"type":"divider"},{"type":"section","text":{"type":"mrkdwn","text":"*Staging or production:* Staging \n *Outcome:* ${{ job.status }}"}},{"type":"actions","elements":[{"type":"button","text":{"type":"plain_text","text":"View build details"},"value":"click_me","url":"${{steps.get-job-url.outputs.result}}"}]}]}
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_DEPLOYMENT_BOT_TOKEN }}
deploy-production:
name: "Production"
if: github.event_name == 'push' && github.ref_name == 'main'
runs-on: ubuntu-latest
steps:
- name: Convert production host nickname to actual hostname
id: convert-nickname
run: |
case "${{ inputs.target_production_server_nickname }}" in
"primary") production_host="212.71.250.173" ;;
"argand") production_host="argand" ;;
*) echo "Invalid nickname"; exit 1 ;;
esac
echo "production_host=$production_host" >> "$GITHUB_OUTPUT"
echo "Converted server nickname '${{ inputs.target_production_server_nickname }}' to hostname '$production_host'."
- name: Get PR number
uses: actions/github-script@v7
id: get-pr-number
with:
script: |
return (await
github.rest.repos.listPullRequestsAssociatedWithCommit({
commit_sha: context.sha,
owner: context.repo.owner,
repo: context.repo.repo,
})).data[0].number;
result-encoding: string
- name: Get build details URL
uses: actions/github-script@v7
continue-on-error: true
id: get-job-url
with:
script: |
const { data: workflow_run } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: context.runId
});
html_url = workflow_run.jobs.find((job) => job.name === "${{env.PRODUCTION_WORKFLOW_NAME}}").html_url
html_url += "?pr=${{steps.get-pr-number.outputs.result}}"
console.log(`URL is ${html_url}`)
return html_url
result-encoding: string
- name: Comment on PR (started build)
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
issue_number: ${{steps.get-pr-number.outputs.result}},
owner: context.repo.owner,
repo: context.repo.repo,
body: `
**In progress: build being promoted to production** 🏗️
\- [View build log](${{steps.get-job-url.outputs.result}})
`
})
# https://app.slack.com/block-kit-builder https://www.text-utils.com/json-formatter/
- name: Post update to Slack
uses: slackapi/[email protected]
with:
channel-id: ${{env.SLACK_CHANNEL_ID}}
payload: >
{"blocks":[{"type":"section","text":{"type":"mrkdwn","text":"_Update in repository ${{ github.event.repository.name }}_"}},{"type":"divider"},{"type":"section","text":{"type":"mrkdwn","text":"*In progress: build being promoted to production* 🏗️"}},{"type":"actions","elements":[{"type":"button","text":{"type":"plain_text","text":"View build details"},"value":"click_me","url":"${{steps.get-job-url.outputs.result}}"}]}]}
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_DEPLOYMENT_BOT_TOKEN }}
- name: Pull latest code
uses: appleboy/[email protected]
with:
host: ${{ env.ARGAND_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.argand_ssh_key }}
proxy_host: ${{ env.SSH_GATEWAY_HOST }}
proxy_username: ${{ env.DEPLOY_SSH_USER }}
proxy_key: ${{ secrets.sshgateway_ssh_key }}
script: |
cd ~/repos
if [ ! -d "${{ github.event.repository.name }}" ]; then
git clone [email protected]:arg-tech/${{ github.event.repository.name }}.git
echo "Repository cloned"
fi
cd "${{ github.event.repository.name }}"
git fetch
git checkout ${{ github.head_ref }}
git reset --hard HEAD
git merge '@{u}'
echo "Repository pulled and updated"
- name: Create project secrets
if: ${{ env.ARE_SECRETS_PRESENT == 'true' }}
env:
ARE_SECRETS_PRESENT: ${{ secrets.production_project_secrets != '' }}
SECRETS: ${{ secrets.production_project_secrets }}
uses: appleboy/[email protected]
with:
host: ${{ env.ARGAND_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.argand_ssh_key }}
proxy_host: ${{ env.SSH_GATEWAY_HOST }}
proxy_username: ${{ env.DEPLOY_SSH_USER }}
proxy_key: ${{ secrets.sshgateway_ssh_key }}
envs: SECRETS
script: |
cd ~/repos/${{ github.event.repository.name }}
mkdir -p .secrets && cd "$_"
i=1
while secret=$(echo "$SECRETS" | cut -d "&" -f $i) ; [ -n "$secret" ] ;do
i=$((i+1))
key=$(echo "$secret" | cut -d "=" -f 1)
value=$(echo "$secret" | cut -d "=" -f 2)
echo "$value" > "$key".txt
break
done
- name: Build containers
uses: appleboy/[email protected]
with:
host: ${{ env.ARGAND_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.argand_ssh_key }}
proxy_host: ${{ env.SSH_GATEWAY_HOST }}
proxy_username: ${{ env.DEPLOY_SSH_USER }}
proxy_key: ${{ secrets.sshgateway_ssh_key }}
command_timeout: ${{env.COMMAND_TIMEOUT}}
script: |
cd ~/repos/${{ github.event.repository.name }}
docker compose up -d --build
- name: Provision new subdomain
uses: appleboy/[email protected]
with:
host: ${{ env.ARGAND_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.argand_ssh_key }}
proxy_host: ${{ env.SSH_GATEWAY_HOST }}
proxy_username: ${{ env.DEPLOY_SSH_USER }}
proxy_key: ${{ secrets.sshgateway_ssh_key }}
script: |
full_domain=${{ inputs.full_app_url }}
if [ -f "/etc/nginx/sites-available/$full_domain" ]; then
existing_config_repo=$(grep -oP '(?<=Subdomain for repo: ).*' /etc/nginx/sites-available/$full_domain)
if [ "$existing_config_repo" != "${{ github.event.repository.name }}" ]; then
echo "A different repository ($existing_config_repo) uses this domain. Choose another domain or contact IWG."
exit 1
fi
fi
nginx_config="
# Below comment is used by the CI/CD pipeline, do not edit or remove
# Subdomain for repo: ${{ github.event.repository.name }}
server {
listen 443 ssl;
include snippets/self-signed.conf;
include snippets/ssl-params.conf;
server_name $full_domain;
location / {
proxy_set_header X-Forwarded-For \$remote_addr;
proxy_set_header Host \$http_host;
proxy_pass \"http://127.0.0.1:${{ inputs.app_port }}\";
auth_basic \"Restricted area\";
auth_basic_user_file /etc/apache2/.htpasswd;
proxy_set_header X-Auth-Username \$remote_user;
}
}"
file_path="/etc/nginx/sites-available/$full_domain"
echo "$nginx_config" > "$file_path"
ln -sf "$file_path" "/etc/nginx/sites-enabled/"
sudo nginx -t
if [ $? -eq 0 ]; then
sudo nginx -s reload
echo "Success: nginx configuration reloaded"
else
echo "Error: nginx configuration test failed. Please contact IWG immediately."
exit 1
fi
- name: Comment on PR (finished build)
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
issue_number: ${{steps.get-pr-number.outputs.result}},
owner: context.repo.owner,
repo: context.repo.repo,
body: `
**Build deployed to production** 🏠
\- Target server: ${{inputs.target_production_server_nickname}}
\- Your app's URL: [${{inputs.full_app_url}}](http://${{inputs.full_app_url}})
\- Tip: delete the source branch, and for future work create a fresh one from main to avoid merge conflicts
\- [View build log](${{steps.get-job-url.outputs.result}})
`
})
# https://app.slack.com/block-kit-builder https://www.text-utils.com/json-formatter/
- name: Post update to Slack
uses: slackapi/[email protected]
with:
channel-id: ${{env.SLACK_CHANNEL_ID}}
payload: >
{"blocks":[{"type":"section","text":{"type":"mrkdwn","text":"_Update in repository ${{ github.event.repository.name }}_"}},{"type":"divider"},{"type":"section","text":{"type":"mrkdwn","text":"*Build deployed to production* 🏠 \n - Target server: ${{inputs.target_production_server_nickname}} \n - Your app's URL: ${{inputs.full_app_url}} \n - Tip: delete the source branch, and for future work create a fresh one from main to avoid merge conflicts"}},{"type":"actions","elements":[{"type":"button","text":{"type":"plain_text","text":"View build details"},"value":"click_me","url":"${{steps.get-job-url.outputs.result}}"}]}]}
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_DEPLOYMENT_BOT_TOKEN }}
- name: Remove artifacts from staging server
# Logs utility should stay on the staging server
if: github.repository != 'arg-tech/dozzle-log-streamer' && github.repository != 'arg-tech/resource-lister'
uses: appleboy/[email protected]
with:
host: ${{ env.STAGING_SERVER_HOST }}
username: ${{ env.DEPLOY_SSH_USER }}
key: ${{ secrets.staging_ssh_key }}
script: |
cd ~/repos/${{ github.event.repository.name }}
docker compose down
staging_domain=$(echo "${{ inputs.full_app_url }}" | sed 's/rae/rae.amfws-staging/')
file_path="/etc/nginx/sites-available/$staging_domain"
rm $file_path
rm /etc/nginx/sites-enabled/$(basename "$file_path")
sudo nginx -t
if [ $? -eq 0 ]; then
sudo nginx -s reload
echo "Success: nginx configuration reloaded"
else
echo "Error: nginx configuration test on STAGING failed. Please contact IWG."
exit 1
fi