Bitbucket Pipeline中SSH连接失败但本地正常,求助排查
排查Bitbucket Pipeline SSH认证失败问题
核心问题定位
从OpenSSH debug日志来看,系统优先使用了Bitbucket Agent默认的密钥路径/opt/atlassian/pipelines/agent/ssh/id_rsa,而非你通过脚本生成的~/.ssh/id_rsa,导致认证失败。
具体修复&排查步骤
1. 强制指定私钥路径
在SSH连接时显式指定你的私钥,避免系统优先加载Agent默认密钥:
ssh -i ~/.ssh/id_rsa user1@example.com
或者在deploy.sh中添加SSH配置,让目标连接自动使用指定密钥:
mkdir -p ~/.ssh echo -e "Host example.com\n IdentityFile ~/.ssh/id_rsa\n User user1" >> ~/.ssh/config
2. 严格设置私钥权限
SSH对私钥权限要求极高,权限过宽会被直接忽略,解码后必须立即设置正确权限:
echo "$SSH_KEY" | base64 -d > ~/.ssh/id_rsa chmod 600 ~/.ssh/id_rsa chmod 700 ~/.ssh
3. 验证变量传递正确性
在Pipeline中添加调试步骤,确认SSH_KEY变量已正确加载且解码正常:
# bitbucket-pipelines.yml 中插入调试脚本 script: - echo "验证SSH_KEY解码结果:" - echo "$SSH_KEY" | base64 -d | head -2 # 输出私钥前两行确认格式正确
4. 强制仅使用指定密钥(可选)
添加IdentitiesOnly=yes参数,禁止SSH尝试其他未指定的密钥:
ssh -o IdentitiesOnly=yes -i ~/.ssh/id_rsa user1@example.com
5. 核对服务器端日志
再次查看服务器/var/log/auth.log,确认Pipeline发起的连接请求使用的密钥指纹,是否和你本地免密登录的RSA密钥完全一致,排除密钥不匹配的问题。
完整deploy.sh示例片段
#!/bin/bash set -e # 创建并配置.ssh目录权限 mkdir -p ~/.ssh chmod 700 ~/.ssh # 解码密钥并设置严格权限 echo "$SSH_KEY" | base64 -d > ~/.ssh/id_rsa chmod 600 ~/.ssh/id_rsa # 配置SSH连接规则 echo -e "Host example.com\n IdentityFile ~/.ssh/id_rsa\n User user1\n StrictHostKeyChecking no" >> ~/.ssh/config chmod 600 ~/.ssh/config # 测试连接 ssh -o IdentitiesOnly=yes user1@example.com "echo '连接成功'"
内容的提问来源于stack exchange,提问作者kellymandem
相关产品推荐
相关产品推荐

