ssh - GitLab CI 拒绝使用具有写入权限的部署 key 进行推送访问

标签 ssh continuous-integration gitlab yaml gitlab-ci-runner

我添加了一个对我的 GitLab 存储库具有写入权限的部署 key 。我的 .gitlab-ci.yml文件包含:

- git clone git@gitlab.domain:user/repo.git
- git checkout master
- git add myfile.pdf
- git commit -m "Generated PDF file"
- git push origin master

克隆存储库时部署 key 有效。
即使部署 key 具有写入权限,也无法推送。
remote: You are not allowed to upload code.
fatal: unable to access 'https://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@domain/user/repo.git/': The requested URL returned error: 403

最佳答案

我刚遇到同样的问题,看到这个问题没有答案,所以有我的解决方案。

问题

问题是由于git用来推送代码的远程url格式为http(s)://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@git.mydomain.com/group/project.git。 .
此网址使用 http(s)协议(protocol),所以 git 不使用 ssh部署您设置的 key 。

解决方案

解决方法是更改​​远程origin的push url所以它匹配 ssh://git@git.mydomain.com/group/project.git .
最简单的方法是使用 predefined variable CI_REPOSITORY_URL .

这是使用 sed 执行此操作的代码示例:

# Change url from http(s) to ssh
url_host=$(echo "${CI_REPOSITORY_URL}" | sed -e 's|https\?://gitlab-ci-token:.*@|ssh://git@|g')
echo "${url_host}"
# ssh://git@git.mydomain.com/group/project.git

# Set the origin push url to the new one
git remote set-url --push origin "${url_host}"

此外,那些使用 docker executor 的人可能想要 verify the SSH host key正如 deploy keys for docker executor 上的 gitlab 文档所建议的那样.

所以我给出一个更完整的例子对于 docker 执行器 .
代码主要来自ssh deploy keys上的gitlab文档.
在此示例中,私有(private)部署 key 存储在名为 SSH_PRIVATE_KEY 的变量中。 .

create:push:pdf:
  before_script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - echo "${SSH_PRIVATE_KEY}" | tr -d '\r' | ssh-add - > /dev/null
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - git config --global user.email "email@example.com"
    - git config --global user.name "User name"
    - gitlab_hostname=$(echo "${CI_REPOSITORY_URL}" | sed -e 's|https\?://gitlab-ci-token:.*@||g' | sed -e 's|/.*||g')
    - ssh-keyscan "${gitlab_hostname}" >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
  script:
    - git checkout master
    - git add myfile.pdf
    - git commit -m "Generated PDF file"
    - url_host=$(echo "${CI_REPOSITORY_URL}" | sed -e 's|https\?://gitlab-ci-token:.*@|ssh://git@|g')
    - git remote set-url --push origin "${url_host}"
    - git push origin master

关于ssh - GitLab CI 拒绝使用具有写入权限的部署 key 进行推送访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55224376/

相关文章:

git - 如何为具有私有(private) git 子模块的私有(private)仓库设置 GitHub Actions CI 服务?

asp.net - MSBuild:自动收集数据库迁移脚本?

javascript - 通过 Gitlab 部署到 Firebase 来自动化 vue.js 应用程序

ssh - 为 GitHub 设置 SSH key

c++ - 为 c++ 中的传入 ssh 连接提供自定义终端 session

ssh - 如何在 Vagrant 中使用 config.ssh.forward_env?

azure - 发布成功,无法在 Azure Synapse Analytics 中触发

Gitlab:构建后如何在后续作业中使用工件

apache - 如何更正 Apache2 Ubuntu 默认页面显示代替 Gitlab

bash - 在Jenkins管道中的ssh上执行bash -c中的管道或for循环