GitHub Actions中如何在后续步骤获取已设置的环境名称?
问题:GitHub Actions中如何在步骤里访问动态设置的环境名称?
我们已在GitHub Actions中配置了dev、uat、prod三个环境并设置了保护规则,会根据分支名称自动部署到对应环境。以下是pipeline.yml的部分内容:
jobs: build: runs-on: ubuntu-latest environment: name: ${{ (github.ref == 'refs/heads/develop' && 'dev') || (github.ref == 'refs/heads/staging' && 'uat') || (github.ref == 'refs/heads/master' && 'prod') }} steps: [...] - name: Build run: docker build --build-arg ENVIRONMENT=???what-here??? -t ... [...]
现在需要在后续步骤(比如构建容器的步骤)中访问这个动态设置的环境名称,作为--build-arg的参数,但在env变量和github对象中都找不到它,该如何实现?
解决方案
有三种常用的方式可以实现这个需求:
方法一:定义Job级别的环境变量(推荐)
在build job中添加一个env字段,用和environment.name相同的表达式定义环境名称变量,这样整个job的所有步骤都能直接调用这个变量:
jobs: build: runs-on: ubuntu-latest # 定义Job级环境变量,复用环境名称的判断逻辑 env: ENV_NAME: ${{ (github.ref == 'refs/heads/develop' && 'dev') || (github.ref == 'refs/heads/staging' && 'uat') || (github.ref == 'refs/heads/master' && 'prod') }} environment: name: ${{ env.ENV_NAME }} # 直接引用上面定义的变量 steps: [...] - name: Build run: docker build --build-arg ENVIRONMENT=${{ env.ENV_NAME }} -t ...
这种方式的好处是逻辑只写一次,避免重复代码,后续维护更方便。
方法二:在步骤中直接复用判断表达式
如果不想额外定义变量,可以直接在步骤的run命令中使用和environment.name相同的表达式:
jobs: build: runs-on: ubuntu-latest environment: name: ${{ (github.ref == 'refs/heads/develop' && 'dev') || (github.ref == 'refs/heads/staging' && 'uat') || (github.ref == 'refs/heads/master' && 'prod') }} steps: [...] - name: Build run: docker build --build-arg ENVIRONMENT=${{ (github.ref == 'refs/heads/develop' && 'dev') || (github.ref == 'refs/heads/staging' && 'uat') || (github.ref == 'refs/heads/master' && 'prod') }} -t ...
这种方式适合简单场景,但如果后续需要修改判断逻辑,要同时改两处,维护成本较高。
方法三:用步骤输出传递环境名称
还可以通过一个前置步骤将环境名称输出,后续步骤引用这个输出值:
jobs: build: runs-on: ubuntu-latest environment: name: ${{ (github.ref == 'refs/heads/develop' && 'dev') || (github.ref == 'refs/heads/staging' && 'uat') || (github.ref == 'refs/heads/master' && 'prod') }} steps: - name: Set environment name output id: set-env run: | if [ "${{ github.ref }}" = "refs/heads/develop" ]; then echo "env_name=dev" >> $GITHUB_OUTPUT elif [ "${{ github.ref }}" = "refs/heads/staging" ]; then echo "env_name=uat" >> $GITHUB_OUTPUT elif [ "${{ github.ref }}" = "refs/heads/master" ]; then echo "env_name=prod" >> $GITHUB_OUTPUT fi [...] - name: Build run: docker build --build-arg ENVIRONMENT=${{ steps.set-env.outputs.env_name }} -t ...
这种方式适合需要在shell逻辑中处理复杂判断的场景,但写法相对繁琐。
内容的提问来源于stack exchange,提问作者MLu
相关产品推荐
相关产品推荐

