Terraform-在循环中有条件地创建资源 [英] Terraform - conditionally creating a resource within a loop
问题描述
是否可以将资源创建与循环(使用计数)结合起来,并根据映射的值有条件地跳过某些资源?
Is it possible to combine resource creation with a loop (using count) and conditionally skip some resources based on the value of a map?
我知道我们可以分别做这些事情:
I know we can do these things separately:
- 使用count循环创建资源.
- 使用变量/计数替代方法(代替"if"语句)有条件地创建资源
为说明起见,我说有一张地图列表:
To illustrate lets say I have a list of maps:
variable "resources" {
type = "list"
default = [
{
name = "kafka"
createStorage = true
},
{
name = "elastic"
createStorage = false
},
{
name = "galera"
createStorage = true
}
]
}
我可以遍历以上列表,并使用资源中的计数"创建三个资源:
I can iterate over the over the above list and create three resources using 'count' within the resource:
resource "azurerm_storage_account" "test" {
name = "test${var.environment}${lookup(var.resources[count.index], "name")}sa"
location = "${var.location}"
resource_group_name = "test-${var.environment}-vnet-rg"
account_tier = "Standard"
account_replication_type = "GRS"
enable_blob_encryption = true
count = "${length(var.resources)}"
}
但是,我还想跳过 createStorage = false
的资源的创建.因此,在上面的示例中,我想创建两个存储帐户,但是跳过了弹性"存储帐户.这可能吗?
However, I want to also skip creation of a resource where createStorage = false
. So in the above example I want to create two storage accounts but the 'elastic' storage account is skipped.
Is this possible?
推荐答案
在terraform 0.12.x中,您可以过滤掉 createStorage = true
的列表,并将其用于计数表达式
In terraform 0.12.x you can filter out the list where createStorage=true
and use that for your count expression
variable "resources" {
type = "list"
default = [
{
name = "kafka"
createStorage = true
},
{
name = "elastic"
createStorage = false
},
{
name = "galera"
createStorage = true
}
]
}
locals {
resources_to_create = [
for resource in var.resources :
resource
if resource.createStorage
]
}
resource "azurerm_storage_account" "test" {
count = length(local.resources_to_create)
name = "test${var.environment}${lookup(local.resources_to_create[count.index], "name")}sa"
location = var.location
resource_group_name = "test-${var.environment}-vnet-rg"
account_tier = "Standard"
account_replication_type = "GRS"
enable_blob_encryption = true
}
这篇关于Terraform-在循环中有条件地创建资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!