Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup Cloudwatch log for a Lambda created in Cloudformation

After creating a Lambda function in Cloudformation, I would like to be able to setup the Cloudwatch Logs expiration in the same Cloudformation script.

eg:

MyLambdaRole:
  Type: AWS::Iam::Role
    ...
    Properties:
      ...
      Policies:
        -
          PolicyName: "myPolicy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: "Allow"
                Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Resource: "arn:aws:logs:*:*:*"

MyLambda:
  Type: AWS::Lambda::Function
  Properties:
    ...
    Role: !GetAtt [ MyLambdaRole, Arn ]

However, CloudFormation does not allow to modify/update Logs that are reserved for AWS: "Log groups starting with AWS/ are reserved for AWS."

Is there a workaround for this? Since there is no way to setup the log name in the Lambda resource creation, maybe there is some way to specify it in the Role definition I can't find.

like image 283
Efren Avatar asked May 17 '18 01:05

Efren


1 Answers

Try this and use RetentionInDays attribute to change the logs expire after time

LogGroup:
  Type: AWS::Logs::LogGroup
  Properties:
    LogGroupName: !Join ['/', ['/aws/lambda', !Ref MyLambda]]
    RetentionInDays: 7 # days

Note: the issue of the LogGroup failing to create will appear if the log group name already exists( will exist if MyLambda already exists). The workaround would be to delete and create stack.

like image 168
roxxypoxxy Avatar answered Nov 12 '22 22:11

roxxypoxxy