DEV Community

Yasuhiro Matsuda for AWS Community Builders

Posted on • Updated on

How to switch Dynamic block definitions in Terraform

The setting of whether or not to enable resources in Terraform can be toggled by using count or for_each.

Example using count

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

Example using for_each

resource "aws_route53_record" "services" {
  // Register only if 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

Since count cannot be used when switching options using Dynamic block, such as capacity_provider_strategy options for aws_ecs_service resources, it can be realized by defining as follows using 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 // ALWAYS TWO ARE BOOTED WITH FARGATE
      weight            = 0
    }
  }

  dynamic "capacity_provider_strategy" {
    for_each = var.is_capacity_provider_strategy ? [1] : []
    content {
      capacity_provider = "FARGATE_SPOT"
      base              = 0
      weight            = 1 // From the third unit onwards, boot to FARGATE_SPOT
    }
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)