Best Python code snippet using localstack_python
boss-account.py
Source:boss-account.py  
...117            count += 1118            delete_alarms.append(alarm['AlarmName'])119            if count >= 10:120                # delete alarms in batches of 10.121                resp = self.client_cw.delete_alarms(AlarmNames=delete_alarms)122                if resp['ResponseMetadata']['HTTPStatusCode'] is not 200:123                    raise ConnectionError("Received HTTPStatusCode: {} when trying to delete following alarms: {}"124                                          .format(resp['ResponseMetadata']['HTTPStatusCode'], ", ".join(delete_alarms)))125                delete_alarms.clear()126                count = 0127        if count > 0:128            resp = self.client_cw.delete_alarms(AlarmNames=delete_alarms)129            if resp['ResponseMetadata']['HTTPStatusCode'] is not 200:130                raise ConnectionError("Received HTTPStatusCode: {} when trying to delete following alarms: {}"131                                      .format(resp['ResponseMetadata']['HTTPStatusCode'], ", ".join(delete_alarms)))132        print("finished deleting billing alarms")133    def list(self):134        # Using paginator since there could be more then 100 alarms.135        paginator = self.client_cw.get_paginator('describe_alarms')136        # Create a PageIterator from the Paginator137        page_iterator = paginator.paginate(AlarmNamePrefix='Billing')138        alarms = []139        for page in page_iterator:140            alarms.extend(page['MetricAlarms'])141        print("Alarms count = {}".format(len(alarms)))142        print("end of list")...aws-cw-alarms-with-missing-dimensions.py
Source:aws-cw-alarms-with-missing-dimensions.py  
...16            result = client.describe_instances(InstanceIds=[dimension['Value']])17        except ClientError as e:18            if 'InvalidInstanceID.NotFound' in str(e):19                if args.delete:20                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])21                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])22                else:23                    print("\"%s\": Instance '%s' not found" % (alarm['AlarmName'], dimension['Value']))24            else:25                print("InstanceId error '%s'" % (e))26                print("%s: %s" % (alarm['AlarmName'], dimension['Value']))27    elif dimension['Name'] == 'AutoScalingGroupName':28        try:29            client = boto3.client('autoscaling')30            result = client.describe_auto_scaling_groups(AutoScalingGroupNames=[dimension['Value']])31            if not result['AutoScalingGroups']:32                if args.delete:33                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])34                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])35                else:36                    print("\"%s\": AutoScalingGroup '%s' not found" % (alarm['AlarmName'], dimension['Value']))37        except ClientError as e:38            print("AutoScalingGroupName error '%s'" % (e))39            print("%s: %s" % (alarm['AlarmName'], dimension['Value']))40    elif dimension['Name'] == 'LoadBalancerName':41        try:42            client = boto3.client('elb')43            result = client.describe_load_balancers(LoadBalancerNames=[dimension['Value']])44            if not result['LoadBalancerDescriptions']:45                if args.delete:46                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])47                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])48                else:49                    print("\"%s\": Classic LoadBalancer '%s' not found" % (alarm['AlarmName'], dimension['Value']))50        except ClientError as e:51            if 'LoadBalancerNotFound' in str(e):52                if args.delete:53                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])54                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])55                else:56                    print("\"%s\": DBInstance '%s' not found" % (alarm['AlarmName'], dimension['Value']))57            else:58                print("Classic LoadBalancer error '%s'" % (e))59                print("%s: %s" % (alarm['AlarmName'], dimension['Value']))60    elif dimension['Name'] == 'LoadBalancer':61        if re.search('/', dimension['Value']):62            dimension['Value'] = re.split(r'/', dimension['Value'])[1]63        try:64            client = boto3.client('elbv2')65            result = client.describe_load_balancers(Names=[dimension['Value']])66            if not result['LoadBalancers']:67                if args.delete:68                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])69                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])70                else:71                    print("\"%s\": ELBv2 LoadBalancer '%s' not found" % (alarm['AlarmName'], dimension['Value']))72        except ClientError as e:73            if 'LoadBalancerNotFound' in str(e):74                if args.delete:75                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])76                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])77                else:78                    print("\"%s\": DBInstance '%s' not found" % (alarm['AlarmName'], dimension['Value']))79            else:80                print("ELBv2 LoadBalancer error '%s'" % (e))81                print("%s: %s" % (alarm['AlarmName'], dimension['Value']))82    elif dimension['Name'] == 'DBInstanceIdentifier':83        try:84            client = boto3.client('rds')85            result = client.describe_db_instances(DBInstanceIdentifier=dimension['Value'])86            if not result['DBInstances']:87                if args.delete:88                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])89                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])90                else:91                    print("\"%s\": DBInstance '%s' not found" % (alarm['AlarmName'], dimension['Value']))92        except ClientError as e:93            if 'DBInstanceNotFound' in str(e):94                if args.delete:95                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])96                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])97                else:98                    print("\"%s\": DBInstance '%s' not found" % (alarm['AlarmName'], dimension['Value']))99            else:100                print("DBInstanceIdentifier error '%s'" % (e))101                print("%s: %s" % (alarm['AlarmName'], dimension['Value']))102    elif dimension['Name'] == 'TableName':103        try:104            client = boto3.client('dynamodb')105            result = client.describe_table(TableName=dimension['Value'])106            if not result['Table']:107                if args.delete:108                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])109                    print("AlarmName \"%s\" deleted" % alarm['AlarmName'])110                else:111                    print("\"%s\": Table '%s' not found" % (alarm['AlarmName'], dimension['Value']))112        except ClientError as e:113            print("TableName error '%s'" % (e))114            print("%s: %s" % (alarm['AlarmName'], dimension['Value']))115    elif args.verbose:116            print("** UNHANDLED RESOURCE ** \"%s\": %s" % (alarm['AlarmName'], str(dimension)))117if __name__ == "__main__":118    parser = argparse.ArgumentParser(description='CloudWatch Alarm Auditing')119    parser.add_argument('-d', '--delete',120                        action='store_true',121                        help='Delete alarms with missing dimensions')122    parser.add_argument('-v', '--verbose',123                        action='store_true',124                        help='Display all alarms')125    parser.add_argument('--debug',126                        action=Debug, nargs=0,127                        help=argparse.SUPPRESS)128    args = parser.parse_args()129    cloudwatch = boto3.client('cloudwatch')130    paginator = cloudwatch.get_paginator('describe_alarms')131    response = paginator.paginate().build_full_result()132    for alarm in response['MetricAlarms']:133        if 'Namespace' in alarm.keys() and alarm['Namespace'] == 'InternetAvailability':134            # Skip Namespace checks135            continue136        if not alarm['Dimensions']:137            if 'Metrics' in alarm:138                for metric in alarm['Metrics']:139                    if 'MetricStat' in metric:140                        if not metric['MetricStat']['Metric']['Dimensions']:141                            print("\"%s\": Empty dimensions with MetricStat metrics, state is %s" % (alarm['AlarmName'], alarm['StateValue']))142                            break143                        else:144                            for dimension in metric['MetricStat']['Metric']['Dimensions']:145                                parse_dimensions(dimension)146            else:147                if args.delete:148                    cloudwatch.delete_alarms(AlarmNames=[alarm['AlarmName']])149                    print("AlarmName \"%s\" deleted, state was %s" % (alarm['AlarmName'], alarm['StateValue']))150                else:151                    print("\"%s\": Empty dimensions, state is %s" % (alarm['AlarmName'], alarm['StateValue']))152        else:153            for dimension in alarm['Dimensions']:...__init__.py
Source:__init__.py  
...13        ]14    except Exception as error:15        print(error)16        exit(1)17def delete_alarms(alarm_names: list) -> bool:18    try:19        client = boto3.client('cloudwatch')20        client.delete_alarms(AlarmNames=alarm_names)21        return True22    except Exception as error:23        print(error)24        exit(1)25class CloudwatchResources:26    27    @classmethod28    async def init(cls):29        self = cls()30        self.alarm_names = list_alarm_names()31        return self32    33    def print(self):34        print("==== Cloudwatch Alarms ====")35        pprint(self.alarm_names)36    37    def delete(self):38        if self.alarm_names:39            delete_alarms(self.alarm_names)...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!!
