aboutsummaryrefslogtreecommitdiff
path: root/sections/cloudwatch.py
blob: 65a59d684f5e2362a316a9bc64b28523570021d9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# cloudwatch.py
import boto3
import datetime
from tabulate import tabulate


def get_section(config):
    profile = config["aws"].get("profile")
    region = config["aws"]["region"]
    session = boto3.Session(
        profile_name=profile if profile else None, region_name=region
    )
    client = session.client("cloudwatch")

    now = datetime.datetime.utcnow()
    yesterday = now - datetime.timedelta(days=1)

    alarms = client.describe_alarms(StateValue="ALARM")["MetricAlarms"]
    rows = []

    for alarm in alarms:
        last_updated = alarm["StateUpdatedTimestamp"]
        if last_updated >= yesterday:
            rows.append(
                [
                    alarm["AlarmName"],
                    alarm["MetricName"],
                    alarm["StateValue"],
                    last_updated.strftime("%Y-%m-%d %H:%M UTC"),
                ]
            )

    if not rows:
        return "CloudWatch Alarms:\nNo alarms triggered in the last 24h."

    table = tabulate(
        rows, headers=["Name", "Metric", "State", "Updated"], tablefmt="simple_grid"
    )
    lines = [
        "CloudWatch Alarms (Last 24h):",
        f"[https://{config['aws'].get('region')}.console.aws.amazon.com/cloudwatch/home#alarmsV2:]",
        table,
    ]

    return "\n".join(lines)