Skip to content

Instantly share code, notes, and snippets.

@adamfortuno
Last active January 15, 2020 19:20
Show Gist options
  • Save adamfortuno/ea9e0f8aaa8bcd3db3a6125fb92f57ee to your computer and use it in GitHub Desktop.
Save adamfortuno/ea9e0f8aaa8bcd3db3a6125fb92f57ee to your computer and use it in GitHub Desktop.
Update AWS CloudWatch Log Retention
const LogGroupRetentionUpdate = async (logGroupNamePrefix, retentionPeriodInDays, profile = "development", region = "'us-wast-1'") => {
const AWS = require('aws-sdk');
process.env.AWS_SDK_LOAD_CONFIG = true;
process.env.AWS_PROFILE = profile;
AWS.config.update( {region: region} );
const logs = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'});
// Make sure the function was passed a valid log group prefix and retention period
if ( [null, undefined].includes(retentionPeriodInDays) ) {
throw new Error("Unable to update log group retention to null or undefined value.");
}
if ( typeof retentionPeriodInDays != 'number' ) {
throw new Error("The retention period should be a number specifying the number of days to keep a log.");
}
if ( [null, undefined].includes(logGroupNamePrefix) ) {
throw new Error("Unable to update log group without search prefix.");
}
let logGroupsToUpdateRetention = [];
let logGroups = [];
let logGroupQueryResults;
let nextToken;
try {
const prefixTargetLogGroups = {
logGroupNamePrefix: logGroupNamePrefix
};
logGroupQueryResults =
await logs.describeLogGroups(prefixTargetLogGroups).promise();
logGroups = logGroups.concat(logGroupQueryResults.logGroups);
nextToken = logGroupQueryResults.nextToken;
// The results are paged; If there is a "nextToken" in the results
// you'll want to query again to get the next set of log groups
while ( nextToken ) {
prefixTargetLogGroups['nextToken'] = nextToken;
logGroupQueryResults
= await logs.describeLogGroups(prefixTargetLogGroups).promise();
logGroups = logGroups.concat(logGroupQueryResults.logGroups);
nextToken = logGroupQueryResults.nextToken;
}
console.log("%i-items returned.", logGroups.length);
logGroups.forEach( (logGroup) => {
console.log("'%s' has a retention of '%i'.", logGroup.logGroupName, logGroup.retentionInDays);
if ( [null, undefined].includes(logGroup.retentionInDays) || logGroup.retentionInDays != retentionPeriodInDays ) {
console.log("Attempting to add retention period to '%s'", logGroup.logGroupName);
const options = {
logGroupName: logGroup.logGroupName,
retentionInDays: retentionPeriodInDays
};
logGroupsToUpdateRetention.push( logs.putRetentionPolicy(options).promise() );
}
});
await Promise.all(logGroupsToUpdateRetention);
console.log("Log Group Updates Completed");
} catch (error) {
console.error(error);
}
};
let [,, prefix, retentionPeriodInDays, profile, region] = process.argv;
LogGroupRetentionUpdate(prefix, parseInt(retentionPeriodInDays), profile, region);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment