Best Python code snippet using localstack_python
create_stackset_lambda.py
Source:create_stackset_lambda.py  
...96    CFT = boto3.client('cloudformation')97    try:98        stackset_result = CFT.describe_stack_set(StackSetName=stacksetName)99        if stackset_result and 'StackSet' in stackset_result:100            stackset_instances = CFT.list_stack_instances(StackSetName=stacksetName)101            while 'NextToken' in stackset_instances:102                stackinstancesnexttoken = stackset_instances['NextToken']103                morestackinstances = CFT.list_stack_instances(NextToken=stackinstancesnexttoken)104                stackset_instances["Summaries"].extend(morestackinstances["Summaries"])105            if len(stackset_instances["Summaries"]) > 0:106                stack_instance_members = [x["Account"] for x in stackset_instances["Summaries"]]107                stack_instance_regions = list(set(x["Region"] for x in stackset_instances["Summaries"]))108                CFT.delete_stack_instances(109                    StackSetName=stacksetName,110                    Accounts=stack_instance_members,111                    Regions=stack_instance_regions,112                    OperationPreferences={'MaxConcurrentCount': 3},113                    RetainStacks=False114                )115            stackset_instances = CFT.list_stack_instances(StackSetName=stacksetName)116            counter = 2117            while len(stackset_instances["Summaries"]) > 0 and counter > 0:118                logger.info("Deleting stackset instance from {}, remaining {}, sleeping for 10 sec".format(stacksetName,119                                                                                                           len(120                                                                                                               stackset_instances[121                                                                                                                   "Summaries"])))122                time.sleep(10)123                counter = counter - 1124                stackset_instances = CFT.list_stack_instances(StackSetName=stacksetName)125            if counter > 0:126                CFT.delete_stack_set(StackSetName=stacksetName)127                logger.info("StackSet {} deleted".format(stacksetName))128            else:129                logger.info("StackSet {} still has stackset instance, skipping".format(stacksetName))130            return True131    except ClientError as e:132        if e.response['Error']['Code'] == 'StackSetNotFoundException':133            logger.info("StackSet {} does not exist".format(stacksetName))134            return True135        else:136            logger.error("Unexpected error: %s" % e)137            return False138def lambda_handler(event, context):...ioa_setup_master.py
Source:ioa_setup_master.py  
...60    cft_client = boto3.client('cloudformation')61    try:62        stackset_result = cft_client.describe_stack_set(StackSetName=stackset_name)63        if stackset_result and 'StackSet' in stackset_result:64            stackset_instances = cft_client.list_stack_instances(StackSetName=stackset_name)65            while 'NextToken' in stackset_instances:66                stackinstancesnexttoken = stackset_instances['NextToken']67                morestackinstances = cft_client.list_stack_instances(NextToken=stackinstancesnexttoken)68                stackset_instances["Summaries"].extend(morestackinstances["Summaries"])69            if len(stackset_instances["Summaries"]) > 0:70                stack_instance_regions = list(set(x["Region"] for x in stackset_instances["Summaries"]))71                cft_client.delete_stack_instances(72                    StackSetName=stackset_name,73                    Accounts=account,74                    Regions=stack_instance_regions,75                    OperationPreferences={'MaxConcurrentCount': 20, 'RegionConcurrencyType': 'PARALLEL'},76                    RetainStacks=False77                )78            stackset_instances = cft_client.list_stack_instances(StackSetName=stackset_name)79            counter = 1080            while len(stackset_instances["Summaries"]) > 0 and counter > 0:81                logger.info("Deleting stackset instance from {}, remaining {}, "82                            "sleeping for 10 sec".format(stackset_name, len(stackset_instances["Summaries"])))83                time.sleep(10)84                counter = counter - 185                stackset_instances = cft_client.list_stack_instances(StackSetName=stackset_name)86            if counter > 0:87                cft_client.delete_stack_set(StackSetName=stackset_name)88                logger.info("StackSet {} deleted".format(stackset_name))89            else:90                logger.info("StackSet {} still has stackset instance, skipping".format(stackset_name))91            return True92    except ClientError as e:93        if e.response['Error']['Code'] == 'StackSetNotFoundException':94            logger.info("StackSet {} does not exist".format(stackset_name))95            return False96        else:97            logger.error("Unexpected error: %s" % e)98            return False99def create_cloudtrail(s3_bucket_name, region):...aws_cloudformation_stack_set_info.py
Source:aws_cloudformation_stack_set_info.py  
...91    @AWSRetry.exponential_backoff(retries=5, delay=5)92    def list_stack_instances_with_backoff(self, **kwargs):93        paginator = self.client.get_paginator('list_stack_instances')94        return paginator.paginate(**kwargs).build_full_result()['Summaries']95    def list_stack_instances(self, stack_set_name):96        try:97            kwargs = {'StackSetName': stack_set_name}98            return self.list_stack_instances_with_backoff(**kwargs)99        except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err:100            self.module.fail_json_aws(101                err,102                msg="Error listing stack instances for stackset {0} in account {1}".format(stack_set_name, account_id)103            )104def to_dict(items, key, value):105    ''' Transforms a list of items to a Key/Value dictionary '''106    if items:107        return dict(zip([i.get(key) for i in items], [i.get(value) for i in items]))108    else:109        return dict()110def main():111    argument_spec = dict(112        stack_set_name=dict(),113        all_facts=dict(required=False, default=False, type='bool'),114        stack_instances=dict(required=False, default=False, type='bool')115    )116    module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)117    service_mgr = CloudFormationStacksetServiceManager(module)118    result = {'cloudformation': {}}119    for stack_description in service_mgr.describe_stack_sets(module.params.get('stack_set_name')):120        facts = {'stack_description': stack_description}121        stack_set_name = stack_description.get('StackSetName')122        # Create optional stack outputs123        all_facts = module.params.get('all_facts')124        if all_facts or module.params.get('stack_instances'):125            facts['stack_instances'] = service_mgr.list_stack_instances(stack_set_name)126        result['cloudformation'][stack_set_name] = camel_dict_to_snake_dict(facts, ignore_list=('stack_outputs',127                                                                                            'stack_parameters',128                                                                                            'stack_policy',129                                                                                            'stack_resources',130                                                                                            'stack_tags',131                                                                                            'stack_template'))132    module.exit_json(changed=False, **result)133if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
