5
votes

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.

3

3 Answers

9
votes

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.

0
votes

No, there is not. As you wrote, it's a log group owned by AWS and you can't give yourself more permissions in a role than AWS would allow. Therefore, you can't allow yourself to modify their log group.

-1
votes

Use the AWS Serverless application Model, takes care of the deployment, roles and logs outbox and you always can add your custom cloudformation code https://github.com/awslabs/serverless-application-model they already have a lot of examples ready to go.