-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaction.yml
More file actions
484 lines (411 loc) · 18.3 KB
/
Copy pathaction.yml
File metadata and controls
484 lines (411 loc) · 18.3 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
---
name: "Docker - Setup"
description: |
Shared action to configure Docker tooling and OCI registry authentication.
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"}`
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`.
required: false
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`.
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
```
built-images:
description: |
Optional built images payload used to resolve manifest publication registries.
When provided, registry authentication targets are inferred from the built image data.
required: false
setup-buildx:
description: |
Whether to install and configure Docker Buildx.
default: true
required: false
buildx-cleanup:
description: |
Whether the Buildx builder should be removed during post-job cleanup.
default: true
required: false
# FIXME: upgrade version when available (https://github.com/docker/actions-toolkit/blob/main/.github/docker-releases.json)
docker-version:
description: |
Docker version used when Docker must be installed by the action.
default: "29.5.2"
required: false
# FIXME: upgrade version when available (https://github.com/docker/buildx/releases)
buildx-version:
description: |
Buildx version used by docker/setup-buildx-action.
default: "v0.34.1"
required: false
# FIXME: upgrade version when available (https://hub.docker.com/r/moby/buildkit)
buildkit-image:
description: |
BuildKit image used by docker/setup-buildx-action.
default: "moby/buildkit:v0.30.0"
required: false
outputs:
push-registry:
description: "Registry used for published images/manifests."
value: ${{ steps.resolve-oci-registries.outputs.push-registry }}
cache-registry:
description: "Registry used for registry-backed build cache."
value: ${{ steps.resolve-oci-registries.outputs.cache-registry }}
pull-registries:
description: "JSON array of registries used to pull base images."
value: ${{ steps.resolve-oci-registries.outputs.pull-registries }}
buildx-name:
description: "Docker Buildx builder name."
value: ${{ steps.setup-buildx.outputs.name }}
runs:
using: "composite"
steps:
- id: resolve-oci-registries
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
BUILT_IMAGES_INPUT: ${{ inputs.built-images }}
REGISTRY_INPUT: ${{ inputs.oci-registry }}
REGISTRY_PASSWORD_INPUT: ${{ inputs.oci-registry-password }}
REGISTRY_USERNAME_INPUT: ${{ inputs.oci-registry-username }}
with:
script: |
function parseJsonObjectInput(inputName, rawValue) {
const value = `${rawValue}`.trim();
if (!value.length) {
return null;
}
if (!value.startsWith('{')) {
return value;
}
let parsedValue;
try {
parsedValue = JSON.parse(value);
} catch (error) {
throw new Error(`"${inputName}" input is not a valid JSON object: ${error}`);
}
if (parsedValue === null || Array.isArray(parsedValue) || typeof parsedValue !== 'object') {
throw new Error(`"${inputName}" input must be a string or a JSON object`);
}
return parsedValue;
}
function normalizeString(value, fieldName) {
if (typeof value !== 'string') {
throw new Error(`"${fieldName}" must be a string`);
}
const trimmedValue = value.trim();
if (!trimmedValue.length) {
throw new Error(`"${fieldName}" must not be empty`);
}
return trimmedValue;
}
function isPullRole(role) {
return role === 'pull' || role.startsWith('pull:');
}
function normalizeRoleMapInput(inputName, rawValue) {
const parsedValue = parseJsonObjectInput(inputName, rawValue);
if (parsedValue === null) {
return {};
}
if (typeof parsedValue === 'string') {
return { scalar: normalizeString(parsedValue, inputName) };
}
return Object.entries(parsedValue).reduce((roleMap, [key, value]) => {
if (key !== 'push' && key !== 'cache' && !isPullRole(key)) {
throw new Error(`"${inputName}.${key}" is not supported`);
}
roleMap[key] = normalizeString(value, `${inputName}.${key}`);
return roleMap;
}, {});
}
function resolveCredentialByRole(credentialMap, role, registry, pushRegistry) {
const defaultCredential = credentialMap.scalar ?? '';
if (role === 'push') {
return credentialMap.push ?? defaultCredential;
}
if (role === 'cache') {
return credentialMap.cache ?? credentialMap.push ?? defaultCredential;
}
if (!isPullRole(role)) {
return defaultCredential;
}
if (credentialMap[role] !== undefined) {
return credentialMap[role];
}
if (credentialMap.pull !== undefined) {
return credentialMap.pull;
}
if (registry === pushRegistry && credentialMap.push !== undefined) {
return credentialMap.push;
}
return defaultCredential;
}
function resolvePushCredential(credentialMap) {
return credentialMap.push ?? credentialMap.scalar ?? '';
}
function extractRegistryFromBuiltImage(builtImage) {
if (builtImage?.registry) {
return normalizeString(
builtImage.registry,
`built-images.${builtImage.name || 'unknown'}.registry`,
);
}
const imageReference = builtImage?.images?.[0];
if (typeof imageReference === 'string') {
const match = imageReference.trim().match(/^([^\/]+)\//);
if (match) {
return match[1];
}
}
return '';
}
function createRegistryAuthList(registryLogins) {
return registryLogins.reduce((registryAuthList, registryLogin) => {
const { registry, username, password, required } = registryLogin;
if ((username && !password) || (!username && password)) {
throw new Error(`Credentials for registry "${registry}" must define both username and password`);
}
if (!username && !password) {
if (required) {
throw new Error(`Credentials for registry "${registry}" are required`);
}
core.info(`Skipping Docker login for optional registry "${registry}" because no credentials were provided.`);
return registryAuthList;
}
registryAuthList.push({
registry,
username,
password,
});
return registryAuthList;
}, []);
}
function toRegistryAuthYaml(registryAuthList) {
return registryAuthList
.map(registryAuth => {
const lines = [
`- registry: ${JSON.stringify(registryAuth.registry)}`,
` username: ${JSON.stringify(registryAuth.username)}`,
` password: ${JSON.stringify(registryAuth.password)}`,
];
return lines.join('\n');
})
.join('\n');
}
function setOutputs({ pushRegistry = '', cacheRegistry = '', pullRegistries = [], registryAuth = [] }) {
core.setOutput('push-registry', pushRegistry);
core.setOutput('cache-registry', cacheRegistry);
core.setOutput('pull-registries', JSON.stringify(pullRegistries));
core.setOutput('registry-auth', toRegistryAuthYaml(registryAuth));
core.setOutput('has-registry-auth', registryAuth.length ? 'true' : 'false');
}
const registryInputName = ['oci', 'registry'].join('-');
const registryUsernameInputName = [registryInputName, 'username'].join('-');
const registryPasswordInputName = [registryInputName, 'password'].join('-');
const builtImagesInput = `${process.env.BUILT_IMAGES_INPUT || ''}`.trim();
if (builtImagesInput.length) {
let builtImages;
try {
builtImages = JSON.parse(builtImagesInput);
} catch (error) {
throw new Error(`"built-images" input is not a valid JSON: ${error}`);
}
const registries = [
...new Set(
Object.values(builtImages)
.map(extractRegistryFromBuiltImage)
.filter(Boolean),
),
];
if (!registries.length) {
const registryInput = normalizeRoleMapInput(registryInputName, `${process.env.REGISTRY_INPUT || ''}`);
if (registryInput.scalar) {
registries.push(registryInput.scalar);
} else {
const [, firstPullRegistryValue] = Object.entries(registryInput).find(([key]) => isPullRole(key)) ?? [];
const pushRegistry = registryInput.push ?? registryInput.cache ?? firstPullRegistryValue ?? '';
if (!pushRegistry.length) {
throw new Error('Unable to resolve any OCI registry to authenticate against');
}
registries.push(pushRegistry);
}
}
const usernameByRole = normalizeRoleMapInput(registryUsernameInputName, `${process.env.REGISTRY_USERNAME_INPUT || ''}`);
const passwordByRole = normalizeRoleMapInput(registryPasswordInputName, `${process.env.REGISTRY_PASSWORD_INPUT || ''}`);
const username = resolvePushCredential(usernameByRole);
const password = resolvePushCredential(passwordByRole);
const registryAuth = createRegistryAuthList(
registries.map(registry => ({
registry,
username,
password,
required: true,
})),
);
setOutputs({
pushRegistry: registries[0] ?? '',
cacheRegistry: registries[0] ?? '',
registryAuth,
});
return;
}
const registryInput = normalizeRoleMapInput(registryInputName, `${process.env.REGISTRY_INPUT || ''}`);
let pushRegistry = '';
let cacheRegistry = '';
let hasExplicitCacheRegistry = false;
let pullRegistryEntries = [];
let pullRegistries = [];
if (registryInput.scalar) {
pushRegistry = registryInput.scalar;
cacheRegistry = pushRegistry;
pullRegistries = [pushRegistry];
} else {
pushRegistry = registryInput.push ?? '';
hasExplicitCacheRegistry = typeof registryInput.cache === 'string';
cacheRegistry = registryInput.cache ?? pushRegistry;
pullRegistryEntries = Object.entries(registryInput)
.filter(([key]) => isPullRole(key))
.map(([role, registry]) => ({ role, registry }));
if (!pushRegistry.length) {
throw new Error(`"oci-registry.push" is required when "oci-registry" uses the JSON object format`);
}
if (!pullRegistryEntries.length) {
pullRegistryEntries = [{ role: 'pull', registry: pushRegistry }];
}
pullRegistries = pullRegistryEntries.map(({ registry }) => registry);
}
const registryEntries = [
{ role: 'push', registry: pushRegistry, required: true },
...pullRegistryEntries.map(pullRegistryEntry => ({ ...pullRegistryEntry, required: false })),
];
if (hasExplicitCacheRegistry) {
registryEntries.push({ role: 'cache', registry: cacheRegistry, required: true });
}
const usernameByRole = normalizeRoleMapInput(registryUsernameInputName, `${process.env.REGISTRY_USERNAME_INPUT || ''}`);
const passwordByRole = normalizeRoleMapInput(registryPasswordInputName, `${process.env.REGISTRY_PASSWORD_INPUT || ''}`);
const registryLoginsByRegistry = new Map();
for (const registryEntry of registryEntries) {
const { role, registry, required } = registryEntry;
const username = resolveCredentialByRole(usernameByRole, role, registry, pushRegistry);
const password = resolveCredentialByRole(passwordByRole, role, registry, pushRegistry);
const existingRegistryLogin = registryLoginsByRegistry.get(registry);
if (existingRegistryLogin) {
const hasDifferentUsername = existingRegistryLogin.username && username && existingRegistryLogin.username !== username;
const hasDifferentPassword = existingRegistryLogin.password && password && existingRegistryLogin.password !== password;
if (hasDifferentUsername || hasDifferentPassword) {
throw new Error(`Conflicting credentials configured for registry "${registry}"`);
}
if (!existingRegistryLogin.username && username) {
existingRegistryLogin.username = username;
}
if (!existingRegistryLogin.password && password) {
existingRegistryLogin.password = password;
}
existingRegistryLogin.required ||= required;
continue;
}
registryLoginsByRegistry.set(registry, {
registry,
username,
password,
required,
});
}
const registryAuth = createRegistryAuthList([...registryLoginsByRegistry.values()]);
setOutputs({
pushRegistry,
cacheRegistry,
pullRegistries,
registryAuth,
});
- id: detect-docker
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
EXPECTED_DOCKER_VERSION: ${{ inputs.docker-version }}
with:
script: |
const dockerPath = await io.which('docker', false);
if (!dockerPath) {
core.setOutput('docker-install-version', process.env.EXPECTED_DOCKER_VERSION);
return;
}
try {
const { stdout } = await exec.getExecOutput('docker', ['version', '--format', '{{.Server.Version}}']);
const dockerVersion = stdout.trim();
// Check if the detected Docker version is the same as the expected version.
if (dockerVersion !== process.env.EXPECTED_DOCKER_VERSION) {
core.setOutput('docker-install-version', process.env.EXPECTED_DOCKER_VERSION);
}
} catch (error) {
core.warning(`Failed to detect Docker version, defaulting to expected version: ${error}`);
core.setOutput('docker-install-version', process.env.EXPECTED_DOCKER_VERSION);
};
- if: steps.detect-docker.outputs.docker-install-version
uses: docker/setup-docker-action@0234bb73ccb40f0c430b795634f9247e2b5c2d23 # v5.2.0
with:
version: type=archive,channel=stable,version=${{ steps.detect-docker.outputs.docker-install-version }}
- if: inputs.setup-buildx != 'false'
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
BUILDKIT_IMAGE_INPUT: ${{ inputs.buildkit-image }}
with:
script: |
const buildkitImage = `${process.env.BUILDKIT_IMAGE_INPUT || ''}`.trim();
if (!buildkitImage.length) {
throw new Error('"buildkit-image" input must not be empty');
}
const maxAttempts = 5;
let delaySeconds = 5;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
const result = await exec.getExecOutput('docker', ['pull', buildkitImage], {
ignoreReturnCode: true,
silent: false,
});
if (result.exitCode === 0) {
core.info(`BuildKit image ${buildkitImage} pulled successfully`);
return;
}
if (attempt >= maxAttempts) {
throw new Error(`Failed to pull BuildKit image ${buildkitImage} after ${maxAttempts} attempts`);
}
core.warning(
`BuildKit image pull attempt ${attempt}/${maxAttempts} failed (exit code: ${result.exitCode}). Retrying in ${delaySeconds}s...`,
);
await new Promise(resolve => setTimeout(resolve, delaySeconds * 1000));
delaySeconds *= 2;
}
- if: inputs.setup-buildx != 'false'
uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
id: setup-buildx
with:
version: ${{ inputs.buildx-version }}
driver-opts: |
image=${{ inputs.buildkit-image }}
buildkitd-config-inline: ${{ inputs.buildkitd-config-inline }}
cleanup: ${{ inputs.buildx-cleanup }}
- if: steps.resolve-oci-registries.outputs.has-registry-auth == 'true'
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
with:
registry-auth: ${{ steps.resolve-oci-registries.outputs.registry-auth }}