コンテンツにスキップ

Count

複数リソースを立ち上げる時に効率的に記載する

Section titled “複数リソースを立ち上げる時に効率的に記載する”

連番ではなくhash keyを使用して、明示的に名前をつける方が、間違いが少なく良い。

locals.tf
locals {
env_config = {
develop = {
instance_type = "t3.small"
instances = ["web", "worker"] # 2個
}
production = {
instance_type = "t3.large"
instances = ["web-a", "web-b", "worker-a", "worker-b"] # 4個
}
}
config = local.env_config[terraform.workspace]
}
ec2.tf
resource "aws_instance" "app" {
for_each = toset(local.config.instances)
instance_type = local.config.instance_type
ami = "ami-xxxxxxxxxxxxxxxxx"
tags = {
Name = "app-${terraform.workspace}-${each.key}"
}
}

productionのみにリソースを作成する場合

Section titled “productionのみにリソースを作成する場合”
locals.tf
locals {
is_production = terraform.workspace == "production"
}
aws_cloudwatch_log_group
count = local.is_production ? 1 : 0
name = "/debug/logs"