You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ansible无法Ping通Terraform创建的DigitalOcean Droplets

问题排查与解决方案

1. 确认Ansible使用的SSH密钥路径

Terraform生成的密钥文件可能没被Ansible正确识别,按以下方式配置:

  • 在inventory.txt中明确指定私钥路径,示例:
    [droplets]
    droplet1 ansible_host=1.2.3.4 ansible_ssh_private_key_file=./ansible/your_private_key
    droplet2 ansible_host=5.6.7.8 ansible_ssh_private_key_file=./ansible/your_private_key
    
  • 或者在ansible.cfg的[defaults]段添加:
    private_key_file = ./ansible/your_private_key
    

2. 彻底修复密钥文件权限

手动改权限后仍有问题?确认这两点:

  • 密钥文件权限必须是600,执行:
    chmod 600 ./ansible/your_private_key
    
  • 确保文件属主是当前执行Ansible的用户,避免权限继承冲突:
    chown $USER:$USER ./ansible/your_private_key
    
    提示:Terraform的local_file资源可以直接设置file_permission = "0600",避免后续手动操作。

3. 验证公钥匹配性

直接SSH能连说明本地私钥有效,但要确认Terraform把正确的公钥传到了Droplet:

  • 登录任意Droplet,查看授权密钥:
    cat ~/.ssh/authorized_keys
    
  • 对比本地生成的公钥(私钥文件同名加.pub)内容,确保完全一致,无换行或字符缺失。

4. 指定正确的Ansible连接用户

DigitalOcean Droplet默认用户是ubuntu(Ubuntu镜像)或root(部分镜像),Ansible默认用当前本地用户连接,大概率不匹配:

  • 在inventory.txt中添加用户字段,示例:
    droplet1 ansible_host=1.2.3.4 ansible_user=ubuntu ansible_ssh_private_key_file=./ansible/your_private_key
    
  • 或者在ansible.cfg中全局设置:
    [defaults]
    remote_user = ubuntu
    

5. 用详细日志定位根源

执行带最高级verbose的ping命令,抓具体错误细节:

ansible all -m ping -vvvv

重点关注:

  • 实际加载的私钥路径是否正确
  • 连接时使用的用户名是否正确
  • SSH握手阶段的公钥验证失败原因(比如公钥不匹配、用户无权限)

6. 检查Terraform密钥生成逻辑

确保local_file资源没有破坏私钥格式:

  • 示例正确配置:
    resource "local_file" "ssh_private_key" {
      filename        = "./ansible/your_private_key"
      content         = tls_private_key.droplet_key.private_key_pem
      file_permission = "0600"
    }
    
    避免通过字符串拼接生成私钥内容,直接引用private_key_pem确保格式完整。

内容的提问来源于stack exchange,提问作者dokichan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:45:41