首页 > 解决方案 > 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?

标签: goterraform

解决方案


您可以使用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),
            },
        },
    }
}

推荐阅读