DEV Community

Yasuhiro Matsuda for AWS Community Builders

Posted on • Edited on

2 1

TerraformでDynamicブロックの定義を切り替える方法

Terraformでリソースを有効にするかどうかの設定は、countを利用するか、for_eachを利用することで切り替えすることができる。

countを利用した例

resource "aws_route53_record" "keycloak" {
  count   = var.enable_dns_record ? 1 : 0
}
Enter fullscreen mode Exit fullscreen mode

for_eachを利用した例

resource "aws_route53_record" "services" {
  // enable_dns_record = true の場合にのみ登録する
  for_each = {
    for name, service in var.service : name => school
    if var.enable_dns_record == true
  }
}
Enter fullscreen mode Exit fullscreen mode

aws_ecs_serviceリソースのcapacity_provider_strategyオプションのようにDynamicブロックの定義を使ったオプションを切り替える場合にはcountを利用できないため、for_eachを利用して以下のように定義することで実現できる。

resource "aws_ecs_service" "service" {
  dynamic "capacity_provider_strategy" {
    for_each = var.is_capacity_provider_strategy ? [1] : []
    content {
      capacity_provider = "FARGATE"
      base              = 2 // 必ず2台はFARGATEで起動
      weight            = 0
    }
  }

  dynamic "capacity_provider_strategy" {
    for_each = var.is_capacity_provider_strategy ? [1] : []
    content {
      capacity_provider = "FARGATE_SPOT"
      base              = 0
      weight            = 1 // 3台目以降はFARGATE_SPOTで起動
    }
  }
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Best Practices for Running  Container WordPress on AWS (ECS, EFS, RDS, ELB) using CDK cover image

Best Practices for Running Container WordPress on AWS (ECS, EFS, RDS, ELB) using CDK

This post discusses the process of migrating a growing WordPress eShop business to AWS using AWS CDK for an easily scalable, high availability architecture. The detailed structure encompasses several pillars: Compute, Storage, Database, Cache, CDN, DNS, Security, and Backup.

Read full post