Terraform中cloudflare_list资源反复触发无意义原地更新的解决咨询
问题
使用以下Terraform代码成功创建了Cloudflare IP地址列表:
resource "cloudflare_list" "example" { account_id = "f037e56e89293a057740de681ac9abbe" name = "example_list" description = "example IPs for a list" kind = "ip" item { value { ip = "192.0.2.0" } comment = "one" } item { value { ip = "192.0.2.1" } comment = "two" } }
但每次执行terraform plan时,都会显示要交换列表项,输出如下:
# cloudflare_list.example will be updated in-place ~ resource "cloudflare_list" "example" { id = "xxxxxxxxxxxxxxxxxxxxxx" name = "example_list" # (3 unchanged attributes hidden) ~ item { ~ comment = "one" -> "two" ~ value { ~ ip = "192.0.2.0" -> "192.0.2.1" } } ~ item { ~ comment = "two" -> "one" ~ value { ~ ip = "192.0.2.1" -> "192.0.2.0" } } }
执行terraform apply后,结果显示Apply complete! Resources: 0 added, 1 changed, 0 destroyed.,但再次执行terraform plan仍会出现相同的变更提示,且Cloudflare UI中的列表顺序没有变化。需要解决这个循环问题,让Terraform显示“Your infrastructure is up-to-date”。
使用的环境配置:
Terraform v1.3.3 on linux_amd64 + provider registry.terraform.io/cloudflare/cloudflare v3.26.0
解决方案
方法1:用lifecycle忽略列表项顺序变更
在cloudflare_list资源块中添加lifecycle配置,忽略item属性的顺序变化:
resource "cloudflare_list" "example" { account_id = "f037e56e89293a057740de681ac9abbe" name = "example_list" description = "example IPs for a list" kind = "ip" item { value { ip = "192.0.2.0" } comment = "one" } item { value { ip = "192.0.2.1" } comment = "two" } lifecycle { ignore_changes = [item] } }
注意:此配置会忽略所有item的变更(包括新增、删除、内容修改),后续需修改item时,需临时移除该配置,执行apply后再重新添加。
方法2:用dynamic块+for_each基于唯一值管理列表项
通过定义本地变量存储IP和注释,使用dynamic item配合for_each让Terraform基于IP唯一标识跟踪列表项,而非依赖顺序:
locals { ip_list = [ { ip = "192.0.2.0", comment = "one" }, { ip = "192.0.2.1", comment = "two" } ] } resource "cloudflare_list" "example" { account_id = "f037e56e89293a057740de681ac9abbe" name = "example_list" description = "example IPs for a list" kind = "ip" dynamic "item" { for_each = local.ip_list content { value { ip = item.value.ip } comment = item.value.comment } } }
这种方式下,Terraform会通过IP值识别每个列表项,即使Cloudflare返回的顺序不同,也能正确匹配,不会产生无意义的变更提示。
方法3:升级Cloudflare Provider
当前使用的v3.26.0版本可能存在列表项顺序比对的bug,尝试升级到较新版本:
- 修改
versions.tf中的provider版本约束:
terraform { required_providers { cloudflare = { source = "cloudflare/cloudflare" version = ">= 4.0.0" # 或更新的稳定版本 } } }
- 执行
terraform init -upgrade完成升级,再运行terraform plan检查问题是否解决。
内容的提问来源于stack exchange,提问作者Nagev
相关产品推荐
相关产品推荐

