Objective
A repository at /home/interview/repo contains a Dockerfile and a starter GitHub Actions workflow, but no automated build process.
Task
Complete the workflow at .github/workflows/build.yml so that every push to the main branch builds a Docker image named app tagged with the short commit SHA.
File Path
- Workflow:
/home/interview/repo/.github/workflows/build.yml
- Dockerfile:
/home/interview/repo/Dockerfile
name: build
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set commit tag
run: |
TAG=$(git rev-parse --short HEAD)
echo "TAG=$TAG" >> $GITHUB_ENV
- name: Build image
run: docker build -t app:${{ env.TAG }} .
Explanation
Step 1: Checkout the Repository
- uses: actions/checkout@v4
GitHub Actions runners start with an empty workspace. Without actions/checkout, there is no repo, no Dockerfile, and no git history. This step clones the repository so subsequent steps can access the code and run git commands.
Step 2: Compute the Short Commit SHA
- name: Set commit tag
run: |
TAG=$(git rev-parse --short HEAD)
echo "TAG=$TAG" >> $GITHUB_ENV
git rev-parse --short HEAD outputs the first 7 characters of the current commit hash (e.g. a3b8f1c). Writing it to $GITHUB_ENV makes the variable available to all subsequent steps in the job. This is the standard way to pass computed values between steps in GitHub Actions.
Step 3: Build and Tag the Image
- name: Build image
run: docker build -t app:${{ env.TAG }} .
${{ env.TAG }} reads the variable set in the previous step. The resulting image is tagged as app:<short-sha> (e.g. app:a3b8f1c), which ties every image directly to the commit that produced it. This makes it trivial to trace a running container back to its source code.
Why Not Use latest?
Tagging images as latest tells you nothing about which version of the code is running. If two developers push within minutes of each other, both images are latest and you cannot tell them apart. Commit SHA tags are unique, immutable, and directly map to a point in the git history, making rollbacks and debugging straightforward.