Terraform – for_each的使用
for_each 可以loop set或者map , 那么就能批量创建资源
使用案例1:loop set
each.value 和 each.key 获取的值都是一样的
provider "aws" {
region = "ap-southeast-1"
}
variable "setdata" {
type = set(string)
default = ["kiat","alice"]
}
resource "aws_iam_user" "iam" {
for_each = var.setdata
name = each.value
tags = {
Name = "user-${each.key}"
}
}
输出结果:

使用案例2:
loop map , each.key 可以读取map的key
provider "aws" {
region = "ap-southeast-1"
}
variable "setdata" {
type = map(string)
default = {
dev = "alice"
prod = "kiat"
}
}
resource "aws_iam_user" "iam" {
for_each = var.setdata
name = each.value
tags = {
Name = "user-${each.key}"
}
}
输出结果:

Facebook评论