Can someone please help with this bash script. I am trying to get all the untagged log groups in an aws account. I am using aws cli api command where i need to paginate the request due to the many records. But for reason, the nextToken is not working, it keeps generating the same first 50 records.
#!/bin/bash
# AWS profile (optional)
AWS_PROFILE="xxx"
# AWS region
AWS_REGION="us-east-1"
# Output CSV file
CSV_FILE="untagged_log_groups.csv"
# Header for CSV file
# Check if CSV file already exists
if [ ! -f "$CSV_FILE" ]; then
# If CSV file doesn't exist, create it and add header
echo "LogGroupName" > $CSV_FILE
fi
ITERATION_COUNT=0
# Function to list log groups with pagination
list_log_groups() {
aws logs describe-log-groups --query 'logGroups[*].logGroupName' --output text --profile "$AWS_PROFILE" --region "$AWS_REGION" --max-items 50
echo "Done list_log_groups"
}
LOG_GROUPS=()
# Iterate through log groups with pagination
next_token=""
while true; do
((ITERATION_COUNT++))
echo "Iteration count: $ITERATION_COUNT"
LOG_GROUPS=$(list_log_groups "$next_token")
echo "Retrieved log groups: $LOG_GROUPS"
for LOG_GROUP in $LOG_GROUPS; do
# Check if the log group has tags
TAGS=$(aws logs list-tags-log-group --log-group-name "$LOG_GROUP" --query 'tags' --output text --profile "$AWS_PROFILE" --region "$AWS_REGION")
echo "TAGS"
# If no tags found, extract log group details
if [ -z "$TAGS" ]; then
echo "$LOG_GROUP" >> "$CSV_FILE"
fi
done
# Check if there are more log groups to fetch
next_token=$(aws logs describe-log-groups --query 'nextToken' --output text --profile "$AWS_PROFILE" --region "$AWS_REGION")
echo "printing next token: $next_token"
if [ -z "$next_token" ] || [ "$next_token" == "None" ]; then
break
fi
done
echo "CSV file updated: $CSV_FILE"