为何在Terraform中添加schema.TypeSet元素会触发资源替换?
为何添加schema.TypeSet元素会触发Terraform资源替换?
背景
我们正在构建一个新的Terraform Provider,其schema定义如下:
"foo": { Type: schema.TypeInt, ... }, "bar": { Type: schema.TypeSet, Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "xxx": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validation.StringIsNotEmpty, }, "yyy": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validation.StringIsNotEmpty, }, "zzz": { Type: schema.TypeInt, Required: true, ForceNew: true, }, }, }, },
将资源配置从修改前:
resource "aaa" "before" { foo = 2 }
更新为修改后:
resource "aaa" "before" { foo = 2 bar { xxx = "aaa" yyy = "bbb" zzz = 3 } }
此时Terraform提示:
+ bar { # forces replacement + xxx = "aaa" + yyy = "bbb" + zzz = 3 }
原因解析
核心原因在于bar集合内的所有字段(xxx、yyy、zzz)都设置了ForceNew: true。
Terraform对嵌套集合(如TypeSet)的变更逻辑是:当集合内发生元素新增、删除或修改时,会检查元素内字段的ForceNew属性。只要嵌套元素中存在带ForceNew: true的字段,哪怕只是新增一个元素,Terraform都会判定该变更需要重建整个资源——嵌套字段的ForceNew会向上传递,影响父级集合的变更行为,即便父级的bar本身未设置ForceNew: true。
直白来说,既然嵌套资源里的每个字段都要求必须重建资源才能修改,那么新增这个嵌套元素的操作,自然会触发整个资源的替换。
内容的提问来源于stack exchange,提问作者Ivan Petrov
相关产品推荐
相关产品推荐

