• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy
Automating CloudWatch log group retention update using Python script

Automating CloudWatch log group retention update using Python script

Priyesh P

  • 4 min read
Automating CloudWatch log group retention update using Python script

Generating audio, please wait...

Amazon CloudWatch Log Groups are an important part of AWS CloudWatch Logs, providing a centralized location for storing, monitoring and managing log data created by multiple AWS services, applications, and resources. For log streams, Log Groups offer a structured and secure repository that can be searched, filtered, and analyzed to reveal information about the functionality and health of your applications and infrastructure. CloudWatch Log Groups enable effective log management while assisting you in maintaining complete log data thanks to their adjustable retention settings and strong querying features.

As we all know every log group needs a retention policy in order to save cost and reduce the complexity while searching the logs.

If the log group doesn't have a retention policy then the logs will never expire and the logs will be retained there from the creation date.

In some cases, we will choose the retention policies and in some cases, we will not. Recently we got a requirement to update the retention period of all the log groups in 5 AWS accounts and upon checking there were almost 100+ log groups in every account.

Doing them manually is pretty boring and time-consuming so we came up with a Python Script for automating this. The Python script uses Boto3 to communicate with AWS services and here we are using boto3 logs API. Also, we need to configure the IAM user with the necessary permissions in AWS CLI to get this done.

Requirements

  1. AWS CLI installed and configured.
  2. Export the AWS CLI profile.
  3. Python3 with boto3 installed.

The script is given below, 
 


import boto3

logs = boto3.client('logs')

output = logs.describe_log_groups()

for_count = len(output['logGroups'])

updated_log_group = 0

retention = int(input("Please enter the retention period in number (eg 7 for 7days) : "))

allowed_retention_values = [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653]

if retention in allowed_retention_values:
print(f"Total {for_count} log groups needs to be updated")

for name in output['logGroups']:
logname = name['logGroupName']
logs.put_retention_policy(
logGroupName= logname,
retentionInDays = retention
)
print(f"The retention policy is successfully added to {logname}")

updated_log_group += 1


print(f"The retention policy updated for {updated_log_group} out of {for_count}")
else:
print("The allowed values are [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653] please enter a valid one")

The script asks for the user input to set retention days and checks if the input is valid. If the input is valid the script will apply the retention to all the log groups and if the input is not valid the script will print a custom message saying it is invalid along with the allowed values.

Demonstration

Here is my current retention setting for my log group /aws/lambda/testmail.

Press enter or click to view image in full size
 

1_1nKSTex0Rnj0B1HmgaVWKQ.webp

We are going to execute the script and change the retention to 7 days.

The script will ask the user for the input and if the value is invalid it will print a message.

1_gK4iZjPFVud9IZ3_hPChEQ.webp
If the value is valid the script will get executed.

1_gquivrT1tR0s4WsOKjsWlw.webp
Now we have set a retention policy for all the log groups in my AWS account with a retention of 7 days.

Press enter or click to view image in full size
1_CdX-dapG6JDNxTBVcfVPow.webp

That’s it, Thank You.

Get your log groups in top shape today! Discover our step-by-step guide and Python script for simplified log management. Ready to optimize your AWS log groups? Learn more at SupportSages for expert insights and a free consultation on mastering CloudWatch Log Groups!

  • AWS
  • DevOps

Continue Your Journey With…

DevOps as a Service

DevOps as a Service

Let us do the heavy lifting for you

Promotional banner
Promotional banner

Posts by Priyesh P