Best Python code snippet using localstack_python
extended_regions_lambda.py
Source:extended_regions_lambda.py  
...37ORG = SESSION.client('organizations')38EXEC_ROLE = 'AWSControlTowerExecution'39CONFIG_STACK = 'AWSControlTowerBP-BASELINE-CONFIG'40CNFPACK_URL = 'https://marketplace-sa-resources-ct-us-east-2.s3.us-east-2.amazonaws.com/ConformsBucket.yaml'41def list_stack_sets(status='ACTIVE'):42    '''Return stack sets if exists and matches the status optionally'''43    result = list()44    ss_list = list()45    try:46        cft_paginator = CFT.get_paginator('list_stack_sets')47        cft_page_iterator = cft_paginator.paginate()48    except Exception as exe:49        LOGGER.error('Unable to list stacksets: %s', str(exe))50    for page in cft_page_iterator:51        ss_list += page['Summaries']52    for item in ss_list:53        if item['Status'] == status:54            result.append(item['StackSetName'])55    return result56def get_stackset_parameters(ss_name):57    '''List all parameters from the given stackset name'''58    try:59        result = CFT.describe_stack_set(StackSetName=ss_name60                                        )['StackSet']['Parameters']61        return result62    except Exception as exe:63        LOGGER.error('Unable to get parameters %s', str(exe))64def get_stackset_body(ss_name):65    '''List all parameters from the given stackset name'''66    try:67        result = CFT.describe_stack_set(StackSetName=ss_name68                                        )['StackSet']['TemplateBody']69        return result70    except Exception as exe:71        LOGGER.error('Unable to get stack body %s', str(exe))72def does_stack_set_exists(ss_name):73    '''Return True if active StackSet exists'''74    result = False75    ss_list = list_stack_sets()76    if ss_name in ss_list:77        result = True78    else:79        LOGGER.warning('StackSet not found:%s', ss_name)80    return result81def add_stack_instance(ss_name, accounts, regions):82    ''' Adds StackSet Instances '''83    result = {'OperationId': None}84    ops = {85        'MaxConcurrentPercentage': 100,86        'FailureTolerancePercentage': 5087        }88    output = does_stack_set_exists(ss_name)89    LOGGER.info('OUTPUT:%s', output)90    if output:91        try:92            LOGGER.info('Add Stack Set Instances: %s, %s, %s',93                        ss_name, regions, accounts)94            result = CFT.create_stack_instances(StackSetName=ss_name,95                                                Accounts=accounts,96                                                Regions=regions,97                                                OperationPreferences=ops)98        except ClientError as exe:99            LOGGER.error("Unexpected error: %s", str(exe))100            result['Status'] = exe101    else:102        LOGGER.error('StackSet %s does not exist', ss_name)103    return result['OperationId']104def list_all_stack_instances(ss_name):105    '''List all stack instances in the account'''106    result = list()107    active_stacksets = list_stack_sets()108    if ss_name not in active_stacksets:109        LOGGER.error('StackSet %s not found in %s', ss_name, active_stacksets)110    else:111        try:112            cft_paginator = CFT.get_paginator('list_stack_instances')113            cft_page_iterator = cft_paginator.paginate(StackSetName=ss_name)114        except Exception as exe:115            LOGGER.error('Unable to list stack instances %s', str(exe))116        for page in cft_page_iterator:117            result += page['Summaries']118    return result119def list_from_stack_instances(ss_name, key='Account'):120    '''List of accounts that are part of stack instances'''121    result = list()122    ss_list = list()123    try:124        cft_paginator = CFT.get_paginator('list_stack_instances')125        cft_page_iterator = cft_paginator.paginate(StackSetName=ss_name)126    except Exception as exe:127        LOGGER.error('Unable to list stack instances: %s', str(exe))128    for page in cft_page_iterator:129        ss_list += page['Summaries']130    for item in ss_list:131        result.append(item[key])132    result = list(dict.fromkeys(result))133    return result134def delete_stack_instances(ss_name, accounts, regions, retain=False):135    '''Delete all stack instances with in the stackset'''136    result = False137    ops = {138        'MaxConcurrentPercentage': 100,139        'FailureTolerancePercentage': 50140        }141    try:142        CFT.delete_stack_instances(StackSetName=ss_name, Accounts=accounts,143                                   Regions=regions, RetainStacks=retain,144                                   OperationPreferences=ops)145        result = True146    except Exception as exe:147        LOGGER.error('Unable to delete stackset: %s', str(exe))148    return result149def get_stack_operation_status(ss_name, operation_id):150    '''Wait and return the status of the operation'''151    count = 25152    status = 'UNKNOWN'153    while count > 0:154        count -= 1155        try:156            output = CFT.describe_stack_set_operation(StackSetName=ss_name,157                                                      OperationId=operation_id)158            status = output['StackSetOperation']['Status']159        except Exception as exe:160            count = 0161            LOGGER.error('Stackset operation check failed: %s', str(exe))162        if status == 'RUNNING':163            LOGGER.info('Stackset operation %s, waiting for 30 sec', status)164            sleep(30)165        elif status in ['FAILED', 'STOPPING', 'STOPPED', 'UNKNOWN']:166            LOGGER.error('Exception on stackset operation: %s', status)167            count = 0168            break169        elif status == 'SUCCEEDED':170            LOGGER.info('StackSet Operation Completed: %s', status)171            break172    return count > 0173def delete_stackset(ss_name):174    '''Delete all stack instances and delete stack set'''175    ss_delete = False176    ss_accounts = list()177    ss_regions = list()178    delete_status = False179    ss_list = list_all_stack_instances(ss_name)180    if len(ss_list) > 0:181        ss_accounts = [item["Account"] for item in ss_list]182        ss_regions = [item["Region"] for item in ss_list]183        ss_accounts = list(dict.fromkeys(ss_accounts))184        ss_regions = list(dict.fromkeys(ss_regions))185    else:186        LOGGER.warning('No stack instances found: %s - %s',187                       ss_name, ss_list)188    if len(ss_accounts) > 0 and len(ss_regions) > 0:189        ss_delete = delete_stack_instances(ss_name, ss_accounts,190                                           ss_regions)191    else:192        ss_delete = True193    if ss_delete:194        ss_list = list_all_stack_instances(ss_name)195        ss_count = len(ss_list)196        counter = 25197        while ss_count > 0:198            LOGGER.info('%s stacks to be deleted. Sleeping for 30 secs.',199                        ss_count)200            sleep(30)201            ss_list = list_all_stack_instances(ss_name)202            ss_count = len(ss_list)203            counter -= 1204            if counter == 0:205                LOGGER.error('FAILED to delete %s stacks. Timing out.',206                             ss_count)207                ss_count = 0208        if counter > 0:209            try:210                LOGGER.info('Deleting the StackSet: %s', ss_name)211                CFT.delete_stack_set(StackSetName=ss_name)212                delete_status = True213            except Exception as exe:214                LOGGER.error('Unable to delete the stackset %s', str(exe))215    return delete_status216def get_master_id():217    ''' Get the master Id from AWS Organization - Only on master'''218    master_id = None219    try:220        master_id = ORG.list_roots()['Roots'][0]['Arn'].rsplit(':')[4]221    except Exception as exe:222        LOGGER.error('Only Run on Organization Root: %s', str(exe))223    return master_id224def get_org_id():225    '''Return org-id'''226    result = None227    try:228        result = ORG.describe_organization()['Organization']['Id']229    except Exception as exe:230        LOGGER.error('Unable to get Org-id: %s', str(exe))231    return result232def launch_stackset(ss_name, template, params,233                    admin_role_arn, template_type='body'):234    ''' Launch Config Stackset on the Master Account '''235    result = True236    capabilities = ['CAPABILITY_IAM',237                    'CAPABILITY_NAMED_IAM',238                    'CAPABILITY_AUTO_EXPAND']239    description = 'Enable Config in additional regions'240    active_stack_sets = list_stack_sets()241    if ss_name not in active_stack_sets:242        try:243            LOGGER.info('Create Stack Set: %s', ss_name)244            if template_type == 'body':245                CFT.create_stack_set(StackSetName=ss_name,246                                     Description=description,247                                     TemplateBody=template, Parameters=params,248                                     AdministrationRoleARN=admin_role_arn,249                                     ExecutionRoleName=EXEC_ROLE,250                                     Capabilities=capabilities)251            else:252                CFT.create_stack_set(StackSetName=ss_name,253                                     Description=description,254                                     TemplateURL=template, Parameters=params,255                                     AdministrationRoleARN=admin_role_arn,256                                     ExecutionRoleName=EXEC_ROLE,257                                     Capabilities=capabilities)258        except ClientError as exe:259            if exe.response['Error']['Code'] == 'NameAlreadyExistsException':260                LOGGER.error("StackSet already exists: %s", str(exe))261            else:262                LOGGER.error("Unexpected error: %s", str(exe))263                result = False264    else:265        LOGGER.info('Given Stack Set already exist: %s', active_stack_sets)266    return result267def deploy_config_stackset(ss_name, admin_role_arn, regions, deploy_to):268    '''Deploy config stackset'''269    config_result = False270    stack_status = False271    result = False272    all_accounts = list_from_stack_instances(CONFIG_STACK, key='Account')273    LOGGER.info('List of AWS Accounts: %s', all_accounts)274    if CONFIG_STACK in list_stack_sets():275        config_body = get_stackset_body(CONFIG_STACK)276        config_params = get_stackset_parameters(CONFIG_STACK)277        LOGGER.info('Config ParamList: %s', config_params)278        config_result = launch_stackset(ss_name, config_body,279                                        config_params, admin_role_arn)280        LOGGER.info('Config Stackset: %s', config_result)281        if deploy_to != 'Future Only':282            LOGGER.info('Deploy To setting: %s', deploy_to)283            operation_id = add_stack_instance(ss_name, all_accounts,284                                              regions)285            LOGGER.info('Operation ID: %s', operation_id)286            stack_status = get_stack_operation_status(ss_name,287                                                      operation_id)288        else:289            LOGGER.info('Skipping current accounts: %s', deploy_to)290            stack_status = True291    else:292        LOGGER.error('StackSet %s not found: %s',293                     CONFIG_STACK, list_stack_sets())294    if config_result and stack_status:295        result = True296    return result297def deploy_cnfpack_stackset(ss_name, admin_role_arn,298                            sse_algorithm, kms_key, log_account_id):299    '''Deploy config stackset'''300    result = False301    cnf_params = list()302    key_dict = dict()303    key_dict['ParameterKey'] = 'OrgId'304    key_dict['ParameterValue'] = get_org_id()305    cnf_params.append(key_dict)306    key_dict = dict()307    key_dict['ParameterKey'] = 'SSEAlgorithm'...cloudformation.py
Source:cloudformation.py  
...25        stack_set_info = self.client.describe_stack_set(26            StackSetName=stack_set_name27        )["StackSet"]28        return stack_set_info29    def list_stack_sets(self, status):30        summaries = self.client.list_stack_sets(31            Status=status32        )["Summaries"]33        return summaries34    def update_stack_set(self, stack_set_name, description, tags, parameters=None, capabilities=None, region_order=None):35        if parameters is None:36            parameters = []37        if capabilities is None:38            capabilities = []39        if region_order is None:40            region_order = []41        operation_id = self.client.update_stack_set(42            StackSetName=stack_set_name,43            Description=description,44            UsePreviousTemplate=True,...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!!
