当cURL包含变量时,GitLab管道中GitLab API的cURL命令成功,返回[0字节数据]

ntjbwcob  于 2022-11-13  发布在  Git
关注(0)|答案(1)|浏览(204)

我有一个GitLab管道,它应该生成一个包含myrepository目录结构校验和的文件last_changes.txt,并将该文件提交到myrepository中的一个新分支。myrepository是一个不同于gitlab管道运行的仓库。
校验和使用cksum databases/* | sort构建并存储在一个变量中,然后在cURL命令中将该变量提交给GitLab API,以更新存储库(https://docs.gitlab.com/ee/api/repository_files.html#update-existing-file-in-repository)中的现有文件。
管道如下所示:

write-status:
  stage: post-build
  image: myrepo.domain.com/myimage
  script:
    - git clone --branch $CI_COMMIT_BRANCH https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.domain.com/project/myrepository.git
    - cd myrepository
    - |
      CHANGED_FILES=$(cksum databases/* | sort) 
      echo $CHANGED_FILES
      curl -v -w --request PUT --header 'PRIVATE-TOKEN: myPrivateToken' \
      --header "Content-Type: application/json" \
      --data "{\"branch\":\"newchanges\", \"start_branch\":\"main\", \"content\":\"${CHANGED_FILES}\", \"commit_message\":\"update file with checksum\"}" \
      "https://gitlab.domain.com/api/v4/projects/2808/repository/files/ressources%2Flast_changes1%2Etxt"    
  when: on_success

如果我从本地Git Bash执行命令,提交就可以工作,分支也会被创建。如果我在本地主机上执行存储为shell脚本的命令,提交也可以工作,分支也会被创建。但是,如果在GitLab管道中的脚本部分执行相同的命令,(如上面的代码块所示),cURL命令成功,返回[0字节数据],但既未创建提交,也未创建分支(输出如下图所示)。这种失败似乎只在JSON内容作为变量添加到cURL命令(cURL包含变量)时发生。如果JSON内容是静态字符串,则一切都正常。
这个错误似乎发生在不同的linux发行版上(在GitLab pipeline中用alpine 3.16和rhel 8 docker映像进行测试)。
有没有办法让GitLab管道接受cURL命令中的变量?
GitLab Pipeline Status with 0 bytes data

camsedfj

camsedfj1#

有趣的问题。
我设置了一个test repo,在其中我能够通过用一个更容易处理的窗体替换JSON-bash-escaping来解决这个问题。
旁注:如果我没有弄错的话,curl命令中的-w需要一个参数,可能是问题的一部分。

commit_variable:
  stage: build
  script: - |
        CHANGED_FILES=$(cksum /usr/bin/* | sort)
        echo $CHANGED_FILES
        curl -v --request PUT --header "PRIVATE-TOKEN: ${TOKEN}" \
            -F "branch=main" \
            -F "content=${CHANGED_FILES}" \
            -F "commit_message=changed files as variable" \
            "https://gitlab.com/api/v4/projects/38716506/repository/files/as_variable%2Etxt"

作为附加测试,我用一个文件替换了环境变量CHANGED_FILES,但结果是相同的。

commit_file:
  stage: build
  script: - |
        cksum /usr/bin/* | sort > /tmp/changed_files.txt
        cat /tmp/changed_files.txt
        curl -v --request PUT --header "PRIVATE-TOKEN: ${TOKEN}" \
            -F "branch=main" \
            -F "content=</tmp/changed_files.txt" \
            -F "commit_message=changed files as file" \
            "https://gitlab.com/api/v4/projects/38716506/repository/files/as_file%2Etxt"

请参阅完整的.gitlab-ci.yml档案。

相关问题