Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set aws cloudwatch retention via Terraform

Using Terraform to deploy API Gateway/Lambda and already have the appropriate logs in Cloudwatch. However I can't seem to find a way to set the retention on the logs via Terraform, using my currently deployed resources (below). It looks like the log group resource is where I'd do it, but not sure how to point log stream from api gateway at the new log group. I must be missing something obvious ... any advice is very much appreciated!

resource "aws_api_gateway_account" "name" {
  cloudwatch_role_arn = "${aws_iam_role.cloudwatch.arn}"
}

  resource "aws_iam_role" "cloudwatch" {
    name = "#{name}_APIGatewayCloudWatchLogs"
    assume_role_policy = <<EOF
{
 "Version": "2012-10-17",
 "Statement": [
   {
     "Sid": "",
     "Effect": "Allow",
     "Principal": {
     "Service": "apigateway.amazonaws.com"
    },
    "Action": "sts:AssumeRole"
  }
 ]
}
  EOF
  }

resource "aws_iam_policy_attachment" "api_gateway_logs" {
  name = "#{name}_api_gateway_logs_policy_attach"
  roles = ["${aws_iam_role.cloudwatch.id}"]
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
}  

resource "aws_api_gateway_method_settings" "name" {
  rest_api_id = "${aws_api_gateway_rest_api.name.id}"
  stage_name  = "${aws_api_gateway_stage.name.stage_name}"
  method_path = "${aws_api_gateway_resource.name.path_part}/${aws_api_gateway_method.name.http_method}"

  settings {
    metrics_enabled = true
    logging_level = "INFO"
    data_trace_enabled = true
  }
}
like image 825
LHK Avatar asked May 18 '18 18:05

LHK


1 Answers

yes, you can use the Lambda log name to create log resource before you create the Lambda function. Or you can import the existing log groups.

resource "aws_cloudwatch_log_group" "lambda" {
  name = "/aws/lambda/${var.env}-${join("", split("_",title(var.lambda_name)))}-Lambda"

  retention_in_days = 7

  lifecycle {
    create_before_destroy = true
    prevent_destroy       = false
  }
}
like image 55
victor m Avatar answered Oct 02 '22 11:10

victor m