GitHub Action新手求助:如何通过标签获取目录用于Matrix Job的Terraform Apply
从PR标签提取目录并生成Matrix Job的实现方案
核心需求拆解
你已经通过actions/labeler@v4实现了PR标签自动添加,现在需要在issue_comment触发的工作流中完成以下步骤:
- 提取PR的所有标签名称
- 根据标签匹配
labeler.yml中的对应目录 - 将目录列表转为Matrix变量,供后续
terraform apply使用
完整工作流实现
以下是补全后的工作流代码,关键步骤已添加注释:
name: label_target_check on: issue_comment: permissions: contents: read pull-requests: write issues: write jobs: get_target_dirs: if: ${{ github.event.issue.pull_request && startsWith(github.event.comment.body, 'apply') }} runs-on: ubuntu-latest outputs: target_dirs: ${{ steps.extract_dirs.outputs.target_dirs }} steps: - name: Fetch PR Branch uses: xt0rted/pull-request-comment-branch@v2 id: comment-branch - name: Checkout uses: actions/checkout@v3 with: ref: ${{ steps.comment-branch.outputs.head_ref }} - name: Generate token uses: tibdex/github-app-token@v1 id: get_installation_token with: app_id: ${{ secrets.APP_ID }} private_key: ${{ secrets.PRIVATE_KEY }} - uses: octokit/request-action@v2.x id: get_latest_label with: route: GET /repos/${{ github.repository }}/issues/${{ github.event.issue.number }}/labels env: GITHUB_TOKEN: ${{ steps.get_installation_token.outputs.token }} # 提取标签名称,生成JSON数组 - name: Extract label names id: extract_labels run: | LABELS=$(echo '${{ steps.get_latest_label.outputs.data }}' | jq -r '.[].name' | jq -R . | jq -s .) echo "labels=$LABELS" >> $GITHUB_OUTPUT # 安装yq用于解析YAML文件 - name: Install yq run: sudo apt-get install -y yq # 匹配标签对应的目录,生成目标目录数组 - name: Extract target directories id: extract_dirs run: | # 将labeler.yml转为键值对JSON LABELER_JSON=$(yq -o json .github/labeler.yml) # 从标签数组中匹配对应的目录,去重后生成JSON数组 TARGET_DIRS=$(echo "$LABELER_JSON" | jq --argjson labels '${{ steps.extract_labels.outputs.labels }}' 'to_entries | map(select(.key | IN($labels[]))) | .[].value' | jq -R . | jq -s .) echo "target_dirs=$TARGET_DIRS" >> $GITHUB_OUTPUT # 调试输出:查看最终的目标目录列表 - name: Print target directories run: echo "Target directories: ${{ steps.extract_dirs.outputs.target_dirs }}" # 使用Matrix Job执行terraform apply terraform_apply: needs: get_target_dirs runs-on: ubuntu-latest strategy: matrix: dir: ${{ fromJson(needs.get_target_dirs.outputs.target_dirs) }} steps: - name: Checkout code uses: actions/checkout@v3 - name: Terraform Apply working-directory: ${{ matrix.dir }} run: | terraform init terraform apply -auto-approve
关键步骤说明
- 提取标签名称:使用
jq从GitHub API返回的JSON中提取所有name字段,转为JSON数组格式,方便后续处理。 - 解析labeler.yml:用
yq将YAML文件转为JSON,再通过jq的IN操作符匹配标签对应的目录,确保只保留PR标签对应的路径。 - Matrix Job配置:通过
fromJson将输出的目录数组转为Matrix的dir变量,实现多目录并行执行terraform apply。
注意事项
- 确保
labeler.yml的路径正确(示例中是.github/labeler.yml,如果你的文件在其他位置需要修改)。 - 若存在标签重复或目录重复的情况,
jq的处理会自动去重,避免重复执行。 - 需要确保runner环境中可以安装
yq(Ubuntu默认源包含该包,若使用其他系统可能需要调整安装方式)。
内容的提问来源于stack exchange,提问作者Rio
相关产品推荐
相关产品推荐

