带变量对象的地形条件动态块



我试图使用对象的变量列表来定义值的类型和默认值,并在动态块中使用它。我知道有一个实验功能,但我想知道如果没有实验功能我该怎么做?

variables.rf

variable "identity" {
type = list(object({
type = string
identity_ids = list(string)
}))
default = [
{
type = null
identity_ids = null
}
]
}

main.tf

resource "azurerm_cognitive_account" "azure" {
# Required
name                = var.name
location            = var.location
resource_group_name = var.resource_group_name
kind                = var.kind
sku_name            = var.sku_name
dynamic "identity" {
for_each = var.identity
content {
type         = identity.value.type
identity_ids = identity.value.identity_ids
}
}
}

用作模块

module "cognitive_account" {
source                = "../modules/cognitive-account"
name                  = "name"
location              = "Australia East"
resource_group_name   = module.rg.name
kind                  = "TextAnalytics"
sku_name              = "S"
custom_subdomain_name = "unique-name"

identity = [{
type = "SystemAssigned"
}]
}

使用这个代码会给我一个错误:

│ Error: Invalid value for module argument
│
│   on main.tf line 66, in module "cognitive_account":
│   66:   identity = [{
│   67:     type = "SystemAssigned"
│   68:   }]
│
│ The given value is not suitable for child module variable "identity" defined at .terraformmodulescognitive_accountvariables.tf:123,1-20: element 0:
│ attribute "identity_ids" is required.

我不确定如何处理省略identity_ids从对象块,我以为默认null会照顾它。

@marcin,感谢您的提示,需要做更多的工作才能使其工作:

variables.tf

variable "identity" {
type = any
description = <<EOT
type = Specifies the type of Managed Service Identity that should be configured on the Cognitive Account. Possible values are SystemAssigned, UserAssigned, SystemAssigned, UserAssigned (to enable both).
identity_ids = A list of IDs for User Assigned Managed Identity resources to be assigned.
EOT
default = null
}

main.tf

resource "azurerm_cognitive_account" "azure" {
# Required
name                = var.name
location            = var.location
resource_group_name = var.resource_group_name
kind                = var.kind
sku_name            = var.sku_name
dynamic "identity" {
for_each = var.identity == null ? [] : [true]
content {
type         = lookup(var.identity, "type", null)
identity_ids = lookup(var.identity, "identity_ids", null)
}
}
}

使用模块

module "cognitive_account" {
source                = "../modules/cognitive-account"
name                  = "name"
location              = "Australia East"
resource_group_name   = module.rg.name
kind                  = "TextAnalytics"
sku_name              = "S"
custom_subdomain_name = "unique-name"
identity = {
type = "SystemAssigned"
}
}

现在不提供标识块时会省略,并且identity变量中的每个对象都可以使用,而不需要指定所有值。

错误不是因为动态块,而是因为您的identity是:

type = list(object({
type = string
identity_ids = list(string)
}))

这意味着identity_ids必需的,但是当您使用您的模块时,您没有提供它:

identity = [{
type = "SystemAssigned"
}]

你必须明确地提供theidentity_ids:

identity = [{
type = "SystemAssigned"
identity_ids = ["somevalue1", "somevalue2"]
}]

最新更新