Least privilege for AWS lambda cloudwatch policy cloudformation and terraform

This guy noted that cloudformation doesn’t use a least privilege config

https://typicalrunt.me/2019/09/20/enforcing-least-privilege-when-logging-lambda-functions-to-cloudwatch/

I noticed the same with the terraform example here https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function

This is the policy I’m using

variable "lambda_function_name" {
  default = "lambda-function-terratest"
}

data "aws_region" "current" {}
data "aws_caller_identity" "current" {}

locals {
    account_id = data.aws_caller_identity.current.account_id
}

# Create the log group 
resource "aws_cloudwatch_log_group" "log_group" {
  name              = "/aws/lambda/${var.lambda_function_name}"
  retention_in_days = 14
}

resource "aws_iam_policy" "lambda_logging" {

  name         = "${var.lambda_function_name}-policy"
  path         = "/"
  description  = "IAM policy for logging from a lambda"
  policy = jsonencode(
{
  "Version": "2012-10-17",
  "Statement": [
        
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:${data.aws_region.current.name}:${local.account_id}:log-group:/aws/lambda/${var.lambda_function_name}:*"
            ]
        }
    ]
}
)
} 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s