我正在用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。https://github.com/EthanSK/git-branch-name-action
其他回答
注意,如果你在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
我添加了一个单独的步骤,用于从$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现在支持GITHUB_REF_NAME,它代表触发工作流运行的分支或标记名称。
GitHub文档在这个https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables上
下面是一个代码片段,它是一个基于$GITHUB_REF的环境变量,如果不存在,则默认为dev。
根据您的需求调整sed命令。
export GIT_BRANCH=$(echo ${GITHUB_REF:-dev} | sed s/.*\\///g)
为了获得delete事件上的ref名称,我最终使用了sed。
on:
delete:
...
steps:
- name: Do something
shell: bash
run: |
refname=$(sed -e s:refs/heads/::g -e s:/:-:g <<< ${{ github.event.ref }})
剪掉指针/头/并将斜杠转换为破折号,例如。引用/heads/feature/somefeature到feature-somefeature