【问题标题】:How to allow an ordered list in a custom terraform provider resource?如何在自定义 terraform 提供程序资源中允许有序列表?
【发布时间】:2021-12-28 22:37:04
【问题描述】:

我有一个自定义 terraform 提供程序,其资源将列表作为其输入之一。

这里是有问题的列表:https://github.com/volterraedge/terraform-provider-volterra/blob/main/volterra/resource_auto_volterra_http_loadbalancer.go#L3501

当我声明列表时,它需要设置为多个块,如下所示:

  active_service_policies {
    policies {
      name      = "foobar"
      namespace = "shared"
    }
    policies {
      name      = "batz"
      namespace = "shared"
    }
  }

相反,我希望能够像下面这样声明它:

  active_service_policies {
    policies = [
    {
      name      = "foobar"
      namespace = "shared"
    },
    {
      name      = "batz"
      namespace = "shared"
    }
    ]
  }

这会导致以下错误:

Error: Unsupported argument
  on main.tf line 79, in resource "volterra_http_loadbalancer" "sp":
  79:     policies = [
An argument named "policies" is not expected here. Did you mean to define a block
of type "policies"?

为什么我不能使用有序列表,如何允许使用它?

这个问题是因为policiesType: schema.TypeList, 应该是TypeSet 还是其他一些对象?

【问题讨论】:

标签: terraform hcl terraform-provider


【解决方案1】:

您使用的 Terraform SDK 最初是为 Terraform v0.11 及更早版本设计的,因此它不支持那些旧版本不支持的配置结构,并且 Terraform v0.11 及更早版本不支持列表以您在此处想要的方式的对象。

要使用现代 Terraform 语言的全部功能,您可以改为使用 the newer Plugin Framework 构建您的提供程序,它是围绕现代 Terraform 语言类型系统设计的,尽管由于它们的差异,它目前还不如旧版 SDK 成熟年龄。

在新框架中,您可以声明一个tfsdk.Attribute,它的Attributes 字段设置为tfsdk.ListNestedAttributes 结果:

tfsdk.Attribute{
    Attributes: tfsdk.ListNestedAttributes(
        map[string]tfsdk.Attribute{
            "name": tfsdk.Attribute{
                // ...
            },
            "namespace": tfsdk.Attribute{
                // ...
            },
        },
        tfsdk.ListNestedAttributesOptions{},
    ),

    // ...
}

上述(部分)示例声明了一个属性,该属性需要一个对象列表,其中每个对象本身可以具有namenamespace 属性。

在旧版 SDK 中最接近这一点的是您在示例中显示的块序列。在使用该 SDK 构建的较旧的提供程序中,这里的常见模式是为块提供单数名称 policy,而不是复数名称 policies,以便在配置中更清楚每个块仅声明一个策略顺序。

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 2021-03-14
    • 2020-09-27
    • 2018-11-11
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多