使用Terraform创建DigitalOcean Droplet时遇整数解析错误求助
Terraform创建DigitalOcean Droplet时的整数解析错误
问题描述
我正在学习Terraform,尝试创建DigitalOcean Droplet以部署一个简单的Express应用,测试Droplet创建流程时遇到以下错误:Error creating droplet: json: cannot unmarshal number 2296635920 into Go struct field LinkAction.links.actions.id of type int
开启TF_LOG=DEBUG后得到关键输出:
"links": { "actions": [ { "id": 2296635920, "rel": "create", "href": "https://api.digitalocean.com/v2/actions/2296635920" } ] }
可以看到actions的id值2296635920超出了32位int的限制,导致提供商无法正确解析,但后续问题无从下手。附上我的main.tf配置:
terraform { required_providers { digitalocean = { source = "digitalocean/digitalocean" version = "2.41.0" } } } variable "digitalocean_token" { description = "DigitalOcean API token" type = string } provider "digitalocean" { token = var.digitalocean_token } resource "digitalocean_ssh_key" "default" { name = "ssh-key" public_key = file("~/.ssh/id_rsa.pub") } resource "digitalocean_droplet" "web" { name = "express-app" size = "s-1vcpu-1gb" image = "ubuntu-24-04-x64" region = "ams3" ssh_keys = [ digitalocean_ssh_key.default.fingerprint ] connection { type = "ssh" host = self.ipv4_address user = "root" private_key = file("~/.ssh/id_rsa.pub") } provisioner "remote-exec" { inline = [ "apt-get update", "apt-get install -y nodejs npm", "npm install -g pm2", "mkdir /app", "echo 'Deploying application...'", "cp -r /tmp/my-express-app/* /app/", "cd /app && npm install", "pm2 start app.js --name my-express-app", "pm2 startup", "pm2 save" ] } }
问题分析与解决
根源判断
这个问题是Terraform DigitalOcean提供商的版本bug,和你的配置无关。
DigitalOcean的API返回的action ID数值已经增长到超过32位整数的最大值(2147483647),而你使用的2.41.0版本提供商代码中,将LinkAction.links.actions.id定义为32位int类型,导致JSON解析时出现类型不匹配的错误。
解决步骤
- 升级DigitalOcean提供商版本:将版本号改为2.42.0及以上,该版本已将action ID的类型改为64位int(int64),兼容更大的数值。修改
terraform块:
terraform { required_providers { digitalocean = { source = "digitalocean/digitalocean" version = ">= 2.42.0" } } }
- 执行升级命令:运行
terraform init -upgrade完成提供商版本升级,之后重新执行terraform apply即可。
额外配置修正
你的connection块中存在一个小问题:private_key引用的是公钥文件~/.ssh/id_rsa.pub,SSH连接需要使用私钥,应改为:
connection { type = "ssh" host = self.ipv4_address user = "root" private_key = file("~/.ssh/id_rsa") }
这个问题和当前报错无关,但会导致后续远程执行provisioner失败,建议一并修正。
内容的提问来源于stack exchange,提问作者Magician
相关产品推荐
相关产品推荐

