Skip to content

Instantly share code, notes, and snippets.

@mgaffney
Created November 30, 2018 14:29
Show Gist options
  • Save mgaffney/da657d583c095c1aee137e22ee02f377 to your computer and use it in GitHub Desktop.
Save mgaffney/da657d583c095c1aee137e22ee02f377 to your computer and use it in GitHub Desktop.
Lambda: enable logging for a lambda function using terraform
# To enable a lambda function to log, create an IAM policy with the needed
# permissions and attach it to the lambda's IAM role.
resource "aws_lambda_function" "func" {
filename = "lambda_function_payload.zip"
function_name = "lambda_function_name"
handler = "exports.text"
runtime = "go1.x"
# each lambda function must have an IAM role
role = "${aws_iam_role.lambda_role.arn}"
# if you want to specify the retention period of the logs you need this
depends_on = ["aws_cloudwatch_log_group.lambda_logging"]
}
# This defines the minimum (maybe only?) IAM policy for a lambda's role.
# Do not try to add permissions for logging directly in to it because it
# won't work.
data "aws_iam_policy_document" "lambda_role" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}
resource "aws_iam_role" "lambda_role" {
name = "lambda_role"
assume_role_policy = "${data.aws_iam_policy_document.lambda_role.json}"
}
# This defines the IAM policy needed for a lambda to log. #1
data "aws_iam_policy_document" "lambda_logging" {
statement {
actions = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
]
resources = [
"arn:aws:logs:*:*:*",
]
}
}
# This creates the policy needed for a lambda to log. #2
resource "aws_iam_policy" "lambda_logging" {
name = "example-lambda-logging"
path = "/"
policy = "${data.aws_iam_policy_document.lambda_logging.json}"
}
# This attaches the policy needed for logging to the lambda's IAM role. #3
resource "aws_iam_role_policy_attachment" "lambda_logging" {
role = "${aws_iam_role.lambda_role.name}"
policy_arn = "${aws_iam_policy.lambda_logging.arn}"
}
resource "aws_cloudwatch_log_group" "lambda_logging" {
name = "/aws/lambda/example-lambda-function"
retention_in_days = 5
}
# Repeat 1, 2, and 3 for any other permissions your lambda needs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment