我遇到了 2 terraform 動態語法,只是想知道有什么區別?
dynamic "storage_account" {
for_each = var.storage_account == null ? {} : var.storage_account
content {
name = storage_account.value.name
type = storage_account.value.type
account_name = storage_account.value.account_name
share_name = storage_account.value.share_name
access_key = storage_account.value.access_key
mount_path = storage_account.value.mount_path
}
}
dynamic "backup" {
for_each = var.app_service_backup != null ? [1] : []
content {
name = var.app_service_backup.name
enabled = true
storage_account_url = var.app_service_backup.storage_account_url
schedule {
frequency_interval = var.app_service_backup.frequency_interval
frequency_unit = var.app_service_backup.frequency_unit
}
}
}
和變數是
variable "storage_account" {
description = <<EOF
(Optional) - One or more storage_account blocks as defined below.
(Required) name - The name of the storage account identifier.
(Required) type - The type of storage. Possible values are AzureBlob and AzureFiles.
(Required) account_name - The name of the storage account.
(Required) share_name - The name of the file share (container name, for Blob storage).
(Required) access_key - The access key for the storage account.
(Required) mount_path - The path to mount the storage within the site's runtime environment.
EOF
type = map(object({
name = string
type = string
account_name = string
share_name = string
access_key = string
mount_path = string
}))
default = null
}
variable "app_service_backup" {
description = <<EOF
(Optional) - The app service backup block supports the following:
(Required) name - Specifies the name for this Backup.
(Required) storage_account_url - The SAS URL to a Storage Container where Backups should be saved.
(Required) frequency_interval - Sets how often the backup should be executed.
(Required) frequency_unit - Sets the unit of time for how often the backup should be executed. Possible values are Day or Hour.
EOF
type = object({
name = string
storage_account_url = string
frequency_interval = number
frequency_unit = string
})
default = null
}
注意它使用的第一個動態 storage_account 如何使用 storage_account.value.name 和第二個“備份”是如何使用 var.app_service_backup.name
對于第二個,我可以使用 backup.value.name 嗎?
uj5u.com熱心網友回復:
當您在 TF 中有條件運算式時,例如
condition ? true_val : false_val
true_val并且false_val必須是同一型別。
所以在你的第一個例子中:
for_each = var.storage_account == null ? {} : var.storage_account
var.storage_account是地圖,所以true_val也必須是map。在這種情況下,它是一個空的map {}。由于此地圖沒有任何元素,for_each因此不會運行。
在您的第二個示例中,也可以使用地圖,但串列寫起來更短,所以您有(只是一個約定):
for_each = var.app_service_backup != null ? [1] : []
where[]是一個空串列,并且[1]是一個包含一個元素的串列。所以for_each只會運行一次。串列中元素的[1]值為1,但實際上并不重要。它可以是任何值,只要串列的長度不為零。
更新。
您不能backup.value.name在第二個示例中使用,因為在這種情況下,它的值backup.value實際上1是來自[1]. for_each此外,強行更改您的使用是沒有意義的var.app_service_backup,因為它只是一個值。它不需要迭代。因此,您只需直接訪問它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482570.html
標籤:天蓝色 地形 terraform-provider-azure
