我正在用Github动作构建Docker图像,并想用分支名称标记图像。
我找到了GITHUB_REF变量,但它导致了refs/heads/feature-branch-1,我只需要feature-branch-1。
我正在用Github动作构建Docker图像,并想用分支名称标记图像。
我找到了GITHUB_REF变量,但它导致了refs/heads/feature-branch-1,我只需要feature-branch-1。
当前回答
注意,如果你在pull request触发器上执行你的GitHub动作,那么GITHUB_REF变量将包含类似refs/pull/421/merge这样的东西,所以如果你尝试git push到那个名字,它很可能会失败。
你可以在YAML中使用GitHub上下文中的引用。比如:${{github。head_ref}}
https://help.github.com/en/actions/automating-your-workflow-with-github-actions/contexts-and-expression-syntax-for-github-actions#github-context
其他回答
你可以使用https://github.com/rlespinasse/github-slug-action
# Just add this =>
- name: Inject slug/short variables
uses: rlespinasse/github-slug-action@v3.x
# And you get this =>
- name: Print slug/short variables
run: |
echo "Slug variables"
echo " - ${{ env.GITHUB_REF_SLUG }}"
echo " - ${{ env.GITHUB_HEAD_REF_SLUG }}"
echo " - ${{ env.GITHUB_BASE_REF_SLUG }}"
echo " - ${{ env.GITHUB_REPOSITORY_SLUG }}"
# output e.g. : master feat-new-feature v1.0.0 product-1.0.0-rc.2 new-awesome-product
echo "Slug URL variables"
echo " - ${{ env.GITHUB_REF_SLUG_URL }}"
echo " - ${{ env.GITHUB_HEAD_REF_SLUG_URL }}"
echo " - ${{ env.GITHUB_BASE_REF_SLUG_URL }}"
echo " - ${{ env.GITHUB_REPOSITORY_SLUG_URL }}"
# output e.g. : master feat-new-feature v1-0-0 product-1-0-0-rc-2 new-awesome-product
echo "Short SHA variables"
echo " - ${{ env.GITHUB_SHA_SHORT }}"
# output e.g. : ffac537e
我添加了一个单独的步骤,用于从$GITHUB_REF提取分支名称,并将其设置为步骤输出
- name: Extract branch name
shell: bash
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
id: extract_branch
在那之后,我可以在接下来的步骤中使用它
- name: Push to ECR
id: ecr
uses: jwalton/gh-ecr-push@master
with:
access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
region: us-west-2
image: eng:${{ steps.extract_branch.outputs.branch }}
获取当前分支很简单,下面的代码适用于我和
github.ref_name
是用于获取分支名称的预定义变量吗
jobs:
main-branch-build:
if: github.ref_name == 'main'
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
feature-branch-build:
if: github.ref_name != 'main'
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
如果你使用的是V2的actions/checkout,那么你总是可以运行git branch——show-current来获取当前签出的分支的名称。
if: github.ref == 'refs/heads/integration' && github.event_name == 'push'
您可以使用上面的命令替换您想要运行的任何分支或事件。