-
Notifications
You must be signed in to change notification settings - Fork 6
1015 lines (959 loc) · 44.1 KB
/
bake.yml
File metadata and controls
1015 lines (959 loc) · 44.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
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
name: bake
on:
workflow_call:
inputs:
runner:
type: string
description: "Ubuntu GitHub Hosted Runner to build on (one of auto, amd64, arm64). The auto runner selects the best-matching runner based on target platforms. You can set it to amd64 if your build doesn't require emulation (e.g. cross-compilation)"
required: false
default: 'auto'
distribute:
type: boolean
description: "Whether to distribute the build across multiple runners (one platform per runner)"
required: false
default: true
setup-qemu:
type: boolean
description: "Runs the setup-qemu-action step to install QEMU static binaries"
required: false
default: false
artifact-name:
type: string
description: "Name of the uploaded GitHub artifact (for local output)"
required: false
default: 'docker-github-builder-assets'
artifact-upload:
type: boolean
description: "Upload build output GitHub artifact (for local output)"
required: false
default: false
cache:
type: boolean
description: "Enable cache to GitHub Actions cache backend"
required: false
default: false
cache-scope:
type: string
description: "Which scope cache object belongs to if cache enabled (defaults to target name)"
required: false
cache-mode:
type: string
description: "Cache layers to export if cache enabled (min or max)"
required: false
default: 'min'
context:
type: string
description: "Context to build from in the Git working tree"
required: false
default: .
files:
type: string
description: "List of bake definition files"
required: false
output:
type: string
description: "Build output destination (one of image or local). Unlike the build-push-action, it only accepts image or local. The reusable workflow takes care of setting the outputs attribute"
required: true
push:
type: boolean
description: "Push image to the registry (for image output)"
required: false
default: false
sbom:
type: boolean
description: "Generate SBOM attestation for the build"
required: false
default: false
set:
type: string
description: "List of targets values to override (eg. targetpattern.key=value)"
required: false
sign:
type: string
description: "Sign attestation manifest for image output or artifacts for local output, can be one of auto, true or false. The auto mode will enable signing if push is enabled for pushing the image or if artifact-upload is enabled for uploading the local build output as GitHub Artifact"
required: false
default: auto
target:
type: string
description: "Bake target to build"
required: true
default: default
vars:
type: string
description: "Variables to set in the Bake definition as list of key-value pair"
required: false
# docker/metadata-action
set-meta-annotations:
type: boolean
description: "Append OCI Image Format Specification annotations generated by docker/metadata-action"
required: false
default: false
set-meta-labels:
type: boolean
description: "Append OCI Image Format Specification labels generated by docker/metadata-action"
required: false
default: false
meta-images:
type: string
description: "List of images to use as base name for tags (required for image output)"
required: false
meta-tags:
type: string
description: "List of tags as key-value pair attributes"
required: false
meta-flavor:
type: string
description: "Flavor defines a global behavior for meta-tags"
required: false
meta-labels:
type: string
description: "List of custom labels"
required: false
meta-annotations:
type: string
description: "List of custom annotations"
required: false
meta-bake-target:
type: string
description: "Bake target name for metadata (defaults to docker-metadata-action)"
required: false
secrets:
registry-auths:
description: "Raw authentication to registries, defined as YAML objects (for image output)"
required: false
github-token:
description: "GitHub Token used to authenticate against the repository for Git context"
required: false
outputs:
meta-json:
description: "Metadata JSON output (for image output)"
value: ${{ jobs.finalize.outputs.meta-json }}
cosign-version:
description: "Cosign version used for verification"
value: ${{ jobs.finalize.outputs.cosign-version }}
cosign-verify-commands:
description: "Cosign verify commands"
value: ${{ jobs.finalize.outputs.cosign-verify-commands }}
artifact-name:
description: "Name of the uploaded artifact (for local output)"
value: ${{ jobs.finalize.outputs.artifact-name }}
output-type:
description: "Build output type"
value: ${{ jobs.finalize.outputs.output-type }}
signed:
description: "Whether attestations manifests or artifacts were signed"
value: ${{ jobs.finalize.outputs.signed }}
env:
BUILDX_VERSION: "v0.31.1"
BUILDKIT_IMAGE: "moby/buildkit:v0.27.1"
SBOM_IMAGE: "docker/buildkit-syft-scanner:1.10.0"
BINFMT_IMAGE: "tonistiigi/binfmt:qemu-v10.2.1-65"
DOCKER_ACTIONS_TOOLKIT_MODULE: "@docker/actions-toolkit@0.76.0"
COSIGN_VERSION: "v3.0.2"
LOCAL_EXPORT_DIR: "/tmp/buildx-output"
MATRIX_SIZE_LIMIT: "20"
jobs:
prepare:
runs-on: ubuntu-24.04
outputs:
includes: ${{ steps.set.outputs.includes }}
sign: ${{ steps.set.outputs.sign }}
ghaCacheSign: ${{ steps.set.outputs.ghaCacheSign }}
steps:
-
name: Install @docker/actions-toolkit
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_DAT-MODULE: ${{ env.DOCKER_ACTIONS_TOOLKIT_MODULE }}
with:
script: |
await exec.exec('npm', ['install', '--prefer-offline', '--ignore-scripts', core.getInput('dat-module')]);
-
name: Install Cosign
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_COSIGN-VERSION: ${{ env.COSIGN_VERSION }}
with:
script: |
const { Cosign } = require('@docker/actions-toolkit/lib/cosign/cosign');
const { Install } = require('@docker/actions-toolkit/lib/cosign/install');
const inpCosignVersion = core.getInput('cosign-version');
const cosignInstall = new Install();
const cosignBinPath = await cosignInstall.download({
version: core.getInput('cosign-version'),
ghaNoCache: true,
skipState: true,
verifySignature: true
});
const cosignPath = await cosignInstall.install(cosignBinPath);
const cosign = new Cosign();
await cosign.printVersion();
-
name: Check dependencies signatures
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_IMAGES: |
${{ env.BUILDKIT_IMAGE }}
${{ env.SBOM_IMAGE }}
${{ env.BINFMT_IMAGE }}
with:
script: |
const { OCI } = require('@docker/actions-toolkit/lib/oci/oci');
const { Sigstore } = require('@docker/actions-toolkit/lib/sigstore/sigstore');
const sigstore = new Sigstore();
for (const image of core.getMultilineInput('images')) {
await core.group(`Verifying ${image}`, async () => {
try {
await sigstore.verifyImageAttestations(image, {
certificateIdentityRegexp: `^https://github.com/docker/github-builder(-experimental)?/.github/workflows/bake.yml.*$`,
platform: OCI.defaultPlatform()
});
} catch (error) {
core.setFailed(error);
return;
}
});
}
-
name: Expose GitHub Runtime
uses: crazy-max/ghaction-github-runtime@3cb05d89e1f492524af3d41a1c98c83bc3025124 # v3.1.0
-
name: Set outputs
id: set
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_SBOM-IMAGE: ${{ env.SBOM_IMAGE }}
INPUT_MATRIX-SIZE-LIMIT: ${{ env.MATRIX_SIZE_LIMIT }}
INPUT_ACTIONS-ID-TOKEN-SET: ${{ env.ACTIONS_ID_TOKEN_REQUEST_TOKEN != '' && env.ACTIONS_ID_TOKEN_REQUEST_URL != '' }}
INPUT_RUNNER: ${{ inputs.runner }}
INPUT_DISTRIBUTE: ${{ inputs.distribute }}
INPUT_ARTIFACT-UPLOAD: ${{ inputs.artifact-upload }}
INPUT_CONTEXT: ${{ inputs.context }}
INPUT_FILES: ${{ inputs.files }}
INPUT_OUTPUT: ${{ inputs.output }}
INPUT_PUSH: ${{ inputs.push }}
INPUT_SBOM: ${{ inputs.sbom }}
INPUT_SET: ${{ inputs.set }}
INPUT_SIGN: ${{ inputs.sign }}
INPUT_TARGET: ${{ inputs.target }}
INPUT_VARS: ${{ inputs.vars }}
INPUT_GITHUB-TOKEN: ${{ secrets.github-token || github.token }}
with:
script: |
const os = require('os');
const { Bake } = require('@docker/actions-toolkit/lib/buildx/bake');
const { GitHub } = require('@docker/actions-toolkit/lib/github');
const { Util } = require('@docker/actions-toolkit/lib/util');
const inpSbomImage = core.getInput('sbom-image');
const inpMatrixSizeLimit = parseInt(core.getInput('matrix-size-limit'), 10);
const inpActionsIdTokenSet = core.getBooleanInput('actions-id-token-set');
const inpRunner = core.getInput('runner');
const inpDistribute = core.getBooleanInput('distribute');
const inpArtifactUpload = core.getBooleanInput('artifact-upload');
const inpContext = core.getInput('context');
const inpVars = Util.getInputList('vars');
const inpFiles = Util.getInputList('files');
const inpOutput = core.getInput('output');
const inpPush = core.getBooleanInput('push');
const inpSbom = core.getBooleanInput('sbom');
const inpSet = Util.getInputList('set', {ignoreComma: true, quote: false});
const inpSign = core.getInput('sign');
const inpTarget = core.getInput('target');
const inpGitHubToken = core.getInput('github-token');
let runner = inpRunner;
if (inpRunner === 'amd64') {
runner = 'ubuntu-24.04';
} else if (inpRunner === 'arm64') {
runner = 'ubuntu-24.04-arm';
} else if (inpRunner !== 'auto') {
core.setFailed(`Invalid runner input: ${inpRunner}`);
return;
}
const sign =
inpSign === 'auto'
? (inpOutput === 'image' && inpPush) || (inpOutput === 'local' && inpArtifactUpload)
: inpSign === 'true';
if (inpOutput === 'local' && inpPush) {
core.warning(`push is ignored when output is local`);
} else if (inpOutput === 'image' && inpArtifactUpload) {
core.warning(`artifact-upload is ignored when output is image`);
}
if (inpOutput === 'image' && !inpPush && sign) {
core.setFailed(`signing attestation manifests requires push to be enabled`);
return;
}
const bakeSource = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}.git#${process.env.GITHUB_REF}:${inpContext}`;
await core.group(`Set bake source`, async () => {
core.info(bakeSource);
});
const envs = Object.assign({},
inpVars ? inpVars.reduce((acc, curr) => {
const idx = curr.indexOf('=');
if (idx !== -1) {
acc[curr.substring(0, idx)] = curr.substring(idx + 1);
}
return acc;
}, {}) : {},
{
BUILDKIT_MULTI_PLATFORM: '1',
BUILDX_BAKE_GIT_AUTH_TOKEN: inpGitHubToken
}
);
await core.group(`Set envs`, async () => {
core.info(JSON.stringify(envs, null, 2));
});
let def;
let target;
try {
await core.group(`Validating definition`, async () => {
const bake = new Bake();
def = await bake.getDefinition({
files: inpFiles,
overrides: inpSet,
sbom: inpSbom ? `generator=${inpSbomImage}` : 'false',
source: bakeSource,
targets: [inpTarget]
}, {
env: Object.keys(envs).length > 0 ? envs : undefined
});
if (!def) {
throw new Error('Bake definition not set');
}
const targetDefs = def.target || {};
const targets = Object.keys(targetDefs);
if (targets.length === 0) {
throw new Error('Bake definition does not contain any targets');
}
const parseContextTarget = value => {
if (typeof value !== 'string') {
return undefined;
}
const match = value.match(/^target:(.+)$/);
return match ? match[1] : undefined;
};
const resolveTarget = () => {
if (targetDefs[inpTarget]) {
return inpTarget;
}
throw new Error(`Unable to resolve ${inpTarget} target, found: ${targets.join(', ')}`);
};
target = resolveTarget();
const allowedTargets = new Set([target]);
const stack = [target];
while (stack.length > 0) {
const current = stack.pop();
const contexts = targetDefs[current]?.contexts || {};
for (const contextValue of Object.values(contexts)) {
const dependencyTarget = parseContextTarget(contextValue);
if (!dependencyTarget || allowedTargets.has(dependencyTarget)) {
continue;
}
if (!targetDefs[dependencyTarget]) {
throw new Error(`Target ${current} uses unknown named context target ${dependencyTarget}`);
}
allowedTargets.add(dependencyTarget);
stack.push(dependencyTarget);
}
}
const unsupportedTargets = targets.filter(name => !allowedTargets.has(name));
if (unsupportedTargets.length > 0) {
throw new Error(`Only one target can be built at once, found unsupported targets: ${unsupportedTargets.join(', ')}`);
}
});
} catch (error) {
core.setFailed(error);
return;
}
const platforms = def.target[target].platforms || [];
if (inpDistribute && platforms.length > inpMatrixSizeLimit) {
core.setFailed(`Platforms to build exceed matrix size limit of ${inpMatrixSizeLimit}`);
return;
}
const privateRepo = GitHub.context.payload.repository?.private ?? false;
await core.group(`Set privateRepo output`, async () => {
core.info(`privateRepo: ${privateRepo}`);
core.setOutput('privateRepo', privateRepo);
});
await core.group(`Set includes output`, async () => {
let includes = [];
if (!inpDistribute || platforms.length === 0) {
includes.push({
index: 0,
runner: runner === 'auto' ? 'ubuntu-24.04' : runner
});
} else {
platforms.forEach((platform, index) => {
includes.push({
index: index,
platform: platform,
runner: runner === 'auto' ? ((!privateRepo && platform.startsWith('linux/arm')) ? 'ubuntu-24.04-arm' : 'ubuntu-24.04') : runner
});
});
}
core.info(JSON.stringify(includes, null, 2));
core.setOutput('includes', JSON.stringify(includes));
});
await core.group(`Set sign output`, async () => {
core.info(`sign: ${sign}`);
core.setOutput('sign', sign);
});
await core.group(`Set ghaCacheSign output`, async () => {
const ghaCacheSign = inpActionsIdTokenSet ? 'true' : 'false';
core.info(`ghaCacheSign: ${ghaCacheSign}`);
core.setOutput('ghaCacheSign', ghaCacheSign);
});
build:
runs-on: ${{ matrix.runner }}
needs:
- prepare
strategy:
fail-fast: false
matrix:
include: ${{ fromJson(needs.prepare.outputs.includes) }}
outputs:
# needs predefined outputs as we can't use dynamic ones atm: https://github.com/actions/runner/pull/2477
# 20 is the maximum number of platforms supported by our matrix strategy
result_0: ${{ steps.result.outputs.result_0 }}
result_1: ${{ steps.result.outputs.result_1 }}
result_2: ${{ steps.result.outputs.result_2 }}
result_3: ${{ steps.result.outputs.result_3 }}
result_4: ${{ steps.result.outputs.result_4 }}
result_5: ${{ steps.result.outputs.result_5 }}
result_6: ${{ steps.result.outputs.result_6 }}
result_7: ${{ steps.result.outputs.result_7 }}
result_8: ${{ steps.result.outputs.result_8 }}
result_9: ${{ steps.result.outputs.result_9 }}
result_10: ${{ steps.result.outputs.result_10 }}
result_11: ${{ steps.result.outputs.result_11 }}
result_12: ${{ steps.result.outputs.result_12 }}
result_13: ${{ steps.result.outputs.result_13 }}
result_14: ${{ steps.result.outputs.result_14 }}
result_15: ${{ steps.result.outputs.result_15 }}
result_16: ${{ steps.result.outputs.result_16 }}
result_17: ${{ steps.result.outputs.result_17 }}
result_18: ${{ steps.result.outputs.result_18 }}
result_19: ${{ steps.result.outputs.result_19 }}
steps:
-
name: Install @docker/actions-toolkit
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_DAT-MODULE: ${{ env.DOCKER_ACTIONS_TOOLKIT_MODULE }}
with:
script: |
await exec.exec('npm', ['install', '--prefer-offline', '--ignore-scripts', core.getInput('dat-module')]);
-
name: Docker meta
id: meta
if: ${{ inputs.output == 'image' }}
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
with:
images: ${{ inputs.meta-images }}
tags: ${{ inputs.meta-tags }}
flavor: ${{ inputs.meta-flavor }}
labels: ${{ inputs.meta-labels }}
annotations: ${{ inputs.meta-annotations }}
bake-target: ${{ inputs.meta-bake-target }}
-
name: Set up QEMU
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
if: ${{ inputs.setup-qemu }}
with:
image: ${{ env.BINFMT_IMAGE }}
cache-image: false
-
name: Expose GitHub Runtime
uses: crazy-max/ghaction-github-runtime@3cb05d89e1f492524af3d41a1c98c83bc3025124 # v3.1.0
-
name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
with:
version: ${{ env.BUILDX_VERSION }}
cache-binary: false
buildkitd-flags: --debug
driver-opts: |
image=${{ env.BUILDKIT_IMAGE }}
env.ACTIONS_ID_TOKEN_REQUEST_TOKEN=${{ env.ACTIONS_ID_TOKEN_REQUEST_TOKEN }}
env.ACTIONS_ID_TOKEN_REQUEST_URL=${{ env.ACTIONS_ID_TOKEN_REQUEST_URL }}
buildkitd-config-inline: |
[cache]
[cache.gha]
[cache.gha.sign]
command = [${{ needs.prepare.outputs.ghaCacheSign == 'true' && '"ghacache-sign-script.sh"' || '' }}]
[cache.gha.verify]
required = ${{ needs.prepare.outputs.ghaCacheSign }}
[cache.gha.verify.policy]
timestampThreshold = 1
tlogThreshold = ${{ needs.prepare.outputs.privateRepo == 'true' && '0' || '1' }}
subjectAlternativeName = "https://github.com/docker/github-builder/.github/workflows/bake.yml*"
githubWorkflowRepository = "${{ github.repository }}"
issuer = "https://token.actions.githubusercontent.com"
runnerEnvironment = "github-hosted"
sourceRepositoryURI = "${{ github.server_url }}/${{ github.repository }}"
-
name: Install Cosign
if: ${{ needs.prepare.outputs.sign == 'true' || inputs.cache }}
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_COSIGN-VERSION: ${{ env.COSIGN_VERSION }}
INPUT_BUILDER-NAME: ${{ steps.buildx.outputs.name }}
INPUT_GHA-CACHE-SIGN-SCRIPT: |
#!/bin/sh
set -e
# Create temporary files
out_file=$(mktemp)
in_file=$(mktemp)
trap 'rm -f "$in_file" "$out_file"' EXIT
cat > "$in_file"
set -x
# Sign with cosign
cosign sign-blob \
--yes \
--oidc-provider github-actions \
--new-bundle-format \
--use-signing-config \
--bundle "$out_file" \
--tlog-upload=${{ needs.prepare.outputs.privateRepo == 'false' }} \
"$in_file"
# Output bundle to stdout
cat "$out_file"
with:
script: |
const fs = require('fs');
const os = require('os');
const path = require('path');
const { Buildx } = require('@docker/actions-toolkit/lib/buildx/buildx');
const { Cosign } = require('@docker/actions-toolkit/lib/cosign/cosign');
const { Install } = require('@docker/actions-toolkit/lib/cosign/install');
const inpCosignVersion = core.getInput('cosign-version');
const inpBuilderName = core.getInput('builder-name');
const inpGHACacheSignScript = core.getInput('gha-cache-sign-script');
const cosignInstall = new Install();
const cosignBinPath = await cosignInstall.download({
version: core.getInput('cosign-version'),
ghaNoCache: true,
skipState: true,
verifySignature: true
});
const cosignPath = await cosignInstall.install(cosignBinPath);
const cosign = new Cosign();
await cosign.printVersion();
const containerName = `${Buildx.containerNamePrefix}${inpBuilderName}0`;
const ghaCacheSignScriptPath = path.join(os.tmpdir(), `ghacache-sign-script.sh`);
core.info(`Writing GitHub Actions cache sign script to ${ghaCacheSignScriptPath}`);
await fs.writeFileSync(ghaCacheSignScriptPath, inpGHACacheSignScript, {mode: 0o700});
core.info(`Copying GitHub Actions cache sign script to BuildKit container ${containerName}`);
await exec.exec('docker', [
'cp',
ghaCacheSignScriptPath,
`${containerName}:/usr/bin/ghacache-sign-script.sh`
]);
core.info(`Copying cosign binary to BuildKit container ${containerName}`);
await exec.exec('docker', [
'cp',
cosignPath,
`${containerName}:/usr/bin/cosign`
]);
-
name: Prepare
id: prepare
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_PLATFORM: ${{ matrix.platform }}
INPUT_SBOM-IMAGE: ${{ env.SBOM_IMAGE }}
INPUT_LOCAL-EXPORT-DIR: ${{ env.LOCAL_EXPORT_DIR }}
INPUT_CACHE: ${{ inputs.cache }}
INPUT_CACHE-SCOPE: ${{ inputs.cache-scope }}
INPUT_CACHE-MODE: ${{ inputs.cache-mode }}
INPUT_CONTEXT: ${{ inputs.context }}
INPUT_FILES: ${{ inputs.files }}
INPUT_OUTPUT: ${{ inputs.output }}
INPUT_PUSH: ${{ inputs.push }}
INPUT_SBOM: ${{ inputs.sbom }}
INPUT_SET: ${{ inputs.set }}
INPUT_TARGET: ${{ inputs.target }}
INPUT_VARS: ${{ inputs.vars }}
INPUT_META-IMAGES: ${{ inputs.meta-images }}
INPUT_SET-META-ANNOTATIONS: ${{ inputs.set-meta-annotations }}
INPUT_SET-META-LABELS: ${{ inputs.set-meta-labels }}
INPUT_BAKE-FILE-TAGS: ${{ steps.meta.outputs.bake-file-tags }}
INPUT_BAKE-FILE-ANNOTATIONS: ${{ steps.meta.outputs.bake-file-annotations }}
INPUT_BAKE-FILE-LABELS: ${{ steps.meta.outputs.bake-file-labels }}
INPUT_GITHUB-TOKEN: ${{ secrets.github-token || github.token }}
with:
script: |
const os = require('os');
const { Build } = require('@docker/actions-toolkit/lib/buildx/build');
const { GitHub } = require('@docker/actions-toolkit/lib/github');
const { Util } = require('@docker/actions-toolkit/lib/util');
const inpPlatform = core.getInput('platform');
const platformPairSuffix = inpPlatform ? `-${inpPlatform.replace(/\//g, '-')}` : '';
core.setOutput('platform-pair-suffix', platformPairSuffix);
const inpSbomImage = core.getInput('sbom-image');
const inpLocalExportDir = core.getInput('local-export-dir');
const inpCache = core.getBooleanInput('cache');
const inpCacheScope = core.getInput('cache-scope');
const inpCacheMode = core.getInput('cache-mode');
const inpContext = core.getInput('context');
const inpFiles = Util.getInputList('files');
const inpOutput = core.getInput('output');
const inpPush = core.getBooleanInput('push');
const inpSbom = core.getBooleanInput('sbom');
const inpSet = Util.getInputList('set', {ignoreComma: true, quote: false});
const inpTarget = core.getInput('target');
const inpVars = Util.getInputList('vars');
const inpMetaImages = core.getMultilineInput('meta-images');
const inpSetMetaAnnotations = core.getBooleanInput('set-meta-annotations');
const inpSetMetaLabels = core.getBooleanInput('set-meta-labels');
const inpBakeFileTags = core.getInput('bake-file-tags');
const inpBakeFileAnnotations = core.getInput('bake-file-annotations');
const inpBakeFileLabels = core.getInput('bake-file-labels');
const inpGitHubToken = core.getInput('github-token');
const bakeSource = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}.git#${process.env.GITHUB_REF}:${inpContext}`;
await core.group(`Set source output`, async () => {
core.info(bakeSource);
core.setOutput('source', bakeSource);
});
await core.group(`Set target output`, async () => {
core.info(inpTarget);
core.setOutput('target', inpTarget);
});
const sbom = inpSbom ? `generator=${inpSbomImage}` : 'false';
await core.group(`Set sbom`, async () => {
core.info(sbom);
core.setOutput('sbom', sbom);
});
const envs = Object.assign({},
inpVars ? inpVars.reduce((acc, curr) => {
const idx = curr.indexOf('=');
if (idx !== -1) {
acc[curr.substring(0, idx)] = curr.substring(idx + 1);
}
return acc;
}, {}) : {},
{
BUILDKIT_MULTI_PLATFORM: '1',
BUILDX_BAKE_GIT_AUTH_TOKEN: inpGitHubToken
}
);
await core.group(`Set envs`, async () => {
core.info(JSON.stringify(envs, null, 2));
core.setOutput('envs', JSON.stringify(envs));
});
let bakeFiles = inpFiles;
await core.group(`Set bake files`, async () => {
if (bakeFiles.length === 0) {
bakeFiles = ['docker-bake.hcl'];
}
if (inpBakeFileTags) {
bakeFiles.push(`cwd://${inpBakeFileTags}`);
}
if (inpSetMetaAnnotations && inpBakeFileAnnotations) {
bakeFiles.push(`cwd://${inpBakeFileAnnotations}`);
}
if (inpSetMetaLabels && inpBakeFileLabels) {
bakeFiles.push(`cwd://${inpBakeFileLabels}`);
}
core.info(JSON.stringify(bakeFiles, null, 2));
core.setOutput('files', bakeFiles.join(os.EOL));
});
let outputOverride = '';
switch (inpOutput) {
case 'image':
if (inpMetaImages.length == 0) {
core.setFailed('meta-images is required when output is image');
return;
}
outputOverride = `*.output=type=image,"name=${inpMetaImages.join(',')}",oci-artifact=true,push-by-digest=true,name-canonical=true,push=${inpPush}`;
break;
case 'local':
outputOverride = `*.output=type=local,platform-split=true,dest=${inpLocalExportDir}`;
break;
default:
core.setFailed(`Invalid output: ${inpOutput}`);
return;
}
let bakeOverrides = [...inpSet, outputOverride];
await core.group(`Set bake overrides`, async () => {
bakeOverrides.push('*.tags=');
if (GitHub.context.payload.repository?.private ?? false) {
// if this is a private repository, we set min provenance mode
bakeOverrides.push(`*.attest=type=provenance,${Build.resolveProvenanceAttrs('mode=min,version=v1')}`);
} else {
// for a public repository, we set max provenance mode
bakeOverrides.push(`*.attest=type=provenance,${Build.resolveProvenanceAttrs('mode=max,version=v1')}`);
}
if (inpPlatform) {
bakeOverrides.push(`*.platform=${inpPlatform}`);
}
if (inpCache) {
bakeOverrides.push(`*.cache-from=type=gha,scope=${inpCacheScope || inpTarget}${platformPairSuffix}`);
bakeOverrides.push(`*.cache-to=type=gha,ignore-error=true,scope=${inpCacheScope || inpTarget}${platformPairSuffix},mode=${inpCacheMode}`);
}
core.info(JSON.stringify(bakeOverrides, null, 2));
core.setOutput('overrides', bakeOverrides.join(os.EOL));
});
-
name: Login to registry
if: ${{ inputs.push && inputs.output == 'image' }}
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
with:
registry-auth: ${{ secrets.registry-auths }}
-
name: Build
id: bake
uses: docker/bake-action@5be5f02ff8819ecd3092ea6b2e6261c31774f2b4 # v6.10.0
with:
source: ${{ steps.prepare.outputs.source }}
files: ${{ steps.prepare.outputs.files }}
targets: ${{ steps.prepare.outputs.target }}
sbom: ${{ steps.prepare.outputs.sbom }}
set: ${{ steps.prepare.outputs.overrides }}
env: ${{ fromJson(steps.prepare.outputs.envs) }}
-
name: Get image digest
id: get-image-digest
if: ${{ inputs.output == 'image' }}
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_TARGET: ${{ steps.prepare.outputs.target }}
INPUT_METADATA: ${{ steps.bake.outputs.metadata }}
with:
script: |
const inpTarget = core.getInput('target');
const inpMetadata = JSON.parse(core.getInput('metadata'));
const imageDigest = inpMetadata[inpTarget]['containerimage.digest'];
core.info(imageDigest);
core.setOutput('digest', imageDigest);
-
name: Login to registry for signing
if: ${{ needs.prepare.outputs.sign == 'true' && inputs.output == 'image' }}
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
with:
registry-auth: ${{ secrets.registry-auths }}
env:
DOCKER_LOGIN_SCOPE_DISABLED: true # make sure the scope feature is disabled to avoid interfering with cosign OIDC login
-
name: Signing attestation manifests
id: signing-attestation-manifests
if: ${{ needs.prepare.outputs.sign == 'true' && inputs.output == 'image' }}
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_IMAGE-NAMES: ${{ inputs.meta-images }}
INPUT_IMAGE-DIGEST: ${{ steps.get-image-digest.outputs.digest }}
with:
script: |
const { Sigstore } = require('@docker/actions-toolkit/lib/sigstore/sigstore');
const inpImageNames = core.getMultilineInput('image-names');
const inpImageDigest = core.getInput('image-digest');
// ECR registry regexes: https://github.com/docker/login-action/blob/28fdb31ff34708d19615a74d67103ddc2ea9725c/src/aws.ts#L8-L9
const ecrRegistryRegex = /^(([0-9]{12})\.(dkr\.ecr|dkr-ecr)\.(.+)\.(on\.aws|amazonaws\.com(.cn)?))(\/([^:]+)(:.+)?)?$/;
const ecrPublicRegistryRegex = /public\.ecr\.aws|ecr-public\.aws\.com/;
for (const imageName of inpImageNames) {
if (ecrRegistryRegex.test(imageName) || ecrPublicRegistryRegex.test(imageName)) {
core.info(`Detected ECR image name: ${imageName}, adding delay to mitigate eventual consistency issue`);
// FIXME: remove once https://github.com/docker/github-builder/issues/30 is resolved
await new Promise(resolve => setTimeout(resolve, 5000));
break;
}
}
const sigstore = new Sigstore();
const signResults = await sigstore.signAttestationManifests({
imageNames: inpImageNames,
imageDigest: inpImageDigest
});
const verifyResults = await sigstore.verifySignedManifests(signResults, {
certificateIdentityRegexp: `^https://github.com/docker/github-builder/.github/workflows/bake.yml.*$`,
retryOnManifestUnknown: true
});
await core.group(`Verify commands`, async () => {
const verifyCommands = [];
for (const [attestationRef, verifyResult] of Object.entries(verifyResults)) {
const cmd = `cosign ${verifyResult.cosignArgs.join(' ')} ${attestationRef}`;
core.info(cmd);
verifyCommands.push(cmd);
}
core.setOutput('verify-commands', verifyCommands.join('\n'));
});
-
name: Signing local artifacts
id: signing-local-artifacts
if: ${{ needs.prepare.outputs.sign == 'true' && inputs.output == 'local' }}
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_LOCAL-OUTPUT-DIR: ${{ env.LOCAL_EXPORT_DIR }}
with:
script: |
const path = require('path');
const { Sigstore } = require('@docker/actions-toolkit/lib/sigstore/sigstore');
const inplocalExportDir = core.getInput('local-output-dir');
const sigstore = new Sigstore();
const signResults = await sigstore.signProvenanceBlobs({
localExportDir: inplocalExportDir
});
const verifyResults = await sigstore.verifySignedArtifacts(signResults, {
certificateIdentityRegexp: `^https://github.com/docker/github-builder/.github/workflows/bake.yml.*$`
});
await core.group(`Verify commands`, async () => {
const verifyCommands = [];
for (const [artifactPath, verifyResult] of Object.entries(verifyResults)) {
const cmd = `cosign ${verifyResult.cosignArgs.join(' ')} --bundle ${path.relative(inplocalExportDir, verifyResult.bundlePath)} ${path.relative(inplocalExportDir, artifactPath)}`;
core.info(cmd);
verifyCommands.push(cmd);
}
core.setOutput('verify-commands', verifyCommands.join('\n'));
});
-
name: List local output
if: ${{ inputs.output == 'local' }}
run: |
tree -nh ${{ env.LOCAL_EXPORT_DIR }}
-
name: Upload artifact
if: ${{ inputs.output == 'local' && inputs.artifact-upload }}
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: ${{ inputs.artifact-name }}${{ steps.prepare.outputs.platform-pair-suffix || '0' }}
path: ${{ env.LOCAL_EXPORT_DIR }}
if-no-files-found: error
-
name: Set result output
id: result
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_INDEX: ${{ matrix.index }}
INPUT_VERIFY-COMMANDS: ${{ steps.signing-attestation-manifests.outputs.verify-commands || steps.signing-local-artifacts.outputs.verify-commands }}
INPUT_IMAGE-DIGEST: ${{ steps.get-image-digest.outputs.digest }}
INPUT_ARTIFACT-NAME: ${{ inputs.artifact-name }}${{ steps.prepare.outputs.platform-pair-suffix }}
INPUT_ARTIFACT-UPLOAD: ${{ inputs.artifact-upload }}
INPUT_SIGNED: ${{ needs.prepare.outputs.sign }}
with:
script: |
const inpIndex = core.getInput('index');
const inpVerifyCommands = core.getInput('verify-commands');
const inpImageDigest = core.getInput('image-digest');
const inpArtifactName = core.getInput('artifact-name');
const inpArtifactUpload = core.getBooleanInput('artifact-upload');
const inpSigned = core.getBooleanInput('signed');
const result = {
verifyCommands: inpVerifyCommands,
imageDigest: inpImageDigest,
artifactName: inpArtifactUpload ? inpArtifactName : '',
signed: inpSigned
}
core.info(JSON.stringify(result, null, 2));
core.setOutput(`result_${inpIndex}`, JSON.stringify(result));
finalize:
runs-on: ubuntu-24.04
outputs:
meta-json: ${{ steps.meta.outputs.json }}
cosign-version: ${{ env.COSIGN_VERSION }}
cosign-verify-commands: ${{ steps.set.outputs.cosign-verify-commands }}
artifact-name: ${{ inputs.artifact-upload && inputs.artifact-name || '' }}
output-type: ${{ inputs.output }}
signed: ${{ needs.prepare.outputs.sign }}
needs:
- prepare
- build
steps:
-
name: Docker meta
id: meta
if: ${{ inputs.output == 'image' }}
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
with:
images: ${{ inputs.meta-images }}
tags: ${{ inputs.meta-tags }}
flavor: ${{ inputs.meta-flavor }}
labels: ${{ inputs.meta-labels }}
annotations: ${{ inputs.meta-annotations }}
bake-target: ${{ inputs.meta-bake-target }}
-
name: Login to registry
if: ${{ inputs.push && inputs.output == 'image' }}
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
with:
registry-auth: ${{ secrets.registry-auths }}
env:
DOCKER_LOGIN_SCOPE_DISABLED: true # FIXME: scope feature is not yet supported by Buildx imagetools command
-
name: Set up Docker Buildx
if: ${{ inputs.push && inputs.output == 'image' }}
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
with:
version: ${{ env.BUILDX_VERSION }}
buildkitd-flags: --debug
driver-opts: image=${{ env.BUILDKIT_IMAGE }}
cache-binary: false
-
name: Create manifest
if: ${{ inputs.output == 'image' }}
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_PUSH: ${{ inputs.push }}
INPUT_IMAGE-NAMES: ${{ inputs.meta-images }}
INPUT_TAG-NAMES: ${{ steps.meta.outputs.tag-names }}
INPUT_BUILD-OUTPUTS: ${{ toJSON(needs.build.outputs) }}
with:
script: |
const inpPush = core.getBooleanInput('push');
const inpImageNames = core.getMultilineInput('image-names');
const inpTagNames = core.getMultilineInput('tag-names');
const inpBuildOutputs = JSON.parse(core.getInput('build-outputs'));
const digests = [];
for (const key of Object.keys(inpBuildOutputs)) {
const output = JSON.parse(inpBuildOutputs[key]);
if (output.imageDigest) {
digests.push(output.imageDigest);
}
}
if (digests.length === 0) {
core.setFailed('No image digests found from build outputs');
return;
}
for (const imageName of inpImageNames) {
let createArgs = ['buildx', 'imagetools', 'create'];
for (const tag of inpTagNames) {
createArgs.push('-t', `${imageName}:${tag}`);
}
for (const digest of digests) {
createArgs.push(digest);
}
if (inpPush) {
await exec.exec('docker', createArgs);
} else {
await core.group(`Generated imagetools create command for ${imageName}`, async () => {
core.info(`docker ${createArgs.join(' ')}`);
});
}
}
-
name: Merge artifacts
if: ${{ inputs.output == 'local' && inputs.artifact-upload }}
uses: actions/upload-artifact/merge@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: ${{ inputs.artifact-name }}
pattern: ${{ inputs.artifact-name }}*
delete-merged: true
-
name: Set outputs
id: set
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_BUILD-OUTPUTS: ${{ toJSON(needs.build.outputs) }}
INPUT_SIGNED: ${{ needs.prepare.outputs.sign }}