How to Set CloudWatch Log Retention Policies with Terraform
AWS CloudWatch is a powerful service for monitoring applications and infrastructure. However, by default, CloudWatch Logs are configured to never expire. This can lead to excessive storage costs and retention of data that you may not need. A better approach is to define a retention policy that aligns with your operational and compliance requirements.
In this post, we will show you how to manage CloudWatch log retention policies using Terraform.
Why Use Retention Policies?
There are several reasons to configure retention policies for your CloudWatch logs:
- Cost optimization: Old logs are automatically deleted, reducing storage costs.
- Compliance: Many organizations are required to keep logs only for a fixed period (e.g., 7, 30, or 90 days).
- Clarity: Retaining only recent logs keeps troubleshooting more efficient.
Managing Retention with Terraform
Terraform allows you to manage AWS resources declaratively. You can define a CloudWatch Log Group and specify how many days logs should be retained using the retention_in_days
argument.
Here is an example where we keep logs for 7 days:
provider "aws" {
region = "us-east-1"
}
resource "aws_cloudwatch_log_group" "app_logs" {
name = "/my-app/logs"
retention_in_days = 7
}
Supported Retention Values
AWS supports predefined values such as:
1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653, and Never expire
.
Select the one that best matches your needs.
Updating Existing Log Groups
If you already have CloudWatch Log Groups created manually or by other services, you can bring them under Terraform management.
- Import the log group into Terraform state:
terraform import aws_cloudwatch_log_group.app_logs /my-app/logs
2. Add the retention_in_days
setting to your configuration.
3. Run:
terraform apply
AWS will then enforce the new retention policy. Logs older than the retention window will be deleted automatically.
Best Practices
- Different environments, different policies
- Development: 7 days
- Staging: 14 days
- Production: 30–90 days (or as required by compliance).
- Automate imports for existing log groups if you have many created by services like Lambda or Glue.
- Use AWS Config to audit whether your log groups comply with your retention standards.
Conclusion
By default, CloudWatch logs never expire, which is rarely what teams actually need. With Terraform, you can define retention policies as code, ensuring consistency, reducing costs, and meeting compliance requirements.
Whether you need to keep logs for a week in development or several years in production, Terraform gives you the tools to manage log retention efficiently and repeatably.
👉 Official reference: Terraform AWS CloudWatch Log Group