英文:
Github Action: How to edit a JSON objects with Github repository secrets
问题
GitHub操作:如何使用GitHub存储库机密编辑JSON对象
在我的工作流程中,我有一个工作,用于编辑JSON文件中的空JSON值,并将它们替换为我的GitHub机密。问题是,当我运行cat 'test.json'命令时,我的更新值不会显示:
JSON文件:
{
"secret": "",
"name": "test"
}
工作流程:
steps:
- name: 编辑Json
      shell: bash
      run: |
        echo "`jq '.secret="${{ secrets.PRIVATE_KEY }}"'test.json`" > test.json
    - name: 显示
      run: |
        cat 'test.json'
输出:
{
"secret": "",
"name": "test"
}
预期输出:
{
"secret": "ABCDEFGH",
"name": "test"
}
英文:
Github Action: How to edit a JSON object with Github repository secrets in my workflow I have a job that edits the empty JSON values in JSON file and replaces them with my GitHub secrets. The problem is when I run the cat 'test.json' command my updated value does not appear:
JSON file:
{
"secret": "",
"name": "test"
}
Workflow:
steps:
- name: Edit Json
      shell: bash
      run: |
        echo "`jq '.secret="${{ secrets.PRIVATE_KEY }}"'test.json`" > test.json
    - name: display
      run: |
        cat 'test.json'
Output:
{
"secret": "",
"name": "test"
}
Expected Output:
{
"secret": "ABCDEFGH",
"name": "test"
}
答案1
得分: 1
你可以使用 jq 和 --arg 来实现这一点。
这个示例对我有用:
steps:
  - name: 创建测试文件
    run: |
      cat > test.json << EOL
      {
          "secret": "",
          "name": "test"
      }
      EOL      
  - name: 编辑 Json
    shell: bash
    run: |
            echo $(jq --arg a "${{ secrets.MY_SECRET }}" '.secret = ($a)' test.json) > test.json
  - name: 显示
    run: |
            cat test.json
  - uses: actions/upload-artifact@v3
    with:
      name: my-test-file
      path: ./test.json
我使用了 actions/upload-artifact 来上传我的 test.json 作为工件,然后在我的本机上读取它,作为 GitHub 隐藏了输出的一种解决方法。
是的,如果在控制台中看到 ***,这并不意味着文件没有更改,它只是在工作流的控制台和日志中被替换了。
如果秘密没有设置到你的文件中,请检查它是否在你的仓库中正确设置,然后检查你的自托管运行器上的 jq 版本,如果你在使用自托管的运行器。
英文:
You can achieve that using jq with --arg
This example worked for me:
steps:
  - name: Create test file
    run: |
      cat > test.json << EOL
      {
          "secret": "",
          "name": "test"
      }
      EOL
  - name: Edit Json
    shell: bash
    run: |
      echo $(jq --arg a "${{ secrets.MY_SECRET }}" '.secret = ($a)' test.json) > test.json   
  - name: display
    run: |
      cat test.json
  - uses: actions/upload-artifact@v3
    with:
      name: my-test-file
      path: ./test.json
I used actions/upload-artifact so I upload my test.json as artifact and then read it on my machine as a workaround as GitHub hides the outputs.
Yes, if you see *** in the console that doesn't mean that the file didn't change, it's just replaced in the workflows' console & logs.
If the secret is not set to your file, check that it's set properly in your repository, then check jq's version on your runners if you use self-hosted ones.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论