Skip to content

Instantly share code, notes, and snippets.

@NeodymiumFerBore
Last active February 5, 2024 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NeodymiumFerBore/2a0af2cf6e208bcc36a22124877c91b6 to your computer and use it in GitHub Desktop.
Save NeodymiumFerBore/2a0af2cf6e208bcc36a22124877c91b6 to your computer and use it in GitHub Desktop.
Run a job in a container, with an image built in a previous job

Run a job in a container with a previously built image

This workflow shows how to use a GitHub Action job output as a variable for another job container image. It will build a simple Docker image, tag it with the commit short SHA, push it to Docker Hub, then run a job in it.

Why?

In job.<job_id>.container.image, the env context is not available, but we can use outputs.

Note

If your docker metadata action returns multiple tags, I don't know how this would behave.

Instead of using ${{ needs.build.outputs.image_tag }}, you can use anything, for example:

job:
  job1:
    outputs:
      my_output: ${{ steps.vars.outputs.sha_short }}
    steps:
      - id: vars
        run: echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
FROM alpine:latest
RUN echo 'Do I exist?' > /test.txt
name: Docker
on:
workflow_dispatch:
push:
branches: [ "main" ]
env:
REPOSITORY: your-docker-hub-namespace/your-docker-hub-repository
jobs:
build:
runs-on: ubuntu-latest
outputs:
# This is what we are going to use to run the next job in our new image
image_tag: ${{ steps.meta.outputs.tags }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Log in to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a
with:
username: ${{ vars.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
with:
images: ${{ env.REPOSITORY }}
tags: type=sha,prefix=
- run: echo "steps.meta.outputs.tags = ${{ steps.meta.outputs.tags }}"
- name: Build and push Docker image
uses: docker/build-push-action@3b5e8027fcad23fda98b2e3ac259d8d67585f671
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
test:
runs-on: ubuntu-latest
needs: build
container:
image: ${{ needs.build.outputs.image_tag }}
steps:
- name: Does this look like your image?
run: ls -l /
- name: Assert that our test file is here
run: test "$(cat /test.txt)" == "Do I exist?"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment