[英]Terraform: How do I use for_each over a comma-delimited string in a dynamic block?
I am writing an Azure Function app module which is causing me some trouble.我正在写一个 Azure Function 应用程序模块,这给我带来了一些麻烦。 I want to add multiple ip_restriction blocks using a for_each, iterating over a comma-delimited string, but I'm missing out on something here.
我想使用 for_each 添加多个 ip_restriction 块,迭代以逗号分隔的字符串,但我在这里遗漏了一些东西。
Given the following block (with random IP CIDR blocks)给定以下块(随机 IP CIDR 块)
resource "azurerm_windows_function_app" "this" {
...
dynamic "ip_restriction" {
for_each = split(",", "1.2.3.4/28,2.3.4.5/28")
content {
ip_address = {
ip_address = ip_restriction.value
}
}
}
...
I get the following error:我收到以下错误:
Inappropriate value for attribute "ip_address": string required
I get the error twice which tells me that the iterator has tried, and failed twice to retrieve the value using '.value'我收到两次错误,告诉我迭代器已经尝试过,但两次都失败了,无法使用“.value”检索值
I've read https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks (of course) and tried various things for a few hours now without being able to figure out why 'value' seems empty.我已经阅读了 https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks (当然)并尝试了几个小时的各种事情,但无法弄清楚为什么“价值”似乎是空的。
How do I retrieve the distinct CIDR address if.value isn't the right thing to do?如果.value 不是正确的做法,我该如何检索不同的 CIDR 地址?
The for_each
meta-argument accepts a map or a set of strings . for_each
元参数接受map 或一组字符串。 What you are currently providing is a list of strings .您目前提供的是一个字符串列表。 If you are not hardcoding the values as in your example, you could create a local variable:
如果您没有像示例中那样对值进行硬编码,则可以创建一个局部变量:
locals {
ip_addresses = split(",", "1.2.3.4/28,2.3.4.5/28")
}
Then, in the dynamic
block, you can use that local variable and cast it to a set with toset
[1]:然后,在
dynamic
块中,您可以使用该局部变量并将其转换为带有toset
[1] 的集合:
resource "azurerm_windows_function_app" "this" {
...
dynamic "ip_restriction" {
for_each = toset(local.ip_addresses)
content {
ip_address = ip_restriction.value
}
}
...
If you do not want to do that, you can do the conversion like this:如果你不想这样做,你可以像这样进行转换:
resource "azurerm_windows_function_app" "this" {
...
dynamic "ip_restriction" {
for_each = toset(split(",", "1.2.3.4/28,2.3.4.5/28"))
content {
ip_address = ip_restriction.value
}
}
...
[1] https://developer.hashicorp.com/terraform/language/functions/toset [1] https://developer.hashicorp.com/terraform/language/functions/toset
Dammit... A collegue of mine found the error, it was sitting approx.该死的...我的一个同事发现了这个错误,它大约坐着。 40 inches from the keyboard:o)
距键盘 40 英寸:o)
It was a syntax beef, I had wrapped the "ip_address" block in an "ip_address" block这是语法问题,我将“ip_address”块包装在“ip_address”块中
The correct code is:正确的代码是:
dynamic "ip_restriction" {
for_each = split(",", var.ip_restriction_allow_ip_range)
content {
ip_address = ip_restriction.value
name = "github_largerunner"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.