GitHub Actions Env & Commits
Environment
There are several ways to consume environment variables in GitHub Actions but I was unsure how to set environment variables. I have a Go build that uses -ldflags "-X main.OSVersion=${VERSION} -X main.GitCommit=${COMMIT}" to set variables in the binary that can be e.g. exported via Prometheus.
The GitCommit is straightforward as it’s one of GitHub Actions’ provided values and is just ${{ github.sha }}.
I wanted to set Version to be the value of uname --kernel-release. Since the build is using ubuntu-latest, this is easy to get but, how to set?
The solution is to use a run step:
- name: Get kernel version
run: echo "VERSION=$(uname --kernel-release)" >> ${GITHUB_ENV}
NOTE The variable (
VERSION) is set but then appended to${GITHUB_ENV}
Then, in a following step, I can reference it as ${{ env.VERSION }}:
- name: build-push
uses: docker/build-push-action@v2
with:
context: .
file: ./Dockerfile
build-args: |
VERSION=${{ env.VERSION }}
COMMIT=${{ github.sha }}
tags: ghcr.io/${{ env.REPO }}:${{ github.sha }}
push: true
Commits
It was non-obvious to me to understand how to commit changes made to the repo’s files during the GitHub Actions workflow. After reviewing several different posts, the following (amalgam) works:
- name: revise occurrences of the image
run: |
git config --local user.email "[email protected]"
git config --local user.name "GitHub Actions"
OLD="ghcr.io/${{ env.REPO }}:[0-9a-f]\{40\}"
NEW="ghcr.io/${{ env.REPO }}:${{ github.sha }}"
sed \
--in-place \
"s|${OLD}|${NEW}|g" \
./kubernetes.yaml
git add ./kubernetes.yaml
git commit --message "GitHub Actions update image references"
git push origin master
That’s all!