Diese Dateien liefen nur auf dem NAS und fehlten im Repository. Ab jetzt ist Gitea die Quelle, der NAS holt per git pull. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
99 lines
3.5 KiB
Python
99 lines
3.5 KiB
Python
"""AWS API Client via boto3.
|
|
|
|
Zugang aus der Umgebung: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import os
|
|
import boto3
|
|
|
|
def _session() -> boto3.Session:
|
|
return boto3.Session(
|
|
aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"),
|
|
aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY"),
|
|
region_name=os.environ.get("AWS_DEFAULT_REGION", "eu-central-1"),
|
|
)
|
|
|
|
def s3_buckets() -> list[dict]:
|
|
"""S3-Buckets auflisten."""
|
|
s3 = _session().client("s3")
|
|
res = s3.list_buckets()
|
|
return [{"name": b["Name"], "created": b["CreationDate"].isoformat()} for b in res.get("Buckets", [])]
|
|
|
|
def s3_objects(bucket: str, prefix: str = "", limit: int = 50) -> list[dict]:
|
|
"""Objekte in einem S3-Bucket auflisten."""
|
|
s3 = _session().client("s3")
|
|
res = s3.list_objects_v2(Bucket=bucket, Prefix=prefix, MaxKeys=min(limit, 200))
|
|
return [{
|
|
"key": o["Key"],
|
|
"size_bytes": o["Size"],
|
|
"last_modified": o["LastModified"].isoformat(),
|
|
} for o in res.get("Contents", [])]
|
|
|
|
def ec2_instances() -> list[dict]:
|
|
"""EC2-Instanzen auflisten."""
|
|
ec2 = _session().client("ec2")
|
|
res = ec2.describe_instances()
|
|
aus = []
|
|
for r in res.get("Reservations", []):
|
|
for i in r.get("Instances", []):
|
|
name = next((t["Value"] for t in i.get("Tags", []) if t["Key"] == "Name"), "")
|
|
aus.append({
|
|
"id": i.get("InstanceId"),
|
|
"name": name,
|
|
"type": i.get("InstanceType"),
|
|
"state": i.get("State", {}).get("Name"),
|
|
"public_ip": i.get("PublicIpAddress"),
|
|
"private_ip": i.get("PrivateIpAddress"),
|
|
})
|
|
return aus
|
|
|
|
def cost_and_usage(days: int = 30) -> dict:
|
|
"""AWS-Kosten der letzten Tage über Cost Explorer abfragen."""
|
|
ce = _session().client("ce")
|
|
heute = datetime.date.today()
|
|
start = heute - datetime.timedelta(days=days)
|
|
res = ce.get_cost_and_usage(
|
|
TimePeriod={"Start": start.strftime("%Y-%m-%d"), "End": heute.strftime("%Y-%m-%d")},
|
|
Granularity="MONTHLY",
|
|
Metrics=["UnblendedCost"],
|
|
GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
|
|
)
|
|
services_cost = []
|
|
total_usd = 0.0
|
|
for period in res.get("ResultsByTime", []):
|
|
for group in period.get("Groups", []):
|
|
srv = group["Keys"][0]
|
|
amount = float(group["Metrics"]["UnblendedCost"]["Amount"])
|
|
if amount > 0.001:
|
|
services_cost.append({"service": srv, "cost_usd": round(amount, 2)})
|
|
total_usd += amount
|
|
services_cost.sort(key=lambda x: x["cost_usd"], reverse=True)
|
|
return {
|
|
"period": f"{start} bis {heute}",
|
|
"total_cost_usd": round(total_usd, 2),
|
|
"by_service": services_cost,
|
|
}
|
|
|
|
def security_groups() -> list[dict]:
|
|
"""Security Groups und offene Ports auflisten."""
|
|
ec2 = _session().client("ec2")
|
|
res = ec2.describe_security_groups()
|
|
aus = []
|
|
for sg in res.get("SecurityGroups", []):
|
|
rules = []
|
|
for p in sg.get("IpPermissions", []):
|
|
rules.append({
|
|
"protocol": p.get("IpProtocol"),
|
|
"from_port": p.get("FromPort"),
|
|
"to_port": p.get("ToPort"),
|
|
})
|
|
aus.append({
|
|
"id": sg.get("GroupId"),
|
|
"name": sg.get("GroupName"),
|
|
"description": sg.get("Description"),
|
|
"rules": rules,
|
|
})
|
|
return aus
|