def delete_stacks()

in aws/solutions/StackSetsResource/FunctionCode/lambda_function.py [0:0]


def delete_stacks(set_region, set_id, accts, regions, ops_prefs):
    # Wrapper for delete_stack_instances
    sleep_time = 15
    retries = 60
    this_try = 0

    logger.info("Deleting stack instances with op prefs {}".format(ops_prefs))
    logger.debug("StackSetName: {}, Accounts: {}, Regions: {}".format(set_id, accts, regions))

    while True:
        try:
            client = boto3.client('cloudformation', region_name=set_region)
            response = client.delete_stack_instances(
                StackSetName=set_id,
                Accounts=accts,
                Regions=regions,
                OperationPreferences=ops_prefs,
                RetainStacks=False,
                # OperationId='string'
            )
            return response
        except ClientError as e:
            if e.response['Error']['Code'] == 'OperationInProgressException':
                this_try += 1
                if this_try == retries:
                    logger.warning("Failed to delete stack instances after {} tries".format(this_try))
                    raise Exception("Error deleting stack instances: {}".format(e))
                else:
                    logger.warning(
                        "Delete stack instances operation in progress for {} in {}. Sleeping for {} seconds.".format(
                            set_id, set_region, sleep_time))
                    sleep(sleep_time)
                    continue
            elif e.response['Error']['Code'] == 'Throttling':
                this_try += 1
                if this_try == retries:
                    logger.warning("Failed to delete stack instances after {} tries".format(this_try))
                    raise Exception("Error deleting stack instances: {}".format(e))
                else:
                    logger.warning(
                        "Throttling exception encountered while deleting stack instances. Backing off and retyring. " 
                        "Sleeping for {} seconds.".format(sleep_time))
                    sleep(sleep_time)
                    continue
            elif e.response['Error']['Code'] == 'StackSetNotFoundException':
                return "No StackSet matching {} found in {}. You must create before deleting stack instances.".format(
                    set_id, set_region)
            else:
                return "Unexpected error: {}".format(e)