skip to Main Content

I need to create TF CloudWatch Metrices only of the env is QAT and PROD. Currently using TF modules to create those in all env.

module "aws_cloudwatch_log_metric_filter" {
  source = "https://github.com/modules.git//aws-cloudwatch-log-metric-filter"
  log_group_name = "/aws/lambda/${var.lambda_name}"
  pattern = "{$.message = "---------------- Message ----------------"}"
}

locals {
  base_tags = {
    environment      = var.environment
  }
}

Main resource where I am calling module.

resource "aws_cloudwatch_log_metric_filter" "log_metric" {
  count          = var.count
  name           = "Metric"
  pattern        = var.pattern
  log_group_name = var.log_group_name
    
  metric_transformation {
    name      = "name"
    namespace = "namespace"
      value     = "1"
      default_value = "0"
  }
}

2

Answers


  1. A simple but good solution :

    locals {
      cw_env = ["QUA", "PROD"]
    }
    
    resource "aws_cloudwatch_log_metric_filter" "log_metric" {
      count          = contains(local.cw_env, var.env) ? 1 : 0
      name           = "Metric"
      pattern        = var.pattern
      log_group_name = var.log_group_name
    
      metric_transformation {
        name      = "name"
        namespace = "namespace"
        value     = "1"
        default_value = "0"
      }
    }
    

    Note you can also use it at the above level :

    module "aws_cloudwatch_log_metric_filter" {
      source = "https://github.com/modules.git//aws-cloudwatch-log-metric-filter"
    
      count          = contains(local.cw_env, local.base_tags.environment) ? 1 : 0
      log_group_name = "/aws/lambda/${var.lambda_name}"
      pattern = "{$.message = "---------------- Message ----------------"}"
    }
    
    locals {
      base_tags = {
        environment      = var.environment
      }
      cw_env = ["QUA", "PROD"]
    }
    
    Login or Signup to reply.
  2. You could do this in the module:

    resource "aws_cloudwatch_log_metric_filter" "log_metric" {
      count          = var.environment == "QAT" || var.environment == "PROD" ? 1 : 0
      name           = "Metric"
      pattern        = var.pattern
      log_group_name = "${var.environment}-${var.log_group_name}"
    
      metric_transformation {
        name      = "name"
        namespace = "namespace"
        value     = "1"
        default_value = "0"
      }
    }
    

    The log_group_name = "${var.environment}-${var.log_group_name}" will ensure you don’t get issues with the same log group name.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search