[英]How to list all items in a list in Terraform and what's the for loop equivalent here?
我是 Terraform 的新手,你能幫我看看 terraform 中的列表嗎?
這是我的代碼
variable "ip_bitbucket" {
type = "list"
}
ip_bitbucket = ["34.199.54.113/32","34.232.25.90/32","34.232.119.183/32","34.236.25.177/32","35.171.175.212/32","52.54.90.98/32","52.202.195.162/32","52.203.14.55/32","52.204.96.37/32","34.218.156.209/32","34.218.168.212/32","52.41.219.63/32","35.155.178.254/32","35.160.177.10/32","34.216.18.129/32","3.216.235.48/32","34.231.96.243/32","44.199.3.254/32","174.129.205.191/32","44.199.127.226/32","44.199.45.64/32","3.221.151.112/32","52.205.184.192/32","52.72.137.240/32"]
並且需要訪問如下列表
resource "aws_security_group_rule "server_rule" {
type = "ingress"
from_port = 443
to_port = 22
protocol = "tcp"
# for each = var.ip_bitbucket
cidr_blocks =
security_group_id = data.aws_security_group.server_sg.id
}
如何訪問 cidr 塊中的變量ip_bitbucket
?
我正在嘗試使用count
和element
但沒有弄清楚
您可以為此使用toset
內置 function [1]:
resource "aws_security_group_rule "server_rule" {
for_each = toset(var.ip_bitbucket)
type = "ingress"
from_port = 443
to_port = 22
protocol = "tcp"
cidr_blocks = [each.value]
security_group_id = data.aws_security_group.server_sg.id
}
[1] https://developer.hashicorp.com/terraform/language/functions/toset
for_each
參數需要一個 map 值(具有任何元素類型)或一組字符串。 您的輸入變量當前被聲明為一個列表,因此它與for_each
不直接兼容。
似乎ip_bitbucket
中元素的順序沒有意義,所以我認為最好的答案是將該變量的類型約束更改為set(string)
,這是對如何使用該值的更准確描述:
variable "ip_bitbucket" {
type = set(string)
}
但是,您可以在單個安全組規則中指定多個 CIDR 塊,因此您實際上可能根本不需要for_each
:
resource "aws_security_group_rule" "server_rule" {
type = "ingress"
from_port = 443
to_port = 22
protocol = "tcp"
cidr_blocks = var.ip_bitbucket
security_group_id = data.aws_security_group.server_sg.id
}
以上將聲明適用於所有給定 CIDR 范圍的單個規則。
如果你仍然想使用for_each
那么你可以使用var.ip_bitbucket
作為for_each
值,一旦你改變了它的類型約束,如上所述:
resource "aws_security_group_rule" "server_rule" {
for_each = var.ip_bitbucket
type = "ingress"
from_port = 443
to_port = 22
protocol = "tcp"
cidr_blocks = [each.value]
security_group_id = data.aws_security_group.server_sg.id
}
請注意,這里的each.value
需要放在方括號中,因為each.value
只是var.ip_bitbucket
中的一個元素,因此它是一個字符串。 cidr_blocks
需要一組字符串。
如果此處未顯示的模塊的某些其他部分確實依賴於var.ip_bitbucket
中元素的特定順序,那么您可以將其聲明為列表,然后將其轉換為for_each
參數中的集合。 但是,只有當您確實需要保留這些元素的順序時,我才會推薦這樣做,因為如果您將它聲明為列表,您的模塊的用戶或未來的維護者可能會認為順序很重要。
variable "ip_bitbucket" {
type = list(string)
}
resource "aws_security_group_rule" "server_rule" {
for_each = toset(var.ip_bitbucket)
type = "ingress"
from_port = 443
to_port = 22
protocol = "tcp"
cidr_blocks = [each.value]
security_group_id = data.aws_security_group.server_sg.id
}
這與前面的示例相同,除了從列表到集合的轉換是使用toset
function 顯式發生的,而不是自動發生的,因為 Terraform 准備了var.ip_bitbucket
的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.