我正在使用Github Actions构建Docker镜像,想要对镜像打上分支名称的标签。
我找到了GITHUB_REF
变量,但它返回refs/heads/feature-branch-1
,而我只需要feature-branch-1
。
我正在使用Github Actions构建Docker镜像,想要对镜像打上分支名称的标签。
我找到了GITHUB_REF
变量,但它返回refs/heads/feature-branch-1
,而我只需要feature-branch-1
。
$GITHUB_REF_NAME
。
Documentation: https://docs.github.com/en/actions/learn-github-actions/variables
#!/bin/bash
echo "${GITHUB_HEAD_REF:-$(git branch --show-current)}"
- run: echo "${GITHUB_HEAD_REF:-$(git branch --show-current)}" >> $GITHUB_OUTPUT
shell: bash
id: branch
- name: Get branch name
id: branch-name
uses: tj-actions/branch-names@v7
- name: Show the current branch name
run: |
echo "Current branch: ${{ steps.branch-name.outputs.current_branch }}"
在Windows上运行? Windows的默认命令是PowerShell终端。
- name: SET CURRENT_BRANCH
run: |
$branchName = "${{github.ref}}".Split("/")["${{github.ref}}".Split("/").Length -1]
echo "::set-env name=CURRENT_BRANCH::$(echo $branchName)"
$branchName = $Env:GITHUB_REF -replace "refs/heads/", ""
。我不是 PowerShell专家,所以我很乐意听取您的建议。 - Airn5475我们目前有一个单独的作业,在所有其他作业之前运行。该步骤根据分支名称确定它在哪个环境中运行。我们的分支与特定环境关联,用于部署基础设施和代码库。每个环境还有自己的机密(GitHub企业功能)。
输出环境变量可以在所有其他连续作业中使用。您可以在步骤中使用该变量,例如将其设置为NODE_ENV
,或者用它标记一个Docker镜像。您还可以在该特定变量上设置并发性,以确保只有一个使用相同值的作业或工作流程在同一时间运行。这使其非常强大。
下面是我上面描述的示例:
name: Build pipeline
on:
push:
branches:
- feature/*
- develop
- release/*
- main
jobs:
environments:
name: Set environment
runs-on: ubuntu-latest
steps:
- run: echo "Setting $ENVIRONMENT.."
outputs:
# Defaults to 'dev' in case of a feature branch
# You could also use the contains expression if needed
environment: ${{ github.ref == 'refs/heads/main' && 'prd' || (startsWith(github.ref, 'refs/heads/release/') && 'acc' || github.ref == 'refs/heads/develop' && 'tst' || 'dev') }}
build:
name: Docker build
runs-on: ubuntu-latest
needs: [environments]
environment: ${{ needs.environments.outputs.environment }} # Enterprise only
concurrency: ${{ needs.environments.outputs.environment }}
env:
ENVIRONMENT: ${{ needs.environments.outputs.environment }}
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Build
run: |
docker build . \
-t hello/world:${{ needs.environments.outputs.environment }}
注意:由于在bash或powershell中提取环境名称尚未完成,因此您受限于expressions github actions提供的有限功能。如果您需要更高级的功能,可以选择其他方式实现,没有唯一的真理。然而,我总是喜欢保持简单和易读。
备选(快速)选项
如果您不介意使用其他人的github actions,您可以使用市场上的许多操作之一来查找替换。例如,可以在here找到一个示例,看起来像:
on: [push]
jobs:
replace-job:
runs-on: ubuntu-latest
name: 'Find and replace'
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Remove refs/heads/ from string
uses: mad9000/actions-find-and-replace-string@1
id: findandreplace
with:
source: ${{ github.ref }}
find: 'refs/heads/'
replace: ''
- name: Branch name
run: echo "The branch name is ${{ steps.findandreplace.outputs.value }}"
setenv
函数,并且没有使用任何外部库。 - michielbdejong${{ github.ref_name }}
对我有效。 - Neil McGuigan