这里是Terraform的新手。
我想使用for_each
遍历一个列表,但似乎键和值是相同的:
provider "aws" {
profile = "default"
region = "us-east-1"
}
variable "vpc_cidrs" {
default = ["10.0.0.0/16", "10.1.0.0/16"]
}
resource "aws_vpc" "vpc" {
for_each = toset(var.vpc_cidrs)
cidr_block = each.value
enable_dns_hostnames = true
tags = { Name = "Company0${each.key}" }
}
我希望标记名称为"Name" = "Company01"
和"Name" = "Company02"
,但是根据terraform apply
,我得到:
"Name" = "Company010.0.0.0/16"
和"Name" = "Company010.1.0.0/16"
我想念什么?
答案 0 :(得分:7)
使用index函数找到了一个简单的解决方案:
tags = { Name = "Company0${index(var.vpc_cidrs, each.value) + 1}" }
答案 1 :(得分:7)
还有另一种无需使用index()
即可获得所需结果的方法:
更改以下三行:
for_each = { for idx, cidr_block in var.vpc_cidrs: cidr_block => idx}
cidr_block = each.key
tags = { Name = format("Company%02d", each.value + 1) }
for_each
将使用cidr_block
返回的index
到for
的映射cidr_block
然后可以只使用each.key
值tags
中也使用format()
上的each.value
来获得两位数字,其前导零为index
完整示例为:
provider "aws" {
profile = "default"
region = "us-east-1"
}
variable "vpc_cidrs" {
default = ["10.0.0.0/16", "10.1.0.0/16"]
}
resource "aws_vpc" "vpc" {
for_each = { for idx, cidr_block in var.vpc_cidrs: cidr_block => idx}
cidr_block = each.key
enable_dns_hostnames = true
tags = { Name = format("Company%02d", each.value + 1) }
}
答案 2 :(得分:3)
当for_each
is used with a set,List<string> temp = (from an in modelDb.MyTable
where an.Id == 0
an.fileName.ToUpper().Contains("SIGNED")
select an.filePath).ToList();
paths = temp.Where(an =>
an.fileName.Split('_')[0] == "19292929383833abe838ac393" &&
an.fileName.Split('_')[1].ToUpper() == "FINANCE").ToList();
和each.key
相同时。
要生成“ Company01”,“ Company02”等字符串,您需要列表中每个CIDR块的索引。一种方法是使用for
expression创建本地地图,例如:
each.value
作为奖励,您可以使用format函数来构建零填充的名称字符串:
locals {
vpc_cidrs = {for s in var.vpc_cidrs: index(var.vpc_cidrs, s) => s}
}
resource "aws_vpc" "vpc" {
for_each = local.vpc_cidrs
cidr_block = each.value
enable_dns_hostnames = true
tags = { Name = "Company0${each.key}" }
}
答案 3 :(得分:0)
您可以使用 count
函数并使用索引来执行此操作:
provider "aws" {
profile = "default"
region = "us-east-1"
}
variable "vpc_cidrs" {
type = list(string)
default = ["10.0.0.0/16", "10.1.0.0/16"]
}
resource "aws_vpc" "vpc" {
count = length(var.vpc_cidrs)
cidr_block = var.vpc_cidrs[count.index]
enable_dns_hostnames = true
tags = { Name = "Company0${count.index}" }
}