-
Notifications
You must be signed in to change notification settings - Fork 1
executable file
·512 lines (392 loc) · 18 KB
/
build.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: Build
on:
push:
paths:
- "services/**"
- ".github/workflows/build.yml"
branches:
- "**"
workflow_dispatch:
inputs:
components:
description: "The list of components to build"
required: true
type: string
build_configuration:
description: "Build Configuration"
required: true
default: "Release"
type: choice
options:
- "Release"
- "Debug"
create_release:
description: "Create Release"
required: true
default: true
type: boolean
create_image:
description: "Create Image"
required: true
default: true
type: boolean
version_suffix:
description: "Version Suffix"
required: false
type: string
permissions:
contents: write
deployments: write
jobs:
# Allows for a switch between push and workflow_dispatch
get-component-names:
name: Get Component Names
runs-on: ubuntu-latest
if: ${{ github.event_name != 'workflow_dispatch' && !contains(github.event.head_commit.message, '#!skip-build!#') }}
outputs:
components: ${{ steps.parse-commit-message.outputs.components }}
deployable-components: ${{ steps.parse-commit-message.outputs.deployable-components }}
steps:
- name: Parse commit message
id: parse-commit-message
uses: actions/github-script@v7
with:
script: |
// Head commit matches the following:
// #!components: component1,component2,component3
// #!deployable-components: component1,component2,component3
// component parts of commit messages do not close with !#, to find the end,
// just read the unti a newline character is found
const headCommitMessage = `${{ github.event.head_commit.message }}`;
const components = headCommitMessage.match(/#!components: ([a-zA-Z0-9_\-.,]+)/);
const deployableComponents = headCommitMessage.match(/#!deployable-components: ([a-zA-Z0-9_\-.,]+)/);
core.setOutput('components', components && components[1] || '');
core.setOutput('deployable-components', deployableComponents && deployableComponents[1] || '');
build:
name: Build Components
if: ${{ always() && !contains(github.event.head_commit.message, '#!skip-build!#') }}
needs: get-component-names
runs-on: ubuntu-latest
env:
BUILD_CONFIGURATION: ${{ github.event.inputs.build_configuration || (github.event_name == 'push' && github.ref == 'refs/heads/master' && 'Release') || 'Debug' }}
COMPONENT_NAMES: ${{ github.event.inputs.components || needs.get-component-names.outputs.components }}
VERSION_SUFFIX: ${{ github.event.inputs.version_suffix || '' }}
outputs:
components: ${{ steps.build-components.outputs.components }}
version: ${{ steps.version.outputs.version }}
docker-commands: ${{ steps.build-components.outputs.docker-commands }}
docker-files: ${{ steps.build-components.outputs.docker-files }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: recursive
- name: Setup .NET 8
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Download Needed Node Modules
run: npm install yaml
- name: Validate and Find components
uses: mfdlabs/component-finder-action@v10
id: find-component-directories
with:
components: ${{ env.COMPONENT_NAMES }}
component-search-directories: services
- name: Generate Version
id: version
run: |
DATE=$(date +"%Y.%m.%d-%H.%M.%S")
# Format: yyyy.mm.dd-hh.mm.ss-<short sha>
VERSION="$DATE-$(echo $GITHUB_SHA | cut -c1-7)"
# If we are building debug, append -dev
if [ "${{ env.BUILD_CONFIGURATION }}" == "Debug" ]; then
VERSION="$VERSION-dev"
fi
# If we have a version suffix, append it
if [ -n "${{ env.VERSION_SUFFIX }}" ]; then
VERSION="${VERSION}${{ env.VERSION_SUFFIX }}"
fi
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Build Components
uses: actions/github-script@v7
id: build-components
env:
VERSION: ${{ steps.version.outputs.version }}
NOMAD_VERSION: ${{ steps.version.outputs.version }}
with:
script: |
const fs = require('fs');
const yaml = require('yaml');
const path = require('path');
const child_process = require('child_process');
const deployDirectory = path.resolve(process.env.GITHUB_WORKSPACE, '.deploy');
// Ensure the deploy directory exists
if (!fs.existsSync(deployDirectory)) {
fs.mkdirSync(deployDirectory, { recursive: true });
}
let components = ${{ steps.find-component-directories.outputs.components }};
const outputComponents = Object.keys(components).map(component => component.split(':')[0]);
components = new Map(Object.entries(components));
core.setOutput('components', outputComponents.join(','));
let dockerCommands = {};
let dockerFiles = {};
function validateComponent(configFileName, config) {
if (!config.component) {
core.error('Component name is required');
return false;
}
if (!config.build) {
core.error('Build section is required');
return false;
}
if (!config.build.project_file) {
core.error('Build project file is required');
return false;
}
config.build.project_file = path.resolve(path.dirname(configFileName), config.build.project_file);
if (!fs.existsSync(config.build.project_file)) {
core.error(`Project file ${config.build.project_file} does not exist`);
return false;
}
if (!config.build.component_directory) {
config.build.component_directory = './.deploy';
}
config.build.component_directory = path.resolve(path.dirname(configFileName), config.build.component_directory, '${{ steps.version.outputs.version }}');
if (!config.build.docker) {
core.error('Docker section is required');
return false;
}
if (!config.build.docker.docker_file) {
config.build.docker.docker_file = 'Dockerfile';
}
config.build.docker.docker_file = path.resolve(path.dirname(configFileName), config.build.docker.docker_file);
if (!fs.existsSync(config.build.docker.docker_file)) {
core.error(`Docker file ${config.build.docker.docker_file} does not exist`);
return false;
}
if (!config.build.docker.image_name) {
core.error('Docker image name is required');
return false;
}
let dockerCommand = `docker build -t ${config.build.docker.image_name}:${{ steps.version.outputs.version }} -f %s %s`;
if (config.build.docker.build_args) {
for (const arg of config.build.docker.build_args) {
dockerCommand += ` --build-arg ${arg}`;
}
}
dockerCommands[`${config.component}@${config.build.docker.image_name}`] = dockerCommand;
dockerFiles[config.component] = fs.readFileSync(config.build.docker.docker_file, 'utf8');
return true;
}
for (const [component, configFileName] of components) {
const [name, version] = component.split(':');
const componentConfigData = fs.readFileSync(configFileName, 'utf8');
const replacedContents = componentConfigData.replace(
/\$\{{ env.([A-Za-z_]+) }}/g, // back slash needed here to escape from github action
(_, envVar) => {
const value = process.env[envVar]
if (!value) {
return 'undefined'
}
return value
},
)
const componentConfig = yaml.parse(replacedContents);
if (!validateComponent(configFileName, componentConfig)) {
core.setFailed(`Failed to validate component ${component}`);
return;
}
let dotnetCommand = `dotnet publish ${componentConfig.build.project_file} -c ${{ env.BUILD_CONFIGURATION }} -o ${componentConfig.build.component_directory}`;
if (componentConfig.build.additional_args) {
for (const arg of componentConfig.build.additional_args) {
dotnetCommand += ` ${arg}`;
}
}
console.log(dotnetCommand);
try {
child_process.execSync(dotnetCommand, { stdio: 'inherit' });
} catch (error) {
core.setFailed(`Failed to build component ${component}`);
return;
}
// Zip the component, and move it to the deploy directory
const zipCommand = `zip -r ${path.resolve(deployDirectory, `${componentConfig.component}.zip`)} .`;
console.log(zipCommand);
try {
child_process.execSync(zipCommand, { stdio: 'inherit', cwd: componentConfig.build.component_directory });
} catch (error) {
core.setFailed(`Failed to zip component ${component}`);
return;
}
const lsCommand = `ls -la ${deployDirectory}`
try {
child_process.execSync(lsCommand, { stdio: 'inherit' });
} catch (error) {
core.setFailed(`Failed to ls component ${component}`);
return;
}
}
core.setOutput('docker-files', dockerFiles);
core.setOutput('docker-commands', dockerCommands);
core.setOutput('deploy-directory', deployDirectory);
- name: Upload Artifacts
uses: actions/upload-artifact@v4
with:
name: components
path: .deploy/*.zip
if-no-files-found: error
include-hidden-files: true
# No need for checkout, downloads the component archives from the
# artifacts of the build job
upload-artifacts:
name: Upload Artifacts
if: ${{ always() && !contains(github.event.head_commit.message, '#!skip-release!#') && !contains(github.event.head_commit.message, '#!skip-image!#') && !contains(github.event.head_commit.message, '#!skip-build!#') && needs.build.result == 'success' }}
needs: build
runs-on: ubuntu-latest
outputs:
components: ${{ steps.build-docker-images.outputs.components }}
env:
BUILD_CONFIGURATION: ${{ github.event.inputs.build_configuration || (github.event_name == 'push' && github.ref == 'refs/heads/master' && 'Release') || 'Debug' }}
CREATE_RELEASE: ${{ github.event.inputs.create_release || !contains(github.event.head_commit.message, '#!skip-release!#') }}
COMPONENTS: ${{ needs.build.outputs.components }}
DOCKER_USERNAME: ${{ vars.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
CREATE_IMAGE: ${{ (github.event.inputs.create_image || !contains(github.event.head_commit.message, '#!skip-image!#')) && vars.DOCKER_USERNAME && secrets.DOCKER_PASSWORD }}
steps:
- name: Download Artifacts
uses: actions/download-artifact@v4
with:
name: components
path: ${{ github.workspace }}/.deploy
- name: Write GitHub Releases
if: ${{ env.CREATE_RELEASE }}
uses: actions/github-script@v7
with:
github-token: ${{ secrets.DEPLOYER_TOKEN }}
script: |
const fs = require('fs');
const path = require('path');
const components = "${{ env.COMPONENTS }}";
for (const component of components.split(',')) {
const data = fs.readFileSync(path.resolve('${{ github.workspace }}/.deploy', `${component}.zip`));
const response = await github.rest.repos.createRelease({
owner: '${{ github.repository_owner }}',
repo: '${{ github.repository }}'.split('/')[1],
tag_name: `${component}-${{ needs.build.outputs.version }}`,
name: `${component}-${{ needs.build.outputs.version }}`,
target_commitish: '${{ github.sha }}',
generate_release_notes: true,
prerelease: ${{ env.BUILD_CONFIGURATION == 'Debug' }}
});
await github.rest.repos.uploadReleaseAsset({
owner: '${{ github.repository_owner }}',
repo: '${{ github.repository }}'.split('/')[1],
release_id: response.data.id,
name: `${{ needs.build.outputs.version }}.zip`,
data: data,
});
}
- name: Unpack Artifacts
if: ${{ env.CREATE_IMAGE }}
run: |
for file in ${{ github.workspace }}/.deploy/*.zip; do
mkdir ${{ github.workspace }}/.deploy/$(basename $file .zip)
unzip -o $file -d ${{ github.workspace }}/.deploy/$(basename $file .zip)
done
- name: Write Dockerfiles
if: ${{ env.CREATE_IMAGE }}
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const dockerFiles = ${{ needs.build.outputs.docker-files }};
for (const [component, dockerFile] of Object.entries(dockerFiles)) {
fs.writeFileSync(`${component}.dockerfile`, dockerFile);
}
- name: Build Docker Images
if: ${{ env.CREATE_IMAGE }}
id: build-docker-images
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const path = require('path');
const util = require('util');
const child_process = require('child_process');
// Login to Docker
child_process.execSync(`echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ vars.DOCKER_USERNAME }} --password-stdin`, { stdio: 'inherit' });
const dockerCommands = ${{ needs.build.outputs.docker-commands }};
const components = '${{ env.COMPONENTS }}'.split(',').map(component => `${component}:${{ needs.build.outputs.version }}`);
for (const [componentAndImage, dockerCommand] of Object.entries(dockerCommands)) {
const [component, image] = componentAndImage.split('@');
const formattedCommand = util.format(dockerCommand, path.resolve('${{ github.workspace }}', `${component}.dockerfile`), path.resolve('${{ github.workspace }}', '.deploy', component));
try {
child_process.execSync(formattedCommand, { stdio: 'inherit' });
} catch (error) {
core.setFailed(`Failed to build docker image for ${component}`);
return;
}
if ("${{ github.ref }}" === "refs/heads/master") {
// Tag the image
try {
child_process.execSync(`docker tag ${image}:${{ needs.build.outputs.version }} ${image}:latest`, { stdio: 'inherit' });
} catch (error) {
core.setFailed(`Failed to tag docker image for ${component}`);
return;
}
}
// Push the image
try {
child_process.execSync(`docker push ${image}:${{ needs.build.outputs.version }}`, { stdio: 'inherit' });
} catch (error) {
core.setFailed(`Failed to push docker image for ${component}`);
return;
}
if ("${{ github.ref }}" === "refs/heads/master") {
// Push the image
try {
child_process.execSync(`docker push ${image}:latest`, { stdio: 'inherit' });
} catch (error) {
core.setFailed(`Failed to push docker image for ${component}`);
return;
}
}
}
core.setOutput('components', components);
deploy:
name: Deploy Components
if: ${{ github.event_name != 'workflow_dispatch' && !contains(github.event.head_commit.message, '#!skip-deploy!#') && github.ref == 'refs/heads/master' && needs.get-component-names.outputs.deployable-components != '' }}
needs:
- get-component-names
- upload-artifacts
runs-on: ubuntu-latest
env:
COMPONENTS: ${{ needs.upload-artifacts.outputs.components }}
DEPLOYABLE_COMPONENTS: ${{ needs.get-component-names.outputs.deployable-components }}
steps:
- name: Get Deployable Components
id: get-deployable-components
uses: actions/github-script@v7
with:
script: |
const components = ${{ env.COMPONENTS }};
const deployableComponents = '${{ env.DEPLOYABLE_COMPONENTS }}';
let deployableComponentsMap = '';
for (const component of components) {
const [name] = component.split(':');
if (deployableComponents.includes(name)) {
deployableComponentsMap += `${component},`;
}
}
const actionInputs = {
components: deployableComponentsMap.slice(0, -1),
nomad_environment: 'production'
};
core.setOutput('action-inputs', JSON.stringify(actionInputs));
- name: Dispatch Deployment
uses: benc-uk/workflow-dispatch@v1
with:
workflow: deploy.yml
inputs: ${{ steps.get-deployable-components.outputs.action-inputs }}
token: ${{ secrets.DEPLOYER_TOKEN }}