如何在GitHub Workflow中获取提交的短SHA值?
Absolutely, this is totally feasible! You don’t need to run git rev-parse --short HEAD directly—GitHub Actions provides straightforward ways to get the short SHA for your global environment variable. Here are two reliable approaches:
Method 1: Use GitHub’s substring expression (simplest for global env)
You can truncate the full ${{ github.sha }} to the first 7 characters (the default length returned by git rev-parse --short HEAD) using the built-in substring function directly in your global env section:
name: continuous integration on: push: branches: - '**' env: IMAGE: docker.pkg.github.com/${{ github.repository }}/jactor-persistence:${{ github.sha | substring(0,7) }}
This will give you exactly the same short SHA as the git command, and it’s available to all jobs in your workflow without extra steps.
Method 2: Set via a step (for custom length or validation)
If you need a different short SHA length (e.g., 10 characters instead of 7) or want to explicitly validate the value first, you can set the variable in an initial setup job and pass it to subsequent jobs:
name: continuous integration on: push: branches: - '**' jobs: setup-sha: runs-on: ubuntu-latest outputs: short_sha: ${{ steps.get-sha.outputs.short_sha }} steps: - name: Checkout code uses: actions/checkout@v4 - name: Get custom short SHA id: get-sha run: echo "short_sha=$(git rev-parse --short=10 HEAD)" >> $GITHUB_OUTPUT build-image: needs: setup-sha runs-on: ubuntu-latest env: IMAGE: docker.pkg.github.com/${{ github.repository }}/jactor-persistence:${{ needs.setup-sha.outputs.short_sha }} steps: # Add your build/push steps here
Either method works, but the first approach is cleaner for a global environment variable that’s used across all jobs.
内容的提问来源于stack exchange,提问作者jactor-rises

