Best Python code snippet using localstack_python
cloudformation.py
Source:cloudformation.py  
...254            message = {'FILE': __file__.split('/')[-1], 'CLASS': self.__class__.__name__,255                       'METHOD': inspect.stack()[0][3], 'EXCEPTION': str(e)}256            self.logger.exception(message)257            raise258    def list_stack_set_operations(self, **kwargs):259        try:260            response = cfn_client.list_stack_set_operations(**kwargs)261            return response262        except Exception as e:263            message = {'FILE': __file__.split('/')[-1], 'CLASS': self.__class__.__name__,264                       'METHOD': inspect.stack()[0][3], 'EXCEPTION': str(e)}265            self.logger.exception(message)266            raise267class Stacks(object):268    def __init__(self, logger, **kwargs):269        self.logger = logger270        if kwargs is not None:271            if kwargs.get('credentials') is None:272                logger.debug("Setting up CFN BOTO3 Client with default credentials")273                self.cfn_client = boto3.client('cloudformation')274            else:...core.py
Source:core.py  
...132        if flip(body) == flip(descresp['StackSet']['TemplateBody']):133            send_to_slack('(Roles deployment) No change to StackSet CFN template')134        else:135            send_to_slack('(Roles deployment) Change detected in StackSet CFN template, updating StackSet')136            response = cfn.list_stack_set_operations(137                StackSetName=stacksetname_roles138                )139            operation_pending = False140            for i in response['Summaries']:141                if i['Status'] == 'RUNNING':142                    operation_pending = True143            while operation_pending == True:144                send_to_slack('Another StackSet operation is in progress, waiting 10 seconds before retrying')145                time.sleep(10)146                response = cfn.list_stack_set_operations(147                    StackSetName=stacksetname_roles148                    )149                operation_pending = False150                for i in response['Summaries']:151                    if i['Status'] == 'RUNNING':152                        operation_pending = True153            response = cfn.update_stack_set(154                StackSetName=stacksetname_roles,155                TemplateURL=template_url_roles,156                Parameters=parameters,157                OperationPreferences={158                    'FailureToleranceCount': 99,159                    'MaxConcurrentCount': 100160                },161                Description=stackset_description,162                AdministrationRoleARN=adminrolearn,163                ExecutionRoleName=executionrolename,164                Capabilities=['CAPABILITY_NAMED_IAM']165                )166            wait_timer_next_deployment = 30167    ### Regional168    time.sleep(wait_timer_next_deployment)169    to_create_stack_set = False170    try:171        descresp = cfn.describe_stack_set(StackSetName=stacksetname_regional)172        send_to_slack("StackSet: <%s|%s>" % ("https://ap-southeast-2.console.aws.amazon.com/cloudformation/home?region=ap-southeast-2#/stackset/detail?stackSetId=" + stacksetname_regional, stacksetname_regional))173    except Exception as e:174        print(e)175        if 'not found' in str(e):176            to_create_stack_set = True177    if to_create_stack_set is True:178        response = cfn.create_stack_set(179            StackSetName=stacksetname_regional,180            Description=stackset_description_regional,181            Parameters=parameters,182            TemplateURL=template_url_regional,183            Capabilities=['CAPABILITY_NAMED_IAM'],184            Tags=Tags,185            AdministrationRoleARN=adminrolearn,186            ExecutionRoleName=executionrolename,187        )188        response = cfn.create_stack_instances(189            StackSetName=stacksetname_regional,190            Accounts=stackset_principals,191            OperationPreferences={192                'FailureToleranceCount': 99,193                'MaxConcurrentCount': 100194            },195            Regions=[196                'ap-southeast-2',197                'us-east-1'198            ]199        )200        send_to_slack("StackSet created: <%s|%s>" % (f"https://ap-southeast-2.console.aws.amazon.com/cloudformation/home?region=ap-southeast-2#/stacksets/{stacksetname_regional}/info", stacksetname_regional))201    else:202        # Add missing stack instances (stack instances = AWS accounts)203        stackset_principals = []204        current_principals = []205        response = cfn.list_stack_instances(206            StackSetName=stacksetname_regional207            )208        for i in response['Summaries']:209            current_principals.append(i['Account'])210        diff_principals = set(stackset_principals) - set(current_principals)211        if diff_principals:212            diff_alias = []213            for p in diff_principals:214                diff_alias.append([j['AWSAccountAlias'] for j in accresp['Items'] if p == j['AWSAccountID']][0])215            print(sorted(diff_alias))216            send_to_slack('Adding missing principals to StackSet instances: %s' % "\n>".join(sorted(diff_alias)))217            response = cfn.create_stack_instances(218                StackSetName=stacksetname_regional,219                Accounts=list(diff_principals),220                Regions=[221                    'ap-southeast-2',222                    'us-east-1'223                    ]224                )225        else:226            send_to_slack('(Regional deployment) No change to StackSet instance principals')227        # Update template if there are missing or removed CFN exports228        s3 = boto3.resource('s3')229        obj = s3.Object(template_bucket, template_key_regional)230        body = obj.get()['Body'].read()231        if flip(body) == flip(descresp['StackSet']['TemplateBody']):232            send_to_slack('(Regional deployment) No change to StackSet CFN template')233        else:234            send_to_slack('(Regional deployment) Change detected in StackSet CFN template, updating StackSet')235            response = cfn.list_stack_set_operations(236                StackSetName=stacksetname_regional237                )238            operation_pending = False239            for i in response['Summaries']:240                if i['Status'] == 'RUNNING':241                    operation_pending = True242            while operation_pending == True:243                send_to_slack('Another StackSet operation is in progress, waiting 10 seconds before retrying')244                time.sleep(10)245                response = cfn.list_stack_set_operations(246                    StackSetName=stacksetname_regional247                    )248                operation_pending = False249                for i in response['Summaries']:250                    if i['Status'] == 'RUNNING':251                        operation_pending = True252            response = cfn.update_stack_set(253                StackSetName=stacksetname_regional,254                TemplateURL=template_url_regional,255                Parameters=parameters,256                OperationPreferences={257                    'FailureToleranceCount': 99,258                    'MaxConcurrentCount': 100259                },...wait.py
Source:wait.py  
...12    # Whether no operations should cause the function to error. It should be true when creating an instance13    # but false when waiting for delete operations to complete.14    error_if_no_operations = event["error_if_no_operations"]15    client = boto3.client("cloudformation")16    stack_operations = client.list_stack_set_operations(StackSetName=stack_name)17    if error_if_no_operations and not stack_operations["Summaries"]:18        # Fail if the stack operations are still not available19        raise StackSetExecutionInProgressException()20    for operation in stack_operations["Summaries"]:21        # The stackset operation hasn't completed22        if operation["Status"] in STACKSET_OPERATION_INCOMPLETE_STATUSES:23            raise StackSetExecutionInProgressException()24    stack_instances = client.list_stack_instances(StackSetName=stack_name)25    for instance in stack_instances["Summaries"]:26        # Stack instances are in progress of being updated27        if (28            instance["Status"] != SYNCHRONIZED_STATUS29            or instance["StackInstanceStatus"]["DetailedStatus"] != SUCCESS_DETAILED_STATUS30        ):...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!!
