Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all alarms from AWS instead of only 50 using describe_alarms on Python

How can I print all the alarms names, instead of only 50, when using the function describe_alarms?

Code, using Python:

conn = boto.connect_cloudwatch()
alarms = conn.describe_alarms()    
for item in alarms:
    print item.name

Thanks.

like image 268
Danilo Avatar asked Feb 09 '23 08:02

Danilo


1 Answers

Even though I am a bit late to the party, here is my solution (in Java). You have to get the next token and keep on asking for the Result in a loop until there is no next token, so it behaves like a pagination on a website

String nextToken = null;
List<MetricAlarm> metricAlarms = new ArrayList<>();
for (int i = 0; i < 100; i++) {

    DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
    describeAlarmsRequest.setNextToken(nextToken);
    describeAlarmsRequest.setMaxRecords(100);

    DescribeAlarmsResult describeAlarmsResult = getClient().describeAlarms(describeAlarmsRequest);
    List<MetricAlarm> metricAlarmsTmp = describeAlarmsResult.getMetricAlarms();
    metricAlarms.addAll(metricAlarmsTmp);
    nextToken = describeAlarmsResult.getNextToken();
    logger.info("nextToken: {}", nextToken);

    if (nextToken == null) {
        break;
    }
}
logger.info("metricAlarms size: {}", metricAlarms.size());

Of course there is room for improvement, e.g. create a while loop instead of a for loop.

UPDATE:

Here my refined version

String nextToken = null;
List<MetricAlarm> metricAlarms = new ArrayList<>();

while (nextToken != null || metricAlarms.size() == 0) {
    DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest().withNextToken(nextToken).withMaxRecords(100); // create the request
    DescribeAlarmsResult describeAlarmsResult = getClient().describeAlarms(describeAlarmsRequest); // get the result
    metricAlarms.addAll(describeAlarmsResult.getMetricAlarms()); // add new alarms to our list
    nextToken = describeAlarmsResult.getNextToken(); // check if we have a nextToken
    if (nextToken == null && cachedMetricAlarms.size() == 0) { // if we have no alarm in AWS we get inside the loop but we would never exit -> intercept that
            break;
        }
}
logger.info("metricAlarms size: {}", metricAlarms.size());
like image 158
Michael Avatar answered Feb 12 '23 10:02

Michael