Akram Dhiabi
Akram Dhiabi

Reputation: 11

How to dynamically create resources only when terraform workspace is staging environment

This is actually not an issue but I need some help with this case!

In essence, I would like to loop through the local metrics below in order to create two CloudWatch metrics but only when terraform workspace is staging.

How can I achieve this condition with only for_each statement?

Thanks in advance.

Terraform Configuration Files


    locals {
    
      local.prefix = terraform.workspace
    
      metrics = {
        "AAA - Attempt" = {
          source          = "frontend"
          filter-pattern  = "YYY"
          metric-value    = 1
        },
        "AAA - Cancel" = {
          source          = "frontend"
          filter-pattern  = "XXX"
          metric-value    = 1
        }
      }
    }
    
    resource "aws_cloudwatch_log_metric_filter" "app-metrics" {
      count          = local.prefix == "staging"  ? 1 : 0
      for_each       = local.metrics
      name           = "${local.prefix}-${each.key}"
      pattern        = each.value["filter-pattern"]
      log_group_name =  aws_cloudwatch_log_group.frontend_logs.name 
    
      metric_transformation {
        name         = each.key
        namespace    = "${local.prefix}-metrics"
        value        = each.value["metric-value"]
      }
    }

Actual Behavior

 The "count" and "for_each" meta-arguments are mutually-exclusive, only one should be used to be explicit about the number of resources to be created.

Upvotes: 0

Views: 429

Answers (1)

Marcin
Marcin

Reputation: 238081

You can do as follows:

resource "aws_cloudwatch_log_metric_filter" "app-metrics" {

  for_each = local.prefix == "staging1" ? local.metrics : {}

  # the rest of your code account for for_each.

Upvotes: 1

Related Questions