Iterators iterators iterators!

Managing lots of CloudFormation stacks can be a pain through the AWS Console. Stacks are paginated so you’ll need to keep clicking that “View more stacks” button until you get to the stack you want.

Performing tasks through the AWS PHP SDK makes it a little easier, but you’ll still need to deal with tokens.

Take the following code snippet for example:

[code lang=php]
$client = \Aws\CloudFormation\CloudFormationClient::factory($config);
$stackstatus = array('CREATE_COMPLETE');

// First run
$result = $client->listStacks(array(
'StackStatusFilter' => $stackstatus,
));
$stacks = $result['StackSummaries'];
$token = $result['NextToken'];
foreach ($stacks as $stack) {
echo "$stack[StackName] – $stack[StackStatus]\n";
}

// Subsequent runs
while ($token != '') {
$result = $client->listStacks(array(
'NextToken' => "$token",
'StackStatusFilter' => $stackstatus,
));
$stacks = $result['StackSummaries'];
$token = $result['NextToken'];
foreach ($stacks as $stack) {
echo "$stack[StackName] – $stack[StackStatus]\n";
}
}
[/code]

Just like in the AWS Console, you’ll need to paginate through the entire list through the use of Tokens. The results on the first page will give you a Token, which you reference on a subsequent request to obtain page 2 and so on and so on.

But there is a better way! And that’s through the use of Iterators.

[code lang=php]
$client = \Aws\CloudFormation\CloudFormationClient::factory($config);
$stackstatus = array('CREATE_COMPLETE');

$iterator = $client->getIterator('ListStacks', array(
'StackStatusFilter' => $stackstatus,
));
$stacks = $iterator->toArray();
foreach ($stacks as $stack) {
echo "$stack[StackName]\n";
}
[/code]

Now that’s better! No pagination and no need to deal with tokens.

Iterators work for listing CF stacks, describing instances, pulling stuff out of DynamoDB, and lots of other things.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top