go - Terraform 提供者应该如何处理在服务器端应用的默认值?
问题描述
背景:我正在实现(我的第一个)Terraform 插件/提供程序作为对现有公共 API 的包装器。
API 中的创建操作之一指定了一个整数字段,该字段采用正值或-1
作为默认值。如果您-1
在创建 API 调用中指定,则该值将被服务器端的某个默认值(例如field = 1000
)替换,并1000
从现在开始存储。
如果我将此呈现给我的 Terraform 插件 ( terraform apply
):
resource "something" "mysomething" {
name = "someName"
field = -1
}
调用不是幂等的。Terraform 继续出现变化,随后提供:
# something.mysomething will be updated in-place
~ resource "something" "mysomething" {
id = "165-1567498530352"
name = "someName"
~ field = 1000 -> -1
}
Plan: 0 to add, 1 to change, 0 to destroy.
如何处理这样的 API?
解决方案
您可以使用DiffSuppressFunc
模式属性上的标志来有条件地抑制差异,以便 Terraform 不会选择对差异做任何事情。
像这样的东西应该适合你:
package something
import (
"github.com/hashicorp/terraform/helper/schema"
)
func somethingSomething() *schema.Resource {
return &schema.Resource{
// ...
Schema: map[string]*schema.Schema{
// ...
"field": {
Type: schema.TypeInt,
Optional: true,
Default: -1,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if new == "-1" {
return true
}
return false
},
},
},
}
}
马丁的答案可能通过使用Computed
标志和制作属性提供了更好的选择Optional
。为了使它正常工作,您需要防止人们指定-1
为 this 的值,您可以ValidateFunc
使用核心 SDK 中预定义验证列表中的IntAtLeast
验证器使用 a 来执行此操作:
package something
import (
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)
func somethingSomething() *schema.Resource {
return &schema.Resource{
// ...
Schema: map[string]*schema.Schema{
// ...
"field": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntAtLeast(1),
},
},
}
}
推荐阅读
- xml - Sulu:在哪里放置自定义实体的 XML 文件?
- ios - 如何更改 M1 Mac 的 Cocoapods 源
- ajax - 从 AJAX 获取受 SSO 保护的 XHR 资源
- laravel - 如何在没有任何付款的情况下在 Braintree 客户中添加一个贝宝帐户?
- android - 如何在kotlin协程中通过ok http从url下载pdf
- continuous-integration - 如何在 GitLab CI/CD 中设置 TestCafe 工件?
- javascript - TypeError:无法读取未定义的属性“拆分”,如何检查参数是否可以拆分?
- laravel - Laravel - 如何解决 whereDate 函数问题
- dotnetnuke - 我们如何按 2sxc 中的热门新闻对新闻进行排序?
- python - 如何识别具有不同背景、大小和尺寸的图像中的相同对象