环境变量并不总是在 GitHub Actions 工作流程文件中展开

use*_*993 2 yaml github azure github-actions

我有一个 GitHub Actions 工作流程文件,其中环境变量并不总是被扩展。

根据注释,环境变量的使用可以正常工作,直到它在name: deploy不扩展的部分中最后一次使用为止,并且实际上变成了字符串,rg-blue-$***GITHUB_REF#refs/heads/***而不是前面部分中正确扩展的字符串:rg-blue-my-branch-name

这会导致 Azure ARM 错误:Error: Resource Group rg-blue-$***GITHUB_REF#refs/heads/*** could not be found.

为什么除了最后一步之外,变量扩展在所有地方都能正确工作?我如何解决它?

on: [push]
name: Azure ARM
jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    env:
      resourceGroupName: rg-blue-${GITHUB_REF#refs/heads/}
      resourceGroupLocation: 'uksouth'

    - name: Use the custom ENV variable
      run: |
        echo "${{ env.resourceGroupName}}"
        echo ${{ env.resourceGroupName}}
      // these two work perfectly fine and prints "rg-blue-my-branch-name" etc

    - uses: actions/checkout@master

    - uses: azure/login@v1
      with:
        creds: ${{ secrets.AZURE_CREDENTIALS }}

    - uses: azure/CLI@v1
      with:
        inlineScript: |
          #!/bin/bash
          
    // works perfectly fine here too
          if $(az group exists --name ${{ env.resourceGroupName }}) ; then
            echo "Azure resource group ${{ env.resourceGroupName }} already exists, skipping creation..."
          else
            az group create --name ${{ env.resourceGroupName }} --location ${{ env.resourceGroupLocation }}
            echo "Azure resource group ${{ env.resourceGroupName }} created"
          fi

      # Deploy Bicep file
    - name: deploy
      uses: azure/arm-deploy@v1
      with:
        subscriptionId: ${{ secrets.AZURE_SUBSCRIPTION }}     <- this one works fine!
        resourceGroupName: "${{ env.resourceGroupName }}"     <- Error: Resource Group rg-blue-$***GITHUB_REF#refs/heads/*** could not be found.
        template: infrastructure/blue.bicep
        parameters: storagePrefix=mystore
        failOnStdErr: false
Run Code Online (Sandbox Code Playgroud)

Ben*_* W. 7

当您在 YAML 中分配值时,不会发生 Shell 参数扩展。换句话说,在这之后

    env:
      resourceGroupName: rg-blue-${GITHUB_REF#refs/heads/}
Run Code Online (Sandbox Code Playgroud)

的值resourceGroupName是文字字符串rg-blue-${GITHUB_REF#refs/heads/}。它似乎有效,因为当你使用

echo "${{ env.resourceGroupName}}"
Run Code Online (Sandbox Code Playgroud)

这被替换为

echo "rg-blue-${GITHUB_REF#refs/heads/}"
Run Code Online (Sandbox Code Playgroud)

然后shell进行扩展。您可以使用以下方法进行测试

echo '${{ env.resourceGroupName}}'
Run Code Online (Sandbox Code Playgroud)

而是抑制 shell 参数扩展。

要修复此问题,您可以使用单独的步骤来正确设置环境变量:

    - name: Set env variable
      run: |
        echo "resourceGroupName=${GITHUB_REF#refs/heads/}" >> "$GITHUB_ENV"
Run Code Online (Sandbox Code Playgroud)

并且没有预先设置它env

或者,您可以使用github.ref_name,它是已经缩短的 Git 参考:

    env:
      resourceGroupName: rg-blue-${{ github.ref_name }}
Run Code Online (Sandbox Code Playgroud)

这也可以在 环境中使用$GITHUB_REF_NAME