-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaction.yml
More file actions
452 lines (409 loc) · 18.6 KB
/
action.yml
File metadata and controls
452 lines (409 loc) · 18.6 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
---
name: "Docker - Build image"
description: |
Action to build and push a "raw" image with Docker for a specific platform.
This action uses the Docker Buildx plugin to build the image.
It supports caching.
It returns the image digest URI, tags, and annotations, but does not handle it itself.
author: hoverkraft
branding:
icon: package
color: blue
inputs:
oci-registry:
description: |
OCI registry configuration used to pull, push and cache images.
Accepts either a registry hostname string (default format) or a JSON object.
JSON example: `{"pull":"docker.io","pull:private":"ghcr.io","push":"ghcr.io"}`
JSON object keys:
- `pull`: registry used to pull public or default base images
- `pull:<name>`: additional pull registry
- `push`: registry used for published images
- `cache`: registry used when `cache-type` is `registry`
If no `pull` key is provided, the `push` registry is also used for pulls.
default: "ghcr.io"
required: true
oci-registry-username:
description: |
Username configuration used to log against OCI registries.
Accepts either a single username string (default format) or a JSON object using the same keys as `oci-registry`.
JSON example:
`{"pull:private":"$\{{ github.repository_owner }}","push":"$\{{ github.repository_owner }}"}`
See https://github.com/docker/login-action#usage.
default: ${{ github.repository_owner }}
required: true
oci-registry-password:
description: |
Password or personal access token configuration used to log against OCI registries.
Accepts either a single password/token string (default format) or a JSON object using the same keys as `oci-registry`.
JSON example: `{"pull:private":"$\{{ github.token }}","push":"$\{{ github.token }}"}`
Can be passed in using `secrets.GITHUB_TOKEN`.
See https://github.com/docker/login-action#usage.
default: ${{ github.token }}
required: true
repository:
description: |
Repository name.
Example: `my-org/my-repo`.
See [Docker get-image-metadata action](../get-image-metadata/README.md).
default: ${{ github.repository }}
required: false
image:
description: |
Additional image name.
Example: `application`.
See [Docker get-image-metadata action](../get-image-metadata/README.md).
required: false
tag:
description: "Force image tag to publish"
required: false
platform:
description: |
Platform to build for. Example: `linux/amd64`.
See https://github.com/docker/build-push-action#inputs.
required: true
context:
description: |
Build's context is the set of files located in the specified PATH or URL.
See https://github.com/docker/build-push-action#inputs.
default: "."
required: false
dockerfile:
description: |
Location of Dockerfile (defaults to Dockerfile).
See https://github.com/docker/build-push-action#inputs.
default: "Dockerfile"
required: false
build-args:
description: |
List of build-time variables.
See https://github.com/docker/build-push-action#inputs.
required: false
target:
description: |
Sets the target stage to build.
See https://github.com/docker/build-push-action#inputs.
required: false
secrets:
description: |
List of secrets to expose to the build.
See https://docs.docker.com/build/ci/github-actions/secrets/.
required: false
secret-envs:
description: |
List of secret environment variables to expose to the build (e.g., `key=envname, MY_SECRET=MY_ENV_VAR`).
See https://docs.docker.com/build/ci/github-actions/secrets/.
required: false
cache-type:
description: |
Cache type.
See https://docs.docker.com/build/cache/backends.
default: "gha"
required: false
buildkitd-config-inline:
description: |
Inline BuildKit daemon configuration.
See https://github.com/docker/setup-buildx-action#inputs.
Example for insecure registry:
```ini
[registry."my-registry.local:5000"]
http = true
insecure = true
```
required: false
multi-platform:
description: |
Whether this build participates in a multi-platform image publication.
When true, the image is pushed by digest only so manifests can be assembled later.
When false, the image is pushed with its tags directly.
default: false
required: false
outputs:
built-image:
description: |
Built image data.
Example:
```json
{
"name": "application",
"registry": "ghcr.io",
"repository": "my-org/my-repo/application",
"digest": "sha256:d31aa93410434ac9dcfc9179cac2cb1fd4d7c27f11527addc40299c7c675f49d",
"image": "ghcr.io/my-org/my-repo/application@sha256:d31aa93410434ac9dcfc9179cac2cb1fd4d7c27f11527addc40299c7c675f49d",
"tags": [
"pr-63-5222075",
"pr-63"
],
"annotations": {
"org.opencontainers.image.created": "2021-09-30T14:00:00Z",
"org.opencontainers.image.description": "Application image"
},
"platform": "linux/amd64",
"multi-platform": false
}
```
value: ${{ steps.get-built-image.outputs.built-image }}
runs:
using: "composite"
steps:
- uses: hoverkraft-tech/ci-github-common/actions/local-actions@a236f015b7dda4712d2ba4d327b8bf27be4c3d3a # 0.34.0
with:
source-path: ${{ github.action_path }}/../..
- id: slugify-platform
uses: hoverkraft-tech/ci-github-common/actions/slugify@a236f015b7dda4712d2ba4d327b8bf27be4c3d3a # 0.34.0
with:
value: ${{ inputs.platform }}
- id: docker-setup
uses: ./../self-actions/docker/setup
with:
oci-registry: ${{ inputs.oci-registry }}
oci-registry-username: ${{ inputs.oci-registry-username }}
oci-registry-password: ${{ inputs.oci-registry-password }}
buildkitd-config-inline: ${{ inputs.buildkitd-config-inline }}
buildx-cleanup: false
- name: Register Buildx cleanup
# FIXME: Workaround for GitHub Actions post-step ordering behavior with composite actions.
# The built-in Buildx cleanup can run before later post steps that still need the builder.
# See: https://github.com/actions/runner/issues/1657
uses: ./../self-actions/docker/cleanup-builder
with:
builder: ${{ steps.docker-setup.outputs.buildx-name }}
- id: metadata
uses: ./../self-actions/docker/get-image-metadata
with:
oci-registry: ${{ steps.docker-setup.outputs.push-registry }}
repository: ${{ inputs.repository }}
image: ${{ inputs.image }}
tag: ${{ inputs.tag }}
- id: get-docker-config
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
CACHE_REGISTRY: ${{ steps.docker-setup.outputs.cache-registry }}
CACHE_TYPE_INPUT: ${{ inputs.cache-type }}
CONTEXT_INPUT: ${{ inputs.context }}
DOCKERFILE_INPUT: ${{ inputs.dockerfile }}
METADATA_IMAGE: ${{ steps.metadata.outputs.image }}
MULTI_PLATFORM_INPUT: ${{ inputs.multi-platform }}
PLATFORM_INPUT: ${{ inputs.platform }}
SLUGIFIED_PLATFORM: ${{ steps.slugify-platform.outputs.result }}
TARGET_INPUT: ${{ inputs.target }}
with:
script: |
const { createHash } = require('crypto');
const fs = require('fs');
const path = require('path');
const workspace = process.env.GITHUB_WORKSPACE || process.cwd();
const rawContext = (process.env.CONTEXT_INPUT || '').trim();
const contextPath = rawContext.length > 0 ? rawContext : '.';
const rawDockerfile = (process.env.DOCKERFILE_INPUT || '').trim();
const dockerfileName = rawDockerfile.length > 0 ? rawDockerfile : 'Dockerfile';
const dockerfilePath = path.resolve(workspace, contextPath, dockerfileName);
if (!fs.existsSync(dockerfilePath) || !fs.statSync(dockerfilePath).isFile()) {
return core.setFailed(`Dockerfile not found at path: ${dockerfilePath}`);
}
const resolvedDockerfilePath = fs.realpathSync(dockerfilePath);
core.setOutput('dockerfile-path', resolvedDockerfilePath);
const cacheMountScope = JSON.stringify({
image: process.env.METADATA_IMAGE || '',
platform: process.env.PLATFORM_INPUT || '',
target: process.env.TARGET_INPUT || '',
});
const cacheMountScopeHash = createHash('sha256')
.update(cacheMountScope)
.digest('hex');
core.setOutput('cache-mount-scope', cacheMountScopeHash);
const slugifiedPlatform = process.env.SLUGIFIED_PLATFORM || '';
const tagSuffix = `-${slugifiedPlatform}`;
core.setOutput('cache-flavor', `suffix=${tagSuffix}`);
const cacheType = (process.env.CACHE_TYPE_INPUT || '').trim();
const metadataImage = process.env.METADATA_IMAGE || '';
const cacheRegistry = (process.env.CACHE_REGISTRY || '').trim();
if (cacheType === 'registry' && !cacheRegistry.length) {
return core.setFailed('Cache registry is required when cache-type is set to "registry".');
}
const metadataImageWithoutRegistry = metadataImage.replace(/^[^\/]+\//, '');
const cacheBaseImage = cacheRegistry.length ? `${cacheRegistry}/${metadataImageWithoutRegistry}` : metadataImage;
const cacheImage = cacheType === 'registry' ? `${cacheBaseImage}/cache` : metadataImage;
core.setOutput('cache-image', cacheImage);
try {
await exec.exec('command -v docker', { stdio: 'ignore' });
core.setOutput('docker-exists', 'true');
} catch (error) {
// docker not available on runner
}
const multiplatformInput = (process.env.MULTI_PLATFORM_INPUT || '').trim().toLowerCase();
const isMultiplatform = !(multiplatformInput.length === 0 || multiplatformInput === 'false');
if (isMultiplatform) {
core.debug('Multi-platform build is enabled.');
core.setOutput('multi-platform', true);
}
const platform = (process.env.PLATFORM_INPUT || '').trim();
if (platform.length === 0) {
return core.setFailed('Input "platform" is required.');
}
const [platformOs, ...platformArchParts] = platform.split('/');
const { stdout: runnerOsOutput } = await exec.getExecOutput('uname -s');
const runnerOs = runnerOsOutput.trim().toLowerCase();
core.debug(`Platform OS: ${platformOs}`);
core.debug(`Runner OS: ${runnerOs}`);
if (platformOs.toLowerCase() === runnerOs) {
const platformArch = platformArchParts.join('/');
const { stdout: runnerArchOutput } = await exec.getExecOutput('uname -m');
const runnerArch = runnerArchOutput.trim();
core.debug(`Platform arch: ${platformArch}`);
core.debug(`Runner arch: ${runnerArch}`);
let runnerArchNormalized = runnerArch;
switch (runnerArch) {
case 'x86_64':
runnerArchNormalized = 'amd64';
break;
case 'aarch64':
runnerArchNormalized = 'arm64';
break;
case 'armv7l':
runnerArchNormalized = 'arm/v7';
break;
default:
core.warning(`Unsupported architecture: ${runnerArchRaw}`);
break;
}
if (platformArch === runnerArchNormalized) {
core.setOutput('platform-exists', 'true');
}
}
- if: steps.get-docker-config.outputs.platform-exists != 'true'
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0
with:
platforms: ${{ inputs.platform }}
# Caching setup
- id: cache-arguments
uses: int128/docker-build-cache-config-action@4788c7e22b9923ca0e44bc7a29281b5beb545e5d # v1.49.0
with:
image: ${{ steps.get-docker-config.outputs.cache-image }}
flavor: ${{ steps.get-docker-config.outputs.cache-flavor }}
pull-request-cache: true
cache-type: ${{ inputs.cache-type }}
extra-cache-to: "image-manifest=true,oci-mediatypes=true"
- uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4
id: cache
with:
path: cache-mount
key: cache-mount-${{ hashFiles(steps.get-docker-config.outputs.dockerfile-path) }}-${{ steps.get-docker-config.outputs.cache-mount-scope }}
restore-keys: |
cache-mount-${{ hashFiles(steps.get-docker-config.outputs.dockerfile-path) }}-
- name: Restore Docker cache mounts
uses: reproducible-containers/buildkit-cache-dance@1b8ab18fbda5ad3646e3fcc9ed9dd41ce2f297b4 # v3.3.2
with:
builder: ${{ steps.docker-setup.outputs.buildx-name }}
cache-dir: cache-mount
dockerfile: ${{ steps.get-docker-config.outputs.dockerfile-path }}
skip-extraction: ${{ steps.cache.outputs.cache-hit }}
- id: build
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0
with:
context: ${{ inputs.context }}
build-args: ${{ inputs.build-args }}
target: ${{ inputs.target }}
file: ${{ steps.get-docker-config.outputs.dockerfile-path }}
secrets: ${{ inputs.secrets }}
secret-envs: ${{ inputs.secret-envs }}
platforms: ${{ inputs.platform }}
cache-from: ${{ steps.cache-arguments.outputs.cache-from }}
cache-to: ${{ steps.cache-arguments.outputs.cache-to }}
outputs: |
${{ steps.get-docker-config.outputs.multi-platform && 'type=image,push-by-digest=true,name-canonical=true,push=true' || 'type=image,push=true' }}
labels: ${{ steps.metadata.outputs.labels }}
annotations: ${{ steps.metadata.outputs.annotations }}
tags: ${{ steps.get-docker-config.outputs.multi-platform && steps.metadata.outputs.image || steps.metadata.outputs.tags }}
provenance: false # Disable provenance to avoid unknown/unknown arch
sbom: false # Disable sbom to avoid unknown/unknown arch
- id: get-built-image
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const builtMetadata = ${{ steps.build.outputs.metadata }};
if (typeof builtMetadata !== 'object') {
core.setFailed('Given "metadata" output is not a JSON object.');
return;
}
const name = `${{ inputs.image }}`;
const image = `${{ steps.metadata.outputs.image }}`;
const registryMatch = image.match(/^([^\/]+)\/.*/);
const registry = registryMatch ? registryMatch[1] : null;
const repositoryMatch = image.match(/^[^\/]+\/([^:]+)/);
const repository = repositoryMatch ? repositoryMatch[1] : null;
const tags = `${{ steps.metadata.outputs.tags }}`
.split("\n")
.map(tag => tag.replace(/[^\/]+\/[^:]+:(.+)/,'$1').trim())
.filter(tag => tag !== "");
let platform;
const buildxProvenance = builtMetadata?.["buildx.build.provenance"];
if (buildxProvenance !== undefined) {
platform = buildxProvenance.invocation?.environment?.platform;
if (platform === undefined) {
return core.setFailed('Given "metadata"."buildx.build.provenance"."invocation"."environment"."platform" output is undefined.');
}
if (typeof platform !== "string") {
return core.setFailed('Given "metadata"."buildx.build.provenance"."invocation"."environment"."platform" is not a string.');
}
platform = platform.trim();
if (platform === "") {
return core.setFailed('Given "metadata"."buildx.build.provenance"."invocation"."environment"."platform" is empty.');
}
} else {
const descriptor = builtMetadata?.["containerimage.descriptor"];
if (descriptor?.["platform"] === undefined) {
return core.setFailed('Given "metadata"."containerimage.descriptor"."platform" output is undefined.');
}
const platformData = descriptor["platform"];
if (typeof platformData !== 'object' || platformData.os === undefined || platformData.architecture === undefined) {
return core.setFailed('Given "metadata"."containerimage.descriptor"."platform" does not contain required "os" and "architecture" fields.');
}
platform = `${platformData.os}/${platformData.architecture}${platformData.variant ? `/${platformData.variant}` : ''}`;
}
if (builtMetadata?.["containerimage.digest"] === undefined) {
return core.setFailed('Given "metadata"."containerimage.digest" output is undefined.');
}
const digests = builtMetadata["containerimage.digest"]
.split(",")
.map(digest => {
const cleanedDigest = digest.trim();
return cleanedDigest !== "" ? cleanedDigest : null;
})
.filter(digest => digest !== null);
const uniqueDigests = [...new Set(digests)];
if (uniqueDigests.length === 0) {
return core.setFailed('No valid digests found in "containerimage.digest" output.');
}
if( uniqueDigests.length > 1 ) {
return core.setFailed(`Multiple digests found: ${uniqueDigests.join(", ")}.`);
}
const digest = uniqueDigests[0];
const imageWithDigest = `${image}@${digest}`;
const annotations = `${{ steps.metadata.outputs.annotations }}`
.split("\n")
.map(annotation => {
const cleanedAnnotation = annotation
.replace(/^[^:]+:/, "")
.trim();
return cleanedAnnotation !== "" ? cleanedAnnotation : null;
})
.filter(annotation => annotation !== null)
.reduce((annotations, annotation) => {
const [key, value] = annotation.split("=");
annotations[key] = value;
return annotations;
}, {})
const isMultiplatform = Boolean(`${{ steps.get-docker-config.outputs.multi-platform }}`);
const builtImage = {
name,
tags,
annotations,
registry,
repository,
image: imageWithDigest,
digest,
platform,
"multi-platform": isMultiplatform,
};
core.setOutput("built-image", JSON.stringify(builtImage));