DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

GitHub Actions 复合动作 Composite Action 输入参数未解析排查

分析 GitHub Actions 编写 Composite Action 时 inputs 与 outputs 变量无法求值为空的语法机制与对策。

故障现象

在 GitHub Actions 中开发自定义复合动作(Composite Action,即 action.yml 中声明 runs.using: "composite")时,调用方传入的参数在动作内部的 shell 步骤中未生效或直接被解析为空字符串,导致后续脚本逻辑错乱:

Deploying to environment: 
Error: Target host or token is missing!

构建日志表明传入的 ${{ inputs.target-env }} 未能正确被替换渲染。

核心机制与根因分析

Composite Action 相比传统的 Docker 或 Javascript 动作有着特殊的语法解析上下文:

  1. 未在 action.yml 中显式声明 input 契约:调用方虽然传递了 with: { env: "prod" },但在 action.yml 的顶层 inputs 块中未对该键名进行定义,GitHub Actions 引擎出于安全规则直接丢弃未声明的传参。
  2. 表达式上下文混淆与 shell 引号陷阱:在 run: 脚本中,直接书写 ${{ inputs.xxx }} 会在 Actions 阶段执行字符串模板替换。若参数内容包含特殊字符或引号未闭合,会导致 shell 语法报错或被误解析为空。
  3. 环境变量绑定机制:在复合动作内部,将 inputs 映射为标准的 step 环境变量是官方推荐的最安全做法。

分步排查与定位

1. 检查 action.yml 的顶层 inputs 声明与拼写

name: "Deploy Action"
description: "Deploy artifacts"
inputs:
  target-env:
    description: "Target environment"
    required: true
    default: "staging"

确保键名拼写与工作流调用方的 with: 下字段完全一致。

针对性解决方案

方案一:通过 env 显式映射避免直接插值(标准最佳实践)

避免在 run: 中直接裸写 ${{ inputs.target-env }},优先映射为 step 环境变量:

runs:
  using: "composite"
  steps:
    - name: Run deploy script
      shell: bash
      env:
        TARGET_ENV: ${{ inputs.target-env }}
        DEPLOY_TOKEN: ${{ inputs.deploy-token }}
      run: |
        echo "Deploying to environment: ${TARGET_ENV}"
        python deploy.py --env "${TARGET_ENV}"

这样由 shell 原生变量保证转义安全,杜绝命令注入与解析丢失。

方案二:针对 Outputs 输出使用 $GITHUB_OUTPUT 文件

在复合动作输出参数时,使用现代 $GITHUB_OUTPUT 文件追加语法:

outputs:
  artifact-id:
    description: "Generated ID"
    value: ${{ steps.generate.outputs.res_id }}
runs:
  using: "composite"
  steps:
    - id: generate
      shell: bash
      run: |
        NEW_ID=$(uuidgen)
        echo "res_id=${NEW_ID}" >> $GITHUB_OUTPUT