diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml new file mode 100644 index 0000000..58d36f2 --- /dev/null +++ b/.github/workflows/pull-request.yml @@ -0,0 +1,81 @@ +name: Build +on: + pull_request: + branches: [main] +concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-pull-request + cancel-in-progress: true +jobs: + run-action: + name: ${{ matrix.name }} + runs-on: ubuntu-latest + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - name: run-action + buildkit-endpoint: '' + buildkit-registry: '' + - name: run-action-buildkit + buildkit-endpoint: tcp://localhost:1234 + buildkit-registry: localhost:5000 + env: + BUILDKIT_ENDPOINT: ${{ matrix.buildkit-endpoint }} + BUILDKIT_REGISTRY: ${{ matrix.buildkit-registry }} + steps: + - uses: actions/checkout@v7 + - name: Start a registry + run: docker run --detach --name registry --publish 5000:5000 registry:3 + - name: Start a shared BuildKit + if: matrix.buildkit-endpoint != '' + run: | + docker run --detach --name buildkitd --privileged --network host moby/buildkit:buildx-stable-1 --addr tcp://0.0.0.0:1234 + until docker exec buildkitd buildctl --addr tcp://localhost:1234 debug workers >/dev/null 2>&1; do sleep 1; done + - name: Build the build stage with a local tag + uses: ./ + with: + image: test + context: ./tests/ + target: build + tag: test-build + build-args: | + MESSAGE=from-args + driver-opts: network=host + - name: Check the tagged image + run: test "$(docker run --rm test-build cat /message)" = from-args + - name: Check the full image builds + uses: ./ + with: + image: test-min + context: ./tests/ + build-args: | + MESSAGE=from-args + cache-mode: min + - name: Push the full image + id: push + uses: ./ + with: + image: test + context: ./tests/ + file: ./tests/Dockerfile + build-args: | + MESSAGE=from-args + push: localhost:5000/pushed:latest + - name: Check the pushed image + env: + IMAGE: localhost:5000/pushed@${{ steps.push.outputs.digest }} + run: | + docker pull --quiet "$IMAGE" + test "$(docker run --rm "$IMAGE" cat /message)" = "$(printf 'from-args\nfinal')" + - name: Skip when the checks already passed + uses: ./ + env: + CHECKS_ALREADY_PASSED: 'true' + with: + image: test + context: ./tests/ + tag: test-skipped + - name: Check nothing was built + run: '! docker image inspect test-skipped >/dev/null 2>&1' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..f0c43df --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,55 @@ +name: Release +on: + workflow_dispatch: +concurrency: + group: release +jobs: + create-release: + runs-on: ubuntu-latest + # NOTE(krishan711): the release environment only allows main and holds the deploy key, which is the only thing allowed past the tag ruleset + environment: release + permissions: + contents: write + steps: + - name: Check out the repo + uses: actions/checkout@v7 + with: + ssh-key: ${{ secrets.RELEASE_DEPLOY_KEY }} + - name: Push the version tag + id: version + run: | + version="v$(jq -r .version package.json)" + if [[ ! "$version" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then + echo "::error::package.json version $version is not semver" + exit 1 + fi + existingSha="$(git ls-remote origin "refs/tags/$version" | cut -f1)" + if [[ -n "$existingSha" && "$existingSha" != "$GITHUB_SHA" ]]; then + echo "::error::$version already exists on $existingSha, bump the version in package.json" + exit 1 + fi + if [[ -z "$existingSha" ]]; then + git tag "$version" + git push origin "refs/tags/$version" + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + - name: Create the release + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.version.outputs.version }} + run: | + if gh release view "$VERSION" >/dev/null 2>&1; then + echo "$VERSION is already released" + elif [[ "$VERSION" == *-* ]]; then + gh release create "$VERSION" --verify-tag --title "Release $VERSION" --generate-notes --prerelease + else + gh release create "$VERSION" --verify-tag --title "Release $VERSION" --generate-notes + fi + - name: Move the major version tag + if: ${{ !contains(steps.version.outputs.version, '-') }} + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + majorTag="${VERSION%%.*}" + git tag --force "$majorTag" + git push --force origin "refs/tags/$majorTag" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0e808ff --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +# Mac +*.DS_Store + +# IDEs +.idea/ +.vscode/ +*.swp +*.log + +# Protobufs +*_pb2.* + +# Testing +coverage +.coverage +tests.xml +lint.xml +.noseids +nosetests.xml +eslint.xml +jest.xml +local_testing* + +# Generated +generated/ +dist/ +build/ +tmp/ + +# Python +__pycache__/ +eggs/ +dist/ +build/ +*.egg-info/ +.env* +.mypy_cache + +# JS +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +*.d.ts diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6ea90df --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Kiba Labs Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f56c56a --- /dev/null +++ b/README.md @@ -0,0 +1,103 @@ +# GitHub Action - Build Image + +Build a docker image in one step: with a shared BuildKit when the runner has one, or with the GitHub Actions cache otherwise. + +The same workflow runs fast on self-hosted runners that share a BuildKit (and its cache), and still caches its layers when it falls back to GitHub's runners. It sets up Buildx, builds, and then either only checks the image builds, makes it available to the local docker daemon, or pushes it. + +## Example + +```yaml +jobs: + app-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Build testable image + uses: kibalabs/github-action-build-image@v1 + with: + image: app + context: ./app/ + target: build + tag: app-build + - name: Run tests + run: docker run --rm app-build make test + - name: Check the full image builds + uses: kibalabs/github-action-build-image@v1 + with: + image: app + context: ./app/ + app-deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Build and push image + uses: kibalabs/github-action-build-image@v1 + with: + image: app + context: ./app/ + push: ghcr.io/${{ github.repository }}-app:latest +``` + +## What it builds + +Set at most one of `tag` and `push`: + +- Neither: the image is only built, to check that it builds and to fill the cache. +- `tag`: the image is available to the local docker daemon under that tag, e.g. to run checks in it. +- `push`: the image is pushed to those tags. Log in to the registry first. + +## Where it builds + +The runner decides, through environment variables, so the same workflow works on any runner: + +- `BUILDKIT_ENDPOINT` set (e.g. `tcp://buildkit:1234`): builds on that BuildKit with the `remote` driver, which keeps its own cache. Images built with `tag` are pushed uncompressed to `BUILDKIT_REGISTRY` (e.g. `buildkit:5000`), a registry the BuildKit and the runner's docker daemon can both reach, and pulled from there instead of being loaded. +- `BUILDKIT_ENDPOINT` not set (e.g. on GitHub's runners): builds in a `docker-container` builder with the GitHub Actions cache (`type=gha`, `cache-mode` defaults to `max`) scoped to `image`. Pass `driver-opts: network=host` if the build pushes to a registry on the runner's `localhost`, e.g. a service container. + +Set them in the runner's environment (e.g. its `.env` file, or the runner container's environment), not in workflows, so jobs that fall back to GitHub's runners don't get them. + +Every build in a job reuses the builder of the first one, so a later build starts with the layers of earlier ones. + +### Choosing `image` + +`image` is the cache scope, so builds that share it share their cache. A GitHub Actions cache scope only keeps what the last build wrote to it: + +- Use the same `image` for builds of the same Dockerfile and build args, e.g. a check build of the `build` target and the deploy build of the full image. With the default `cache-mode: max`, the full build includes the `build` stage, so what it writes covers both, and deploys on `main` fill the cache that pull requests read. +- Use a different `image` when the Dockerfile or build args change, e.g. a worker built from `worker.Dockerfile` in the same context, or the same app built with different build args. Otherwise each build replaces the other's cache. + +GitHub keeps up to 10 GB of cache per repository and evicts the least recently used entries beyond that. If several large images keep evicting each other, use `cache-mode: min`, which only caches the layers of the final image. A full build with `min` then no longer writes the layers of its earlier stages, so give builds of different targets their own `image`. + +## Inputs + +| Input | Default | Description | +| --- | --- | --- | +| `image` | | Name of the image these layers belong to, e.g. `api`. Used as the cache scope and as the image name in the BuildKit registry. | +| `context` | | Build context. | +| `file` | `Dockerfile` in the context | Path to the Dockerfile. | +| `target` | `''` | Build target. | +| `build-args` | `''` | Build args, one per line. | +| `tag` | `''` | Make the built image available to the local docker daemon under this tag. | +| `push` | `''` | Tags to push the built image to, one per line. | +| `cache-mode` | `max` | GitHub Actions cache mode without a shared BuildKit: `max` caches every stage, `min` only the final image's layers. | +| `driver-opts` | `''` | Options for the `docker-container` builder used without a shared BuildKit, one per line, e.g. `network=host`. | +| `summary` | `false` | Add the build summary to the job summary and upload the build record as an artifact. | + +## Outputs + +| Output | Description | +| --- | --- | +| `digest` | Digest of the built image, when it is tagged or pushed. | + +## With Skip If Passed + +When [Skip If Passed](https://github.com/kibalabs/github-action-skip-if-passed) decides a job can be skipped, it sets `CHECKS_ALREADY_PASSED=true` and this action does nothing. + +## Development + +The action is the composite action in `action.yml`. The Build workflow runs it on pull requests twice: once with the GitHub Actions cache and once with a BuildKit and registry started in the job. + +To release, bump `version` in `package.json` in a PR, then run the Release workflow on `main` (Actions → Release → Run workflow). It tags `vX.Y.Z`, publishes the release and moves the `vX` tag to it, so `@v1` always points at the latest 1.x release. Versions with a pre-release suffix (e.g. `1.1.0-rc1`) are published as pre-releases and don't move `vX`. Only the release workflow can push version tags. diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..4318d77 --- /dev/null +++ b/action.yml @@ -0,0 +1,125 @@ +name: 'Build Image' +description: 'Build a docker image with a shared BuildKit when the runner has one, or the GitHub Actions cache otherwise' +branding: + icon: 'package' + color: 'blue' +author: 'Kiba Labs' +inputs: + image: + description: 'Name of the image these layers belong to, e.g. api. Used as the GitHub Actions cache scope and as the image name in the BuildKit registry. Use the same image for builds of the same Dockerfile and build args, and a different one when either changes.' + required: true + context: + description: 'Build context' + required: true + file: + description: 'Path to the Dockerfile. Defaults to Dockerfile in the context.' + required: false + default: '' + target: + description: 'Build target' + required: false + default: '' + build-args: + description: 'Build args, one per line' + required: false + default: '' + tag: + description: 'Make the built image available to the local docker daemon under this tag' + required: false + default: '' + push: + description: 'Tags to push the built image to, one per line. Log in to the registry first.' + required: false + default: '' + cache-mode: + description: 'GitHub Actions cache mode when building without a shared BuildKit: max caches every stage, min only the layers of the final image (smaller, but intermediate stages rebuild)' + required: false + default: 'max' + driver-opts: + description: 'Options for the docker-container builder used without a shared BuildKit, one per line, e.g. network=host to reach registries on the runner''s localhost. The builder is created by the first build in the job, so set it there.' + required: false + default: '' + summary: + description: 'Add the build summary to the job summary and upload the build record as an artifact' + required: false + default: 'false' +outputs: + digest: + description: 'Digest of the built image, when it is tagged or pushed' + value: ${{ steps.build.outputs.digest }} +runs: + using: composite + steps: + - name: Choose how to build + id: resolve + if: env.CHECKS_ALREADY_PASSED != 'true' + shell: bash + env: + IMAGE: ${{ inputs.image }} + TAG: ${{ inputs.tag }} + PUSH: ${{ inputs.push }} + run: | + if [[ -n "$TAG" && -n "$PUSH" ]]; then + echo "::error::Set tag or push, not both" + exit 1 + fi + endpoint="${BUILDKIT_ENDPOINT:-}" + outputs='' + if [[ -z "$TAG" && -z "$PUSH" ]]; then + outputs='type=cacheonly' + elif [[ -n "$TAG" && -n "$endpoint" ]]; then + if [[ -z "${BUILDKIT_REGISTRY:-}" ]]; then + echo "::error::BUILDKIT_REGISTRY must be set with BUILDKIT_ENDPOINT to tag images" + exit 1 + fi + registryImage="$(echo "$BUILDKIT_REGISTRY/$GITHUB_REPOSITORY/$IMAGE" | tr '[:upper:]' '[:lower:]')" + outputs="type=image,name=$registryImage:latest,push=true,compression=uncompressed,force-compression=true" + echo "registry-image=$registryImage" >> "$GITHUB_OUTPUT" + fi + echo "endpoint=$endpoint" >> "$GITHUB_OUTPUT" + echo "outputs=$outputs" >> "$GITHUB_OUTPUT" + # NOTE(krishan711): builder options only apply to the docker-container builder, the shared BuildKit is configured where it runs + - name: Set up Docker Buildx + id: buildx + if: env.CHECKS_ALREADY_PASSED != 'true' && env.BUILD_IMAGE_BUILDER == '' + uses: docker/setup-buildx-action@v4 + with: + driver: ${{ steps.resolve.outputs.endpoint != '' && 'remote' || 'docker-container' }} + driver-opts: ${{ steps.resolve.outputs.endpoint == '' && inputs.driver-opts || '' }} + endpoint: ${{ steps.resolve.outputs.endpoint }} + # NOTE(krishan711): later builds in the job reuse this builder so they share its local state instead of starting a new one + - name: Remember the builder + if: env.CHECKS_ALREADY_PASSED != 'true' && env.BUILD_IMAGE_BUILDER == '' + shell: bash + env: + BUILDER: ${{ steps.buildx.outputs.name }} + run: echo "BUILD_IMAGE_BUILDER=$BUILDER" >> "$GITHUB_ENV" + - name: Build image + id: build + if: env.CHECKS_ALREADY_PASSED != 'true' + uses: docker/build-push-action@v7 + env: + DOCKER_BUILD_SUMMARY: ${{ inputs.summary }} + DOCKER_BUILD_RECORD_UPLOAD: ${{ inputs.summary }} + with: + builder: ${{ env.BUILD_IMAGE_BUILDER }} + context: ${{ inputs.context }} + file: ${{ inputs.file }} + target: ${{ inputs.target }} + build-args: ${{ inputs.build-args }} + outputs: ${{ steps.resolve.outputs.outputs }} + load: ${{ steps.resolve.outputs.endpoint == '' && inputs.tag != '' }} + push: ${{ inputs.push != '' }} + tags: ${{ inputs.push != '' && inputs.push || (steps.resolve.outputs.endpoint == '' && inputs.tag || '') }} + cache-from: ${{ steps.resolve.outputs.endpoint == '' && format('type=gha,scope={0}', inputs.image) || '' }} + # NOTE(krishan711): a failed cache upload, e.g. when GitHub rate limits the cache, shouldn't fail a build that succeeded + cache-to: ${{ steps.resolve.outputs.endpoint == '' && format('type=gha,mode={0},scope={1},ignore-error=true', inputs.cache-mode, inputs.image) || '' }} + - name: Pull image + if: env.CHECKS_ALREADY_PASSED != 'true' && steps.resolve.outputs.registry-image != '' + shell: bash + env: + IMAGE: ${{ steps.resolve.outputs.registry-image }}@${{ steps.build.outputs.digest }} + TAG: ${{ inputs.tag }} + run: | + docker pull --quiet "$IMAGE" + docker tag "$IMAGE" "$TAG" diff --git a/package.json b/package.json new file mode 100644 index 0000000..4204574 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "@kibalabs/github-action-build-image", + "version": "1.0.0", + "description": "GitHub Action to build a docker image with a shared BuildKit when the runner has one, or the GitHub Actions cache otherwise", + "license": "MIT", + "private": true, + "repository": { + "type": "git", + "url": "https://github.com/kibalabs/github-action-build-image.git" + }, + "bugs": "https://github.com/kibalabs/github-action-build-image/issues" +} diff --git a/tests/Dockerfile b/tests/Dockerfile new file mode 100644 index 0000000..8c6d9e6 --- /dev/null +++ b/tests/Dockerfile @@ -0,0 +1,7 @@ +FROM alpine:3 AS build +ARG MESSAGE=default +RUN echo "$MESSAGE" > /message + +FROM alpine:3 +COPY --from=build /message /message +RUN echo final >> /message