Skip to content

Instantly share code, notes, and snippets.

@jheerman
Last active December 18, 2021 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jheerman/f13c17fa476bb00c20c5bae4d8b17913 to your computer and use it in GitHub Desktop.
Save jheerman/f13c17fa476bb00c20c5bae4d8b17913 to your computer and use it in GitHub Desktop.
Update AWS Cloudwatch Retention Policy on Log Groups
#!/bin/bash
# This script takes the number of days to retain AWS Cloudwatch logs as an argument
# and updates all AWS Cloudwatch logs policy to the desired retention length
if [ $# -eq 0 ]
then
echo "Please specify the number of days to retain AWS Cloudwatch Logs"
echo "Usage: update-log-retention-policy 90"
echo "Done"
echo ""
return 0
fi
days=$1
echo "Number of days to retain logs set to $days"
#create json file
echo "Getting log groups from AWS..."
aws logs describe-log-groups > logGroups.json
#find logs with retention less than $days (ignore null, that means already are indefinite)
echo "Filtering logs based on desired retention..."
logs=$(cat logGroups.json | jq '.[] | map({logGroupName: .logGroupName, retention: .retentionInDays })' | jq -cr --argjson DAYS "$days" '.[] | select((.retention != null) and .retention < $DAYS)')
if [ -z "$logs" ]
then
echo "No logs found with retention < $days"
echo "Done"
echo ""
return 0
fi
echo "Updating retention policy..."
#update the retention policy
echo $logs | jq -r '.logGroupName' | while read log; do echo "Updating retention policy for log group: $log"; aws logs put-retention-policy --log-group-name $log --retention-in-days $days; done
rm logGroups.json
echo "Done"
echo ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment