How to configure AWS Lambda CloudWatch logging with Terraform

Bjorn Krolsavatar

Bjorn Krols

Published on
09 March 2022

Create a log group, specifying a retention period.

The name of the log group should respect the specified pattern.

resource "aws_cloudwatch_log_group" "function_log_group" {
  name              = "/aws/lambda/${aws_lambda_function.function.function_name}"
  retention_in_days = 7
  lifecycle {
    prevent_destroy = false
  }
}

Create a role for your function.

resource "aws_iam_role" "function_role" {
  name               = "function-role"
  assume_role_policy = jsonencode({
    "Version" : "2012-10-17",
    "Statement" : [
      {
        Action : "sts:AssumeRole",
        Effect : "Allow",
        Principal : {
          "Service" : "lambda.amazonaws.com"
        }
      }
    ]
  })
}

Attach the role to your function.

resource "aws_lambda_function" "function" {
  role = aws_iam_role.function_role.arn
}

Create a logging policy.

resource "aws_iam_policy" "function_logging_policy" {
  name   = "function-logging-policy"
  policy = jsonencode({
    "Version" : "2012-10-17",
    "Statement" : [
      {
        Action : [
          "logs:CreateLogStream",
          "logs:PutLogEvents"
        ],
        Effect : "Allow",
        Resource : "arn:aws:logs:*:*:*"
      }
    ]
  })
}

Attach the logging policy to the function role.

resource "aws_iam_role_policy_attachment" "function_logging_policy_attachment" {
  role = aws_iam_role.function_role.id
  policy_arn = aws_iam_policy.function_logging_policy.arn
}

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

More like this