in aws/solutions/StackSetsResource/FunctionCode/lambda_function.py [0:0]
def delete(event, context):
"""
Handle StackSetResource DELETE events.
Delete StackSet resource and any stack instances specified in the template.
"""
# Set up for retries
sleep_time = 15
retries = 60
this_try = 0
# Collect everything we need to delete the stack set
set_id = event['PhysicalResourceId']
if set_id == 'NONE':
# This is a rollback from a failed create. Nothing to do.
return
# First, we need to tear down all of the stacks associated with this
# stack set
if 'StackInstances' in event['ResourceProperties']:
# Check for Operation Preferences
if 'OperationPreferences' in event['ResourceProperties']:
set_ops_prefs = convert_ops_prefs(event['ResourceProperties']['OperationPreferences'])
else:
set_ops_prefs = {}
# Iterate over stack instances
for instance in event['ResourceProperties']['StackInstances']:
logger.debug("Stack Instance: Regions: {} : Accounts: {}".format(instance['Regions'], instance['Accounts']))
logger.info("Removing existing stacks from stack set {}".format(set_id))
response = delete_stacks(
os.environ['AWS_REGION'],
set_id,
instance['Accounts'],
instance['Regions'],
set_ops_prefs
)
logger.debug(response)
client = boto3.client('cloudformation', region_name=os.environ['AWS_REGION'])
# Retry loop
logger.info('Deleting stack set')
while True:
try:
response = client.delete_stack_set(
StackSetName=set_id
)
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
return
else:
raise Exception("HTTP Error: {}".format(response))
except ClientError as e:
if e.response['Error']['Code'] == 'OperationInProgressException':
this_try += 1
if this_try == retries:
raise Exception("Failed to delete StackSet after {} tries.".format(this_try))
else:
logger.warning(
"Delete StackSet operation in progress for {}. Sleeping for {} seconds.".format(
set_id, sleep_time))
sleep(sleep_time)
continue
elif e.response['Error']['Code'] == 'StackSetNotEmptyException':
raise Exception("There are still stacks in set {}. You must delete these first.".format(set_id))
else:
raise Exception("Unexpected error: {}".format(e))