Allows a CloudWatch Log Group to invoke a Lambda function for logging purposes.

Terraform Template

data "aws_iam_policy_document" "assume_role" {

  statement {
    actions = ["sts:AssumeRole"]
    effect = "Allow"

    principals {
      identifiers = ["lambda.amazonaws.com"]
      type = "Service"
    }
  }
}

resource "aws_cloudwatch_log_group" "default" {
  name = "/default"
}

resource "aws_cloudwatch_log_subscription_filter" "logging" {
  depends_on = ["aws_lambda_permission.logging"]
  destination_arn = aws_lambda_function.logging.arn
  log_group_name = aws_cloudwatch_log_group.default.name
  name = "logging_default"
}

resource "aws_iam_role" "default" {
  assume_role_policy = data.aws_iam_policy_document.assume_role.json
  name = "iam_for_lambda_called_from_cloudwatch_logs"
}

resource "aws_lambda_function" "logging" {
}

resource "aws_lambda_permission" "logging" {
  action = "lambda:InvokeFunction"
  function_name = aws_lambda_function.logging.function_name
  principal = "logs.eu-west-1.amazonaws.com"
  source_arn = "${aws_cloudwatch_log_group.default.arn}:*"
}