Gitlab CI部署报错:/home/gitlab-runner/.ssh/ssh-key.pem权限拒绝
问题:GitLab CI/CD流水线部署时出现Permission denied错误
错误场景
配置GitLab项目CD流水线时触发以下错误:
bash: line 151: /home/gitlab-runner/.ssh/ssh-key.pem: Permission denied
清理项目目录及文件变量后,任务仍因退出状态1失败。
提供的gitlab-ci.yml配置
default: image: amazonlinux:latest deploy-prod: only: - main stage: deploy before_script: - ls -la - pwd - 'which ssh-agent || ( yum update -y && yum install openssh-client -y )' - eval $(ssh-agent -s) - mkdir -p ~/.ssh - chmod 700 ~/.ssh - cat $SSH_KEY_EC2 - echo "$(cat $SSH_KEY_EC2)" >> ~/.ssh/ssh-key.pem - chmod 400 ~/.ssh/ssh-key.pem - cat ~/.ssh/ssh-key.pem - echo -e "Host * StrictHostKeyChecking no " > ~/.ssh/config - yum update -y - apt-get -y install rsync script: - >- ...
解决方案
1. 修正文件所有权问题
GitLab Runner以gitlab-runner用户执行任务,需确保.ssh目录及文件归该用户所有,在chmod 400后添加:
- chown -R gitlab-runner:gitlab-runner ~/.ssh
2. 简化密钥写入逻辑
避免嵌套命令导致的权限异常,将密钥写入命令改为:
- echo "$SSH_KEY_EC2" > ~/.ssh/ssh-key.pem
(用>而非>>,防止重复写入损坏密钥)
3. 修复包管理器命令错误
amazonlinux使用yum而非apt-get,将安装rsync的命令改为:
- yum install -y rsync
4. 检查变量配置
确保GitLab项目中SSH_KEY_EC2变量:
- 若main分支是受保护分支,勾选"Protect variable";否则无需勾选
- 变量类型选择Variable而非File,直接用
$SSH_KEY_EC2读取即可
修改后的before_script示例
before_script: - ls -la - pwd - 'which ssh-agent || ( yum update -y && yum install openssh-client -y )' - eval $(ssh-agent -s) - mkdir -p ~/.ssh - chmod 700 ~/.ssh - echo "$SSH_KEY_EC2" > ~/.ssh/ssh-key.pem - chmod 400 ~/.ssh/ssh-key.pem - chown -R gitlab-runner:gitlab-runner ~/.ssh - echo -e "Host *\n\tStrictHostKeyChecking no\n" > ~/.ssh/config - yum install -y rsync
内容的提问来源于stack exchange,提问作者Jhovanny
相关产品推荐
相关产品推荐

