Boto: What is the best way to check if a CloudFormation stack exists?

advertisements

What is the best way to check if a CloudFormation stack exists and is not in a broken state using Boto? By broken I mean failed and rollback states.

I don't want to use a try/except solution, because boto logs it as an error, and in my scenario it's going to send the exception log to an alarm system.


At the moment I have the following solutions:

1) Use boto.cloudformation.connection.CloudFormationConnection.describe_stacks()

valid_states = '''\
CREATE_IN_PROGRESS
CREATE_COMPLETE
UPDATE_IN_PROGRESS
UPDATE_COMPLETE_CLEANUP_IN_PROGRESS
UPDATE_COMPLETE'''.splitlines()

def describe_stacks():
    result = []
    resp = cf_conn.describe_stacks()
    result.extend(resp)
    while resp.next_token:
        resp = cf_conn.describe_stacks(next_token=resp.next_token)
        result.extend(resp)
    return result

stacks = [stack for stack in describe_stacks() if stack.stack_name == STACK_NAME and stack.stack_status in valid_states]
exists = len(stacks) >= 1

This is slow because I have lots of stacks.


2) Use boto.cloudformation.connection.CloudFormationConnection.list_stacks()

def list_stacks(filters):
    result = []
    resp = cf_conn.list_stacks(filters)
    result.extend(resp)
    while resp.next_token:
        resp = cf_conn.list_stacks(filters, next_token=resp.next_token)
        result.extend(resp)
    return result

stacks = [stack for stack in list_stacks(valid_states) if stack.stack_name == STACK_NAME]
exists = len(stacks) >= 1

This takes forever, because summaries are kept for 90 days and I have lots of stacks.


Question: What is the ideal solution to check if a given stack exists and is not in a failure or rollback state?


From the boto docs:

describe_stacks(stack_name_or_id=None, next_token=None)

Returns the description for the specified stack; if no stack name was specified, then it returns the description for all the stacks created.

Parameters: stack_name_or_id (string) – The name or the unique identifier associated with the stack.

Since you know the stack name, you can use describe_stacks(stack_name_or_id=STACK_NAME). That should speed things up for you.