def lifecycle_processing()

in functions/source/stackset/stackset.py [0:0]


def lifecycle_processing(event):
    if event['detail']['serviceEventDetails']['createManagedAccountStatus']['state'] == 'SUCCEEDED':
        cloudFormationClient = session.client('cloudformation')
        account_id = event['detail']['serviceEventDetails']['createManagedAccountStatus']['account']['accountId']
        stackSetName = os.environ["stackSetName"]
        stackset_instances = list_stack_instance_by_account(session, stackSetName, account_id)
        stackset_instances_regions = list_stack_instance_region(session, stackSetName)
        
        logger.info("Processing Lifecycle event for {}".format(account_id))
        #stackset instance does not exist, create a new one
        if len(stackset_instances) == 0:
            logger.info("Create new stackset instance for {} {} {}".format(stackSetName, account_id, stackset_instances_regions))
            messageBody = {}
            messageBody[stackSetName] = { 'target_accounts': [account_id], 'target_regions': stackset_instances_regions }
            stackset_processing(messageBody)
        
        #stackset instance already exist, check for missing region
        elif len(stackset_instances) > 0:
            stackset_region = []
            for instance in stackset_instances:
                stackset_region.append(instance['Region'])
            next_region = list(set(stackset_instances_regions) - set(stackset_region))
            if len(next_region) > 0:
                logger.info("Append new stackset instance for {} {} {}".format(stackSetName, account_id, next_region))
                messageBody = {}
                messageBody[stackSetName] = { 'target_accounts': [account_id], 'target_regions': next_region }
                stackset_processing(messageBody)
            else:
                logger.info("Stackset instance already exist : {}".format(stackset_instances))
    else:
         logger.error("Invalid event state, expected: SUCCEEDED : {}".format(event))