Skip to content

Instantly share code, notes, and snippets.

@suhussai
Last active November 19, 2023 18:35
Show Gist options
  • Save suhussai/3ac5be45a923a1585a36d01748dd8aa8 to your computer and use it in GitHub Desktop.
Save suhussai/3ac5be45a923a1585a36d01748dd8aa8 to your computer and use it in GitHub Desktop.
AWS CLI script that iterates over CloudWatch log groups, and sets the retention policy on log groups that don't have one.
#!/bin/bash
next_token=""
RETENTION_POLICY_IN_DAYS=30
echo "$(date) Starting..."
while true; do
if [[ "${next_token}" == "" ]]; then
echo "$(date) making api call to search for log groups.."
response=$(aws logs describe-log-groups --max-items 50)
else
echo "$(date) making api call to search for log groups using next token..."
response=$(aws logs describe-log-groups --max-items 50 --starting-token "$next_token")
fi
log_group_names=$(echo "$response" | jq -r '.logGroups | map(select( has("retentionInDays") | not ))[] | .logGroupName ')
for i in $log_group_names; do
echo "setting retention on log group with name \"$i\" to $RETENTION_POLICY_IN_DAYS"
aws logs put-retention-policy --log-group-name "$i" --retention-in-days $RETENTION_POLICY_IN_DAYS
done
next_token=$(echo "$response" | jq '.NextToken')
if [[ "${next_token}" == "null" ]]; then
echo "$(date) no more log groups left."
# no more results left. Exit loop...
break
fi
done
echo "$(date) Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment