如何在GitHub Action的if语句中使用matrix作为条件
问题分析与解决方案
错误原因
你遇到的Unrecognized named-value: 'matrix'错误,核心原因是GitHub Actions中job级别的if条件会在matrix实例生成前就完成评估。此时matrix变量还未初始化,自然无法引用matrix.project这类矩阵内的变量。
最佳实现方案
推荐采用动态生成过滤后的matrix的方式,只包含有代码变更的项目,同时保留分支条件判断,既避免无效job运行,又符合你的迭代需求。
步骤1:修改变更检查Job,输出动态Matrix
调整changes Job的配置,让dorny/paths-filter不仅检测变更,还生成仅包含变更项目的matrix格式JSON:
changes: runs-on: ubuntu-latest outputs: matrix: ${{ steps.filter.outputs.matrix }} steps: - uses: actions/checkout@v4 - uses: dorny/paths-filter@v2 id: filter with: filters: | AA: - 'AA/**' BB: - 'BB/**' CC: - 'CC/**' DD: - 'DD/**' EE: - 'EE/**' # 生成仅包含变更项目的matrix JSON matrix: | { "include": [ ${{ steps.filter.outputs.AA == 'true' && '{\"project\": \"AA\", \"working_dir\": \"AA/sandbox\"}' || '' }}, ${{ steps.filter.outputs.BB == 'true' && '{\"project\": \"BB\", \"working_dir\": \"BB/dev\"}' || '' }}, ${{ steps.filter.outputs.CC == 'true' && '{\"project\": \"CC\", \"working_dir\": \"CC/global\"}' || '' }}, ${{ steps.filter.outputs.DD == 'true' && '{\"project\": \"DD\", \"working_dir\": \"DD/dev\"}' || '' }}, ${{ steps.filter.outputs.EE == 'true' && '{\"project\": \"EE\", \"working_dir\": \"EE/prod\"}' || '' }} ].filter(item => item !== '') }
步骤2:调整Apply Job,使用动态Matrix
修改terraform-apply-cloudrnd Job,直接引用动态生成的matrix,同时保留分支判断条件:
terraform-apply-cloudrnd: strategy: # 解析动态生成的matrix,仅包含有变更的项目 matrix: ${{ fromJSON(needs.changes.outputs.matrix) }} # 无变更项目时跳过整个Job组,避免空运行 fail-fast: false # 根据需求调整并行执行数量 max-parallel: 1 # 仅在main分支相关场景触发 if: github.ref_name == 'main' || github.base_ref == 'main' needs: [changes] uses: ./.github/workflows/terraform-apply.yml secrets: GH_PAT: ${{ secrets.GH_PAT_AUTOMATION }} GH_USERNAME: ${{ vars.GH_USERNAME_AUTOMATION }} with: deployment_dir: ${{ matrix.working_dir }}
替代方案(简单但效率稍低)
如果不想修改变更检查逻辑,也可以将变更判断移到子workflow的步骤中:
- 在子workflow
terraform-apply.yml中添加变更检查步骤:
on: workflow_call: inputs: deployment_dir: type: string secrets: GH_PAT: required: true GH_USERNAME: required: true jobs: apply: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: 检查当前项目是否有变更 id: check-changes uses: dorny/paths-filter@v2 with: filters: | changed: - '${{ inputs.deployment_dir }}/**' - name: Terraform Apply if: steps.check-changes.outputs.changed == 'true' # 此处添加你的Terraform Apply执行逻辑
- 父workflow的Apply Job仅保留分支判断:
terraform-apply-cloudrnd: strategy: matrix: include: - project: "AA" working_dir: "AA/sandbox" - project: "BB" working_dir: "BB/dev" - project: "CC" working_dir: "CC/global" - project: "DD" working_dir: "DD/dev" - project: "EE" working_dir: "EE/prod" if: github.ref_name == 'main' || github.base_ref == 'main' needs: [changes] uses: ./.github/workflows/terraform-apply.yml secrets: GH_PAT: ${{ secrets.GH_PAT_AUTOMATION }} GH_USERNAME: ${{ vars.GH_USERNAME_AUTOMATION }} with: deployment_dir: ${{ matrix.working_dir }}
这种方式会触发所有matrix对应的Job,但只有有变更的项目会执行Apply步骤,配置简单但会产生少量无效Job运行。
内容的提问来源于stack exchange,提问作者cloudest
相关产品推荐
相关产品推荐

