gpt4 book ai didi

azure - 如何从 Terraform 中的 CSV 列中提取不同的值?

转载 作者:行者123 更新时间:2023-12-03 07:00:08 25 4
gpt4 key购买 nike

我有一个 CSV,其中包含多个网络安全规则。我正在尝试使用此列表创建 NSG。但是,列表中存在重复项,导致创建失败。如何从 Terraform 中的 CSV 列中提取不同的值?

locals {
csv_data = <<-CSV
id,nsgname,rgname,rule,priority
1,nsg-one,rg-test,rule1,100
2,nsg-one,rg-test,rule2,110
3,nsg-one,rg-test,rule3,120
4,nsg-one,rg-test,rule4,130
5,nsg-one,rg-test,rule5,100
6,nsg-one,rg-test,rule6,110
7,nsg-one,rg-test,rule7,120
8,nsg-one,rg-test,rule8,130
9,nsg-two,rg-test,rule9,2300
10,nsg-two,rg-test,rule10,2300
11,nsg-two,rg-test,rule11,2140
12,nsg-two,rg-test,rule12,2140
13,nsg-three,rg-test,rule13,2100
14,nsg-three,rg-test,rule14,2110
15,nsg-three,rg-test,rule15,2120
16,nsg-three,rg-test,rule16,2130
17,nsg-three,rg-test,rule17,2100
18,nsg-three,rg-test,rule18,2130
19,nsg-three,rg-test,rule19,2140
20,nsg-three,rg-test,rule20,2140
21,nsg-four,rg-test,rule21,2300
22,nsg-four,rg-test,rule22,2140
23,nsg-four,rg-test,rule23,2140
CSV

nsgss = csvdecode(local.csv_data)
}

resource "azurerm_network_security_group" "tf_network_security_groups" {
for_each = { for nsg in local.nsgss : nsg.id => nsg }

name = format("nsg-%s", each.value.nsgname)
location = "uksouth"
resource_group_name = "rg-test"
}

我假设本练习存在资源组 rg-test。如果您想测试它,那么您需要手动或使用以下配置创建它。

resource "azurerm_resource_group" "tf_resource_group" {
name = "rg-test"
location = "uksouth"
}

最佳答案

可以使用 splat 语法从 CSV 中提取列

dist = distinct(local.nsgss.*.nsgname)

所以我之前的示例需要更改为以下内容

csv_data = <<-CSV
id,nsgname,rgname,rule,priority
1,nsg-one,rg-test,rule1,100
2,nsg-one,rg-test,rule2,110
3,nsg-one,rg-test,rule3,120
4,nsg-one,rg-test,rule4,130
5,nsg-one,rg-test,rule5,100
6,nsg-one,rg-test,rule6,110
7,nsg-one,rg-test,rule7,120
8,nsg-one,rg-test,rule8,130
9,nsg-two,rg-test,rule9,2300
10,nsg-two,rg-test,rule10,2300
11,nsg-two,rg-test,rule11,2140
12,nsg-two,rg-test,rule12,2140
13,nsg-three,rg-test,rule13,2100
14,nsg-three,rg-test,rule14,2110
15,nsg-three,rg-test,rule15,2120
16,nsg-three,rg-test,rule16,2130
17,nsg-three,rg-test,rule17,2100
18,nsg-three,rg-test,rule18,2130
19,nsg-three,rg-test,rule19,2140
20,nsg-three,rg-test,rule20,2140
21,nsg-four,rg-test,rule21,2300
22,nsg-four,rg-test,rule22,2140
23,nsg-four,rg-test,rule23,2140
CSV

nsgss = csvdecode(local.csv_data)

dist = distinct(local.nsgss.*.nsgname)
}

resource "azurerm_network_security_group" "tf_network_security_groups" {
for_each = toset(local.dist)

name = each.key
location = "uksouth"
resource_group_name = "rg-test"
}

关于azure - 如何从 Terraform 中的 CSV 列中提取不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72528703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com