【问题标题】:GitHub Actions: How to pass toJSON() result to shell commandsGitHub Actions:如何将 toJSON() 结果传递给 shell 命令
【发布时间】:2022-11-10 08:34:52
【问题描述】:

因此,我正在与 Github Actions 合作进行端到端测试。我正在查看的设置是让一项工作检索要测试的 url 列表,而我的第二项工作使用该列表创建一个矩阵并对其进行全部测试。我的问题是,当我实际运行我的测试脚本时,必须从命令行完成,因为我使用的是 Playwright。因此我不能直接使用我的矩阵对象;我必须将其输出到 JSON 文件。问题是当我将 toJSON 输出到我的文件时,它会创建无效的漂亮打印 JSON,这会破坏我的脚本。这是我的代码:

name: <name>

on:
    push:
    workflow_dispatch:

jobs:
    fetch_strategic_urls:
        runs-on: ubuntu-latest
        outputs:
            urls: ${{ steps.req-urls.outputs.urls }}
        steps:
            - name: Request Urls
              id: req-urls
              run: |
                  export RESPONSE=$(
                    curl -X GET -H "Accept: application/json" <api-endpoint>)
                  echo "::set-output name=urls::$RESPONSE"
    run_tests:
        runs-on: ubuntu-latest
        strategy:
            matrix:
                url: ${{needs.fetch_strategic_urls.outputs.urls}}
        needs: fetch_strategic_urls
        steps:
            - ...
            - ...
            - run: |
                  ls
                  echo '${{ toJSON(matrix.url) }}' >> props.json
                  cat props.json
                  npm test
              working-directory: E2E.Tests

无论我尝试过echo ${{matrix.url}} &gt;&gt; props.json的哪种配置(cat &lt;&lt;'EOF' &gt; props.json ${{matrix.url}},添加和删除引号),它总是生成没有引号的JSON文件,即:{ url: string }而不是{"url": "string"},这是无效的。这显然是非常破坏性的行为。我在网上看到很多人推荐 jq,但我不知道在这种情况下我会如何使用它,因为我怀疑 jq 是否可以解析 GitHub 类型的 JSON 对象,这是我在分片时使用的必要条件工作。任何帮助是极大的赞赏!

【问题讨论】:

标签: json bash yaml github-actions jsonparser


【解决方案1】:

将 JSON 文档直接放在命令行中并不容易。您可以使用环境变量。

- shell: bash
  env:
    JSON_DOC: ${{ toJSON(some.var) }}
  run: |
    printf '%s
' "$JSON_DOC" > foo.json
    cat foo.json
    ...

【讨论】:

  • 在我花了很长时间研究不同的解决方案之后,这实际上非常有效。谢谢!
【解决方案2】:

Github 操作文档在这里有一个解决方案:

name: Context testing
on: push

jobs:
  dump_contexts_to_log:
    runs-on: ubuntu-latest
    steps:
      - name: Dump GitHub context
        id: github_context_step
        run: echo '${{ toJSON(github) }}'

来自https://docs.github.com/en/actions/learn-github-actions/contexts#example-printing-context-information-to-the-log

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2015-01-08
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多