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

茉莉花

我添加了对我的GitLab存储库具有写访问权限的部署密钥。我的.gitlab-ci.yml文件包含:

- git clone [email protected]:user/repo.git
- git checkout master
- git add myfile.pdf
- git commit -m "Generated PDF file"
- git push origin master

克隆存储库时,deploy键有效。即使部署密钥具有写访问权,也无法进行推送。

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:[email protected]/group/project.git该网址使用http(s)协议,因此git不使用ssh您设置部署密钥。

解决方案是更改遥控器的推入URL,origin使其匹配ssh://[email protected]/group/project.git最简单的方法是使用预定义变量 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://[email protected]/group/project.git

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

另外,那些使用docker executor的用户可能想要按照gitlab文档中关于docker executor的部署密钥的建议验证SSH主机密钥

因此,我为docker executor提供了一个更完整的示例该代码主要来自ssh部署密钥上的gitlab文档在此示例中,私有部署密钥存储在名为的变量内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 protected]"
    - 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章