How to use least privileges with AWSLambdaBasicExecutionRole

If you choose the option “Create a new Lambda with basic permissions” from the amazon console it will attach the AWSLambdaBasicExecutionRole, but it restricts its resource to only the log stream of the own Lambda that was created. Like this

{
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "arn:aws:logs:us-east-1:XXXXXXXX:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:us-east-1:XXXXXXXX:log-group:/aws/lambda/lambda_name:*"
            ]
        } 

But this example is using ::*

How do I accomplish this limiting with terraform?

# See also the following AWS managed policy: AWSLambdaBasicExecutionRole
resource "aws_iam_policy" "lambda_logging" {
  name        = "lambda_logging"
  path        = "/"
  description = "IAM policy for logging from a lambda"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*",
      "Effect": "Allow"
    }
  ]
}
EOF
}

This guy wrote typicalrunt.me » Enforcing Least Privilege When Logging Lambda Functions to CloudWatch on how he fixed it with cloudformation

Ok, I think this does the trick

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         = "iam_policy_lambda_logging_function"
  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}:*"
            ]
        }
    ]
}
)
}

# Policy Attachment on the role.

resource "aws_iam_role_policy_attachment" "policy_attach" {
  role        = aws_iam_role.lambda_role.name
  policy_arn  = aws_iam_policy.lambda_logging.arn
}