Skip to content

readme: outputs docs #5

readme: outputs docs

readme: outputs docs #5

Workflow file for this run

name: bake

Check failure on line 1 in .github/workflows/bake.yml

View workflow run for this annotation

GitHub Actions / .github/workflows/bake.yml

Invalid workflow file

(Line: 910, Col: 15): Unrecognized named-value: 'step'. Located at position 34 within expression: steps.manifest.outputs.digest || step.artifact.outputs.artifact-digest
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 }}
digest:
description: "Digest of the image pushed or artifact uploaded"
value: ${{ jobs.finalize.outputs.digest }}
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.32.1"
BUILDKIT_IMAGE: "moby/buildkit:v0.28.0"
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.81.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@04d248b84655b509d8c44dc1d6f990c879747487 # v4.0.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/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@04d248b84655b509d8c44dc1d6f990c879747487 # v4.0.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/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@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.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 || '' }}
digest: ${{ steps.manifest.outputs.digest || step.artifact.outputs.artifact-digest }}
output-type: ${{ inputs.output }}
signed: ${{ needs.prepare.outputs.sign }}
needs:
- prepare
- build
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: 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
id: 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 { ImageTools } = require('@docker/actions-toolkit/lib/buildx/imagetools');
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;
}
let digest;
for (const imageName of inpImageNames) {
const tags = [];
for (const tag of inpTagNames) {
tags.push(`${imageName}:${tag}`);
}
const result = await new ImageTools().create({
sources: digests,
tags: tags,
skipExec: !inpPush
});
if (inpPush) {
if (!result.digest) {
core.setFailed('Failed to create manifest, no digest returned');
return;
}
digest = result.digest;
core.info(`Manifest created: ${imageName}@${result.digest}`);
}
}
if (digest) {
core.setOutput('digest', digest);
}
-
name: Merge artifacts
id: artifact
if: ${{ inputs.output == 'local' && inputs.artifact-upload }}
uses: actions/upload-artifact/merge@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.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 }}
with:
script: |
const inpBuildOutputs = JSON.parse(core.getInput('build-outputs'));
const inpSigned = core.getBooleanInput('signed');
if (inpSigned) {
const verifyCommands = [];
for (const key of Object.keys(inpBuildOutputs)) {
const output = JSON.parse(inpBuildOutputs[key]);
if (output.verifyCommands) {
verifyCommands.push(output.verifyCommands);
}
}
core.setOutput('cosign-verify-commands', verifyCommands.join('\n'));
}