使用TypeSet时,Terraform表示哈希索引是根据集合的值计算的。我有一个用Go编写的Terraform,它使用Terraform提供者Go SDK,我目前需要在测试中对这些索引值进行硬编码。能否避免硬编码Terraform提供程序测试中的值?
Terraform文档说明如下,但不提供有关如何计算散列索引值或避免计算它们的信息。
TypeSet项以状态存储,其索引值由集合属性的哈希值计算。
参考文献: Terraform:https://www.terraform.io/plugin/sdkv2/schemas/schema-types
下面是文档中提供的示例,其中1061987227和493694946是自动生成的散列索引值。
"ingress.#": "2",
"ingress.1061987227.cidr_blocks.#": "1",
"ingress.1061987227.cidr_blocks.0": "10.0.0.0/8",
"ingress.1061987227.description": "",
"ingress.1061987227.from_port": "80",
"ingress.1061987227.ipv6_cidr_blocks.#": "0",
"ingress.1061987227.protocol": "tcp",
"ingress.1061987227.security_groups.#": "0",
"ingress.1061987227.self": "false",
"ingress.1061987227.to_port": "9000",
"ingress.493694946.cidr_blocks.#": "2",
"ingress.493694946.cidr_blocks.0": "0.0.0.0/0",
"ingress.493694946.cidr_blocks.1": "10.0.0.0/8",
"ingress.493694946.description": "",
"ingress.493694946.from_port": "80",
"ingress.493694946.ipv6_cidr_blocks.#": "0",
"ingress.493694946.protocol": "tcp",
"ingress.493694946.security_groups.#": "0",
"ingress.493694946.self": "false",
"ingress.493694946.to_port": "8000",目前,在我的Go测试中,我硬编码了我想避免的散列索引值。下面是带有3个硬编码索引值的摘录:368698502、1552086545和3172309932
resource.TestCheckResourceAttr(resourceName, "workspace_configs.368698502.client_ip_header", "Fastly-Client-IP"),
resource.TestCheckResourceAttr(resourceName, "workspace_configs.368698502.instance_location", "advanced"),
resource.TestCheckResourceAttr(resourceName, "workspace_configs.368698502.listener_protocols.#", "1"),
resource.TestCheckResourceAttr(resourceName, "workspace_configs.368698502.listener_protocols.1552086545", "https"),
resource.TestCheckResourceAttr(resourceName, "workspace_configs.368698502.routes.#", "1"),
resource.TestCheckResourceAttr(resourceName, "workspace_configs.368698502.routes.3172309932.certificate_ids.#", "0"),
resource.TestCheckResourceAttr(resourceName, "workspace_configs.368698502.routes.3172309932.connection_pooling", "true"),完整的代码在这里:test.go
是否有办法避免对索引值进行硬编码?例如,是否可以创建一个函数来满足与CheckResourceAttrWithFunc一起使用的TestCheckResourceAttrWith接口
发布于 2022-09-13 19:19:14
这些哈希值是SDKv2继续使用的较旧版本的Terraform的保留值,因此使用它构建的提供程序可以与这些旧版本的Terraform保持兼容。
resource.TextCheckResourceAttr是一个助手函数,它返回一个resource.TestCheckFunc值,它实际上只是引用具有以下签名的函数的命名类型:
func(*terraform.State) error在resource包中还有许多其他帮助函数返回测试检查函数,其中一些函数专门用于描述有关集合的断言,同时避免提及特定的哈希键:
resource.TestCheckTypeSetElemAttrresource.TestCheckTypeSetElemAttrPairresource.TestCheckTypeSetElemNestedAttrsresource.TestMatchTypeSetElemNestedAttrs我建议首先为每个文档检查文档,看看它是否与您想要编写的断言相匹配。
如果发现它们都不符合您需要描述的规则,则回退是编写与上述签名匹配的自己的函数,然后可以使用任意逻辑来分析给定*terraform.State值中的数据。
您可以使用预定义的测试检查函数帮助器作为如何使用该API的示例。尽管在resource包中实现它的方式存在一些间接的问题,但是一般的模式是:
is是指向terraform.InstanceState对象的指针,其属性位于Attributes映射中。
您将在这里找到原始键,包括希望避免硬编码的散列值,因此通常需要编写遍历所有属性的逻辑,以查找与特定前缀匹配的属性,然后可能还匹配特定的后缀,以确定您找到了哪个叶属性,然后只对键与相关条件匹配的值进行断言。https://stackoverflow.com/questions/73682537
复制相似问题