[英]How to use multiple loops for a resource name in Terraform
I'm looking for a way to dynamically create AWS S3 buckets by looping on two list(string)
type variables.我正在寻找一种通过循环两个
list(string)
类型变量来动态创建 AWS S3 存储桶的方法。 This is what I have so far:这是我到目前为止所拥有的:
variable "network" {
type = list(string)
default = ["blue", "green", "orange"]
}
variable "type" {
type = list(string)
default = ["ClientA", "ClientB"]
}
resource "aws_s3_bucket" "this" {
for_each = var.type
content {
bucket = "${each.key}-${var.network}.mysite.com"
tags = local.tags
}
}
The problem is that I'm not sure how to also get it to loop through var.network
.问题是我不确定如何让它循环通过
var.network
。 Ideally it should create the following buckets from the example above:理想情况下,它应该从上面的示例中创建以下存储桶:
ClientA-blue.mysite.com
ClientA-green.mysite.com
ClientA-orange.mysite.com
ClientB-blue.mysite.com
ClientB-green.mysite.com
ClientB-orange.mysite.com
Does anybody know how I might achieve this?有人知道我如何实现这一目标吗?
What you do is flatten the outcome of some nested for's .您所做的是将一些嵌套for 的结果展平。
locals {
networks = ["blue", "green", "orange"]
types = ["ClientA", "ClientB"]
stuff = flatten([for network in local.networks : [
for type in local.types : [
"${type}-${network}.mysite.com"
]
]])
}
output "stuff" {
value = local.stuff
}
which yields:产生:
Changes to Outputs:
+ stuff = [
+ "ClientA-blue.mysite.com",
+ "ClientB-blue.mysite.com",
+ "ClientA-green.mysite.com",
+ "ClientB-green.mysite.com",
+ "ClientA-orange.mysite.com",
+ "ClientB-orange.mysite.com",
]
In your case, that resource would look like:在您的情况下,该资源如下所示:
resource "aws_s3_bucket" "this" {
for_each = flatten([for network in var.network : [
for type in var.type : [
"${type}-${network}"
]
]])
content {
bucket = "${each.key}.mysite.com"
tags = local.tags
}
}
While an double for
loop may work, I suggest using setproduct
:虽然双
for
循环可能有效,但我建议使用setproduct
:
resource "aws_s3_bucket" "this" {
for_each = toset([for p in setproduct(var.type, var.network) : "${p[0]}-${p[1]}"])
bucket = "${each.key}.mysite.com"
tags = local.tags
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.