向运行PowerShell的自定义GitHub Actions传递环境变量失败排查
问题描述
尝试实现一个运行自定义Action的GitHub工作流模板,需要将主工作流的环境变量传递给自定义Action并在PowerShell中使用。目前bash环境下可正常获取变量值,但在PowerShell中输入值为空。
主工作流代码
name: cicd service on: push: branches: [ "master", "main", "refs/tags/s*", "refs/tags/v*" ] pull_request: branches: [ "master", "main" ] env: pod_name: 'cicd' compile_name: 'cicd' reg_name: 'cicd' jobs: build: runs-on: enterprise-linux-runner steps: - name: Checkout uses: actions/checkout@v2 with: ref: ${{ github.event.workflow_run.head_branch }} - name: aaa shell: bash run: echo "Hello ${pod_name}" # 输出符合预期:Hello cicd - name: Get tag uses: ./.github/templates/gettag with: dname: ${pod_name}
可复用Action代码
name: gettag inputs: dname: required: true runs: using: "composite" steps: - name: bbb shell: pwsh run: write-host "name ${{ inputs.dname }}" # 输出为"name ",不符合预期 - name: bbb shell: bash run: echo "name ${{ inputs.dname }}" # 输出符合预期:name cicd
问题原因与解决方案
问题根源
主工作流传递参数给自定义Action时,用了shell的变量引用语法${pod_name},但GitHub Actions的YAML配置中,必须用GitHub Actions表达式语法引用环境变量,否则传递的是变量名字符串而非实际值:
- Action的bash步骤中,传入的
${pod_name}会被bash解析为继承自主工作流的环境变量,所以输出正常; - Action的PowerShell步骤中,PowerShell不支持
${变量名}的语法,无法将该字符串解析为环境变量,最终输出空值。
解决方案
修改主工作流的参数传递代码,使用${{ env.pod_name }}替代${pod_name},让GitHub Actions直接把环境变量值传递给自定义Action:
- name: Get tag uses: ./.github/templates/gettag with: dname: ${{ env.pod_name }}
修改后,自定义Action的inputs.dname会直接拿到cicd的值,PowerShell和bash步骤都能正常输出name cicd。
内容的提问来源于stack exchange,提问作者Eduard Dubilyer
相关产品推荐
相关产品推荐

