DEV Community

Yasuhiro Matsuda for AWS Community Builders

Posted on • Edited on

2 2

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)

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