Skip to content

Commit a9bece9

Browse files
diodonfrostCircleCI
authored andcommitted
refactor(python): enhance CloudWatch alarm scheduler with improved method organization
Refactored the CloudWatchAlarmScheduler class to improve code clarity and maintainability. Added detailed docstrings for methods, reorganized start and stop functionalities to utilize a shared processing method, and introduced logging for actions taken on CloudWatch alarms.
1 parent badd34b commit a9bece9

File tree

1 file changed

+51
-47
lines changed

1 file changed

+51
-47
lines changed
Lines changed: 51 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,76 @@
11
"""Cloudwatch alarm action scheduler."""
22

3-
from typing import Dict, List
3+
from typing import Dict, List, Optional
4+
import logging
45

56
import boto3
6-
77
from botocore.exceptions import ClientError
88

99
from .exceptions import cloudwatch_exception
1010
from .filter_resources_by_tags import FilterByTags
1111

1212

1313
class CloudWatchAlarmScheduler:
14-
"""Abstract Cloudwatch alarm scheduler in a class."""
14+
"""CloudWatch alarm scheduler for enabling/disabling alarm actions based on tags.
1515
16-
def __init__(self, region_name=None) -> None:
17-
"""Initialize Cloudwatch alarm scheduler."""
18-
if region_name:
19-
self.cloudwatch = boto3.client("cloudwatch", region_name=region_name)
20-
else:
21-
self.cloudwatch = boto3.client("cloudwatch")
22-
self.tag_api = FilterByTags(region_name=region_name)
16+
This class provides functionality to start (enable) or stop (disable) CloudWatch
17+
alarm actions that match specific AWS resource tags.
18+
"""
2319

24-
def stop(self, aws_tags: List[Dict]) -> None:
25-
"""Aws Cloudwatch alarm disable function.
20+
def __init__(self, region_name: Optional[str] = None) -> None:
21+
"""Initialize CloudWatch alarm scheduler with the specified AWS region.
2622
27-
Disable Cloudwatch alarm with defined tags.
23+
Args:
24+
region_name: Optional AWS region name. If not provided, the default
25+
region from AWS configuration will be used.
26+
"""
27+
self.cloudwatch = (
28+
boto3.client("cloudwatch", region_name=region_name)
29+
if region_name
30+
else boto3.client("cloudwatch")
31+
)
32+
self.tag_api = FilterByTags(region_name=region_name)
33+
self.logger = logging.getLogger(__name__)
2834

29-
:param list[map] aws_tags:
30-
Aws tags to use for filter resources.
31-
For example:
32-
[
33-
{
34-
'Key': 'string',
35-
'Values': [
36-
'string',
37-
]
38-
}
39-
]
35+
def _process_alarms(self, aws_tags: List[Dict], enable: bool) -> None:
36+
"""Process CloudWatch alarms by enabling or disabling them.
37+
38+
Args:
39+
aws_tags: AWS tags to filter resources by
40+
enable: True to enable alarms, False to disable alarms
4041
"""
42+
action = "enable" if enable else "disable"
43+
method = (
44+
self.cloudwatch.enable_alarm_actions
45+
if enable
46+
else self.cloudwatch.disable_alarm_actions
47+
)
48+
action_present = "Enabling" if enable else "Disabling"
49+
action_past = "Enabled" if enable else "Disabled"
50+
4151
for alarm_arn in self.tag_api.get_resources("cloudwatch:alarm", aws_tags):
4252
alarm_name = alarm_arn.split(":")[-1]
4353
try:
44-
self.cloudwatch.disable_alarm_actions(AlarmNames=[alarm_name])
45-
print(f"Disable Cloudwatch alarm {alarm_name}")
54+
method(AlarmNames=[alarm_name])
55+
self.logger.info(f"{action_past} CloudWatch alarm {alarm_name}")
56+
print(f"{action_past} CloudWatch alarm {alarm_name}")
4657
except ClientError as exc:
4758
cloudwatch_exception("cloudwatch alarm", alarm_name, exc)
4859

49-
def start(self, aws_tags: List[Dict]) -> None:
50-
"""Aws Cloudwatch alarm enable function.
60+
def stop(self, aws_tags: List[Dict]) -> None:
61+
"""Disable CloudWatch alarm actions for resources with the specified tags.
5162
52-
Enable Cloudwatch alarm with defined tags.
63+
Args:
64+
aws_tags: AWS tags to filter resources by.
65+
Format: [{'Key': 'tag_key', 'Values': ['tag_value', ...]}]
66+
"""
67+
self._process_alarms(aws_tags, enable=False)
68+
69+
def start(self, aws_tags: List[Dict]) -> None:
70+
"""Enable CloudWatch alarm actions for resources with the specified tags.
5371
54-
:param list[map] aws_tags:
55-
Aws tags to use for filter resources.
56-
For example:
57-
[
58-
{
59-
'Key': 'string',
60-
'Values': [
61-
'string',
62-
]
63-
}
64-
]
72+
Args:
73+
aws_tags: AWS tags to filter resources by.
74+
Format: [{'Key': 'tag_key', 'Values': ['tag_value', ...]}]
6575
"""
66-
for alarm_arn in self.tag_api.get_resources("cloudwatch:alarm", aws_tags):
67-
alarm_name = alarm_arn.split(":")[-1]
68-
try:
69-
self.cloudwatch.enable_alarm_actions(AlarmNames=[alarm_name])
70-
print(f"Enable Cloudwatch alarm {alarm_name}")
71-
except ClientError as exc:
72-
cloudwatch_exception("cloudwatch alarm", alarm_name, exc)
76+
self._process_alarms(aws_tags, enable=True)

0 commit comments

Comments
 (0)