- terraform에서 비슷한 resource를 여러개 생성하는 경우 필요함
- for_each 로 선택할 수 있는 자료구조: set, map
resource "azurerm_resource_group" "rg" {
for_each = {
a_group = "eastus"
another_group = "westus2"
}
name = each.key
location = each.value
} // map
// 위의 resource를 변수로 활용할 경우
// azurerm_resource_group.rg["a_group"], azurerm_resource_group.rg["another_group"]
resource "aws_iam_user" "the-accounts" {
for_each = toset( ["Todd", "James", "Alice", "Dottie"] )
name = each.key
} // set
In child module
# my_buckets.tf
module "bucket" {
for_each = toset(["assets", "media"])
source = "./publish_bucket"
name = "${each.key}_bucket"
}
# publish_bucket/bucket-and-cloudfront.tf
variable "name" {} # this is the input parameter of the module
resource "aws_s3_bucket" "example" {
# Because var.name includes each.key in the calling
# module block, its value will be different for
# each instance of this module.
bucket = var.name
# ...
}
resource "aws_iam_user" "deploy_user" {
# ...
}
응용
variable "vpcs" {
type = map(object({
cidr_block = string
}))
}
resource "aws_vpc" "example" { // vpcs 변수에 따라 여러개의 vpc 생성
# One VPC for each element of var.vpcs
for_each = var.vpcs
# each.value here is a value from var.vpcs
cidr_block = each.value.cidr_block
}
resource "aws_internet_gateway" "example" { // vpc에 따라 1:1로 igw 생성
# One Internet Gateway per VPC
for_each = aws_vpc.example
# each.value here is a full aws_vpc object
vpc_id = each.value.id
}
output "vpc_ids" {
value = {
for k, v in aws_vpc.example : k => v.id
}
# The VPCs aren't fully functional until their
# internet gateways are running.
depends_on = [aws_internet_gateway.example]
}
locals {
subnet_ids = toset([
"subnet-abcdef",
"subnet-012345",
])
}
resource "aws_instance" "server" {
for_each = local.subnet_ids
ami = "ami-a1b2c3d4"
instance_type = "t2.micro"
subnet_id = each.key # each.key와 each.value set에서 같음
tags = {
Name = "Server ${each.key}"
}
}
출처
https://www.terraform.io/language/meta-arguments/for_each
'IT > Devops' 카테고리의 다른 글
[Jenkins] Credentials from Kubernetes Secrets will not be available. (0) | 2022.05.21 |
---|---|
[Terraform] User Data, Provisioner 우선 순위 (0) | 2022.05.08 |
[Terraform] Block type (0) | 2022.04.06 |
[Terraform] Module 기본 구조 (0) | 2022.03.16 |
HCL이란 (0) | 2022.03.15 |
댓글