我添加了一个对我的 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/