我需要使用 GitHub Action,该操作将执行 api 调用来获取 ID 列表,然后循环遍历 ID 列表并使用其中的每一个执行 api POST。
我遇到的问题是 api 返回多个数组对象,而我无法仅访问数组对象。
作业 1 (define-matrix) 中的“json-project”是第一个 api 调用返回的示例。
---
name: Test Loop
on:
push:
branches: [development]
jobs:
# Job 1: Collect data
define-matrix:
runs-on: ubuntu-latest
outputs:
json-project: ${{ steps.project-step.outputs.json-project }}
steps:
- name: Define Project String
id: project-step
run: |
echo "json-project={\"count\":2,\"include\":[{\"project\":\"1\",\"config\":\"Debug\"},{\"project\":\"2\",\"config\":\"Release\"}]}" >> "$GITHUB_OUTPUT"
# Job 2: Print the output of the "define-matrix" job
print-output:
runs-on: ubuntu-latest
needs: define-matrix
steps:
- name: Print project-json variable
id: print-stuff
run: |
echo ${{ toJson(needs.define-matrix.outputs.json-project) }}
echo ${{ toJson(needs.define-matrix.outputs.json-project) }} | jq -r '.include[].project'
# Job 3: Loop through array
print-array-output:
runs-on: ubuntu-latest
needs: define-matrix
strategy:
matrix: ${{ fromJson(needs.define-matrix.outputs.json-project) }}
steps:
- name: Print project-json variable
id: print-array-item
run: |
curl --insecure --request POST --url ${{ vars.url }}/projects/${{ matrix.include.project }}/update/
当我运行此作业时,作业 3(打印数组输出)返回以下错误:
评估作业“打印数组输出”的“策略”时出错。 .github/workflows/test-loop2.yml(行:40,列:15):意外值“2”
这似乎是错误的,因为“count”对象位于“include”数组的前面。但我不知道如何让策略/矩阵仅使用“包含”对象。
有人可以提供建议吗?
您可以使用 属性解引用运算符
.
和 fromJson
来仅获取 include
数组并直接设置 strategy.matrix.include
,如下所示:
strategy:
matrix:
include: ${{ fromJson(needs.define-matrix.outputs.json-project).include }}
,稍后使用
matrix.project
和 matrix.config
访问这些值。
这是更新后的工作流程:
name: matrix_test
on: workflow_dispatch
jobs:
define-matrix:
runs-on: ubuntu-latest
outputs:
json-project: ${{ steps.project-step.outputs.json-project }}
steps:
- name: Define Project String
id: project-step
run: echo 'json-project={"count":2,"include":[{"project":"1","config":"Debug"},{"project":"2","config":"Release"}]}' >>"$GITHUB_OUTPUT"
print-output:
runs-on: ubuntu-latest
needs: define-matrix
steps:
- name: Print project-json variable
run: echo '${{ needs.define-matrix.outputs.json-project }}' | jq -r '.include[].project'
print-array-output:
runs-on: ubuntu-latest
needs: define-matrix
strategy:
matrix:
include: ${{ fromJson(needs.define-matrix.outputs.json-project).include }}
steps:
- name: Print project-json variable
run: echo '${{ matrix.project }} | ${{ matrix.config }}'