git 推送在 gitlab ci/cd 期间所做的更改

git push changes made during gitlab ci/cd

我正在尝试在我正在开发的管道中的工作期间更改文件,然后将该更改提交到同一项目的主分支,但我很难让它工作.

这是工作:

maven_next_release:
  stage: next-version
  dependencies:
    - maven_test
  before_script:
    - apt update && apt-get install git perl-base -yrelease-demo.git
    - git config --global user.email "${GITLAB_USER_EMAIL}"
    - git config --global user.name "${GITLAB_USER_NAME}"
    - git fetch
    - git checkout master
  script:
    - cat VERSION
    - perl -i -pe 's/\d+\.\d+\.\K(\d+)/ +1 /e' VERSION
    - echo $(cat VERSION)-SNAPSHOT > VERSION
    - cat VERSION
    - git add VERSION
    - git commit -m "[skip ci]New version $(cat VERSION)"
    - git push https://${GIT_USERNAME}:${GIT_PASSWORD}@gitlab.com/myproject/release-demo.git
  only:
    - tags
  except:
- branches

因此,除了 push 命令外,一切似乎都正常。这是日志:

$ git push https://${GIT_USERNAME}:${GIT_PASSWORD}@gitlab.com/myproject/release-demo.git
remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab.com/myproject/release-demo.git/'

我真的不确定该怎么做,我阅读了有关设置 SSH 密钥的信息,这样我就不必传递用户名和密码,但我不确定如何为运行程序生成 SSH 密钥。

GitLab CI(与 GitHub Actions 不同)不会自动授权您在结帐时推送代码。

要实现您想要的效果,您需要生成 Git 推送令牌并将其秘密传递到您的管道。

示例 - 您可以在此处参考我的示例 helm cd 项目 - https://gitlab.com/taleodor/sample-helm-cd/

特别是,在文档中搜索“GIT_PUSH_TOKEN”,然后实际的 git 提交部分在“.git-script”块中的 https://gitlab.com/taleodor/sample-helm-cd/-/blob/master/.gitlab-ci.yml 中。

您可以使用 ssh_key 而不是使用 https。 您可以在共享运行器或私有运行器 gitlabci 中的容器内添加 ssh_key。

所以我解决了我的问题:

首先,我之前在我的 ci/cd、GIT_USER 和 GIT_PASSWORD 中创建了两个环境变量,我将它们作为受保护变量,所以我不得不取消选择那个,只是将它们标记为屏蔽。

其次我修改了我的工作:

maven_next_release:
  stage: next-version
  dependencies:
    - maven_test
  before_script:
    - apt update && apt-get install git perl-base -y
    - git clone http://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/myteam/release-demo.git &> /dev/null
    - cd release-demo
    - git config --global user.email "${GITLAB_USER_EMAIL}"
    - git config --global user.name "${GITLAB_USER_NAME}"
  script:
    - cat VERSION
    - perl -i -pe 's/\d+\.\d+\.\K(\d+)/ +1 /e' VERSION
    - echo $(cat VERSION)-SNAPSHOT > VERSION
    - cat VERSION
    - git add VERSION
    - git commit -m "[skip ci]Version $(cat VERSION)"
    - git push "https://${GIT_USERNAME}:${GIT_PASSWORD}@${CI_REPOSITORY_URL#*@}" HEAD:master
  only:
    - tags
  except:
    - branches

至此,我的管道终于可以正常工作了,可以将更改推送到 master 分支。