Generated banner for Amazon Aurora Postgresql
Generated logo for Amazon Aurora Postgresql

Amazon Aurora Postgresql

AWSOfficialPublished by AWS

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Amazon Aurora PostgreSQL — creates, modifies, and advises on Aurora PostgreSQL clusters specifically (PostgreSQL-compatible engine, Aurora serverless, express configuration, pgvector, Babelfish). Trigger for Aurora PostgreSQL cluster operations, express-configuration quick-start, ACU sizing, I/O-Optimized storage, commitment pricing, or PostgreSQL upgrade planning. For Aurora MySQL, use amazon-aurora-mysql instead. Contains safety guardrails, express-first routing, and response templates that override defaults.
— the description by AWS

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Amazon Aurora PostgreSQL provides a structured approach to managing Aurora PostgreSQL clusters, offering sub-skills for cluster creation, serverless capacity planning, storage optimization, commitment-based cost analysis, and version upgrade planning. It includes safety guardrails for resource mutations and utilizes specific scripts for sizing and financial modeling. The skill is designed to route user requests to the appropriate domain-specific instructions while ensuring consistent resource tagging and adherence to AWS operational best practices.

What it does

  • Provisions Aurora PostgreSQL clusters using either express or full configuration workflows.
  • Analyzes Aurora serverless capacity requirements and ACU sizing.
  • Evaluates the cost-benefit of switching to I/O-Optimized storage.
  • Compares Reserved Instances and Database Savings Plans for cost optimization.
  • Provides guidance and checklists for major and minor version upgrades.
  • Applies mandatory resource tagging and safety guardrails for all cluster operations.

When to use it

  • When you need to create or modify an Aurora PostgreSQL cluster.
  • When planning capacity for Aurora serverless or evaluating ACU scaling.
  • When assessing whether to switch to I/O-Optimized storage.
  • When comparing Reserved Instances versus Database Savings Plans.
  • When preparing for a major or minor PostgreSQL version upgrade.

Advantages

  • Automates complex configuration decisions through a structured decision matrix.
  • Provides consistent, script-based financial analysis for cost optimization.
  • Enforces safety guardrails to prevent accidental production impact.
  • Ensures standardized resource tagging for all created infrastructure.
  • Simplifies connection management for express-configured clusters via IAM auth.

Usage examples

“I need to set up a new Aurora PostgreSQL database.”
The agent identifies the request as a cluster creation task, determines whether to use express or full configuration based on your requirements, and guides you through the provisioning process.
“Should I switch my cluster to I/O-Optimized storage?”
The agent evaluates your current I/O usage against the 25% cost threshold rule and provides a recommendation on whether the switch is cost-effective.
“Help me compare Reserved Instances and Savings Plans for my cluster.”
The agent runs a commitment pricing analysis to show potential savings over 1-year or 3-year terms based on your specific instance type and region.
“How do I plan for a major version upgrade of my Aurora PostgreSQL cluster?”
The agent provides a pre-upgrade checklist, recommends a target version, and suggests a blue/green deployment strategy.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/aws/amazon-aurora-postgresql/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip amazon-aurora-postgresql.zip -d .agents/skills

Documentation by AWS

Amazon Aurora PostgreSQL

A modular toolkit for Aurora PostgreSQL organized as a registry of sub-skills. Each sub-skill handles one domain of Aurora PostgreSQL work. The router matches user intent to the right sub-skill, then loads only the references needed. (For Aurora MySQL, use the amazon-aurora-mysql skill.)

Operating procedure (follow in order)

  1. Route — match the request to a sub-skill using the Trigger phrases column (match on meaning, not exact wording), then confirm with the When to route here column.

  2. Load — file_read the matched sub-skill's references/{id}-instructions.md and announce the path. Do not answer a matched sub-skill from general knowledge alone.

  3. Analyze / advise — perform the sub-skill's work; run a bundled script when the user supplies the inputs (see Scripts).

  4. If a mutation is requested — classify against the Safety guardrails tier, confirm with the user, apply resource tags, then execute (MCP-preferred, CLI fallback).

  5. Present results — tables with dollar/ACU figures and a recommendation label; no derivation or arithmetic steps.

Edge cases: if the request spans multiple sub-skills, run them in sequence (load each instructions.md in turn). If no sub-skill matches, answer directly from Aurora PostgreSQL knowledge. If a script or MCP/CLI call fails, show the error and suggest a fix before retrying. The numbered Global rules below are details that hang off these steps.

Sub-skill registry

Column semantics: Trigger phrases = the keyword index you match the request against (step 1). When to route here = the decision logic confirming the match. Next steps = sub-skills to offer the user as a natural follow-up after this one completes (not auto-chained); Reached from = sub-skills that typically route into this one. Next-steps/Reached-from are suggestions for guiding the user, never automatic execution.

IDNameWhen to route hereTrigger phrasesReached fromNext steps
createCreate ClusterRoutes Aurora PostgreSQL cluster creation requests. Express configuration (single API call, no VPC) is the default — routes to express-create. Routes to full configuration when VPC, custom KMS, custom params, or a specific engine version is required.create a cluster, new database, set up Aurora PostgreSQL, get started, need a PostgreSQL database, provision—express-create, serverless-advisory, io-optimized
express-createExpress ConfigurationProvisions Aurora PostgreSQL serverless via the single-API-call express flow. AWS-managed connectivity (no customer VPC). IAM-only authentication via Internet Access Gateway — no master password. Post-creation connection is via IAM auth token (aws rds generate-db-auth-token). Use when no VPC, custom KMS, or custom parameter group is required. Routes back to create for full configuration needs.express configuration, express create, internet access gateway, single API call, Aurora PostgreSQL serverless quick start, no VPC, IAM auth token, how to connect to express clustercreate—
serverless-advisoryAurora serverless AdvisoryAll Aurora serverless questions: ACU sizing, scale-to-zero behavior and compatibility, provisioned→serverless migration, capacity planning, and feature constraints.ACU sizing, Aurora serverless, scale-to-zero, provisioned to serverless, how many ACUs, capacity, auto-scaling, RDS Proxy compatibility, scale-to-zero incompatibility, serverless limitationscreate (optional)commitment-pricing
io-optimizedI/O-Optimized StorageEvaluates whether to switch from Aurora Standard to I/O-Optimized (aurora-iopt1). Uses the 25% I/O cost threshold rule.I/O-Optimized, aurora-iopt1, storage type switch, 25% threshold, I/O costs too high, storage comparison——
commitment-pricingCommitment PricingCompares Reserved Instances vs Database Savings Plans for provisioned clusters, and DSP-only for Aurora serverless. 1yr vs 3yr analysis.Reserved Instance, RI, Savings Plan, DSP, 1yr vs 3yr, commitment, cost optimization, overpayingserverless-advisory (optional)—
upgrade-planningUpgrade PlanningMajor and minor version upgrade planning for Aurora PostgreSQL. LTS version guidance, pre/post-upgrade checklists, blue/green deployment recommendations.upgrade, version, LTS, pre-upgrade checklist, post-upgrade, major version, minor version, end of life, deprecation——

Express vs Full configuration — decision matrix

When routing a create request (sub-skill create), pick the path with this matrix. Express is the default for Aurora PostgreSQL; route to Full configuration only if ANY "Full" trigger is present. Don't present the choice to the user — decide, then state which path and why.

Requirement / signalExpressFull config
Default PostgreSQL create, no special networking✅ default—
Quick start / "no VPC setup" / "ready in seconds"✅—
Customer VPC, subnet group, or specific security group—✅ required
Customer-managed KMS key (CMK)—✅ required
Custom DB cluster parameter group at creation—✅ required
Specific engine version pinned by the user—✅ required (intent to pin = not express)
Aurora MySQLn/ause amazon-aurora-mysql (express is PG-only)

Notes: any single Full trigger disqualifies express — name every trigger you matched in the routing statement. Express clusters are still customizable after creation (e.g. a custom parameter group can be applied post-create), so a future need isn't itself a reason to start with Full. Full depth on the flow lives in references/express-create-instructions.md and references/create-instructions.md — load those for the actual steps.

Global rules (apply to every sub-skill)

  1. Execute, don't just suggest. When the user requests an action and confirms, EXECUTE it rather than handing back a command to run. The AWS MCP server is the recommended execution path when available (sandboxed, IAM-authenticated, audit-logged) — prefer it. When MCP tools are not available (e.g. Claude Code, Cursor, or other non-MCP hosts), use the AWS CLI / SDK directly with the same aws rds ... operation. Only if execution is genuinely not possible in the current environment, present the complete CLI command for the user to run.

  2. Confirmation before mutation. MUST confirm with the user before any create or modify operation. Do NOT execute without explicit confirmation ("yes", "proceed", "confirmed", "go ahead").

  3. Resource tagging (always apply on resource creation). When creating any cluster or instance, ALWAYS include these tags: --tags Key=created_by,Value=aurora-skill Key=generation_model,Value={your-model-id} Use your model id if known; if you cannot reliably determine it, use Value=unknown — never let tagging block the create. Include these tags even if the user does not mention tagging. If the user provides additional tags, append these to their tags.

  4. Safety guardrails.

    Tier 1 — Confirm (a yes/no confirmation is enough; no risk briefing required):

    • create-db-cluster, create-db-cluster --with-express-configuration

    • create-db-instance

    • modify-db-cluster --serverless-v2-scaling-configuration (ACU scaling)

    • modify-db-cluster --backup-retention-period

    • modify-db-cluster --deletion-protection / --no-deletion-protection

    • modify-db-cluster --enable-cloudwatch-logs-exports

    • modify-db-cluster --preferred-backup-window

    • modify-db-cluster --enable-http-endpoint (Data API)

    • add-tags-to-resource, remove-tags-from-resource

    Tier 2 — High-impact: state the specific risk, THEN confirm (spell out the impact before asking; do not call any API until the user confirms with that risk in front of them):

    • modify-db-cluster --storage-type — no downtime for most instance classes; requires restart for NVMe/Optimized Reads instances (r6gd, r6id, r8gd). Switching from Aurora Standard to Aurora I/O-Optimized is limited to once every 30 days; switching from Aurora I/O-Optimized back to Aurora Standard can be done at any time.

    • modify-db-instance --db-instance-class — causes failover in multi-AZ

    • modify-db-cluster --engine-version for a minor version upgrade — applied in the maintenance window (or immediately with --apply-immediately); brief failover/restart. State the target version and the restart impact, then confirm. (For a major version upgrade, see Block below — route to upgrade-planning first.)

    • Any modify with --apply-immediately — bypasses maintenance window

    Tier 3 — Block (refuse, explain why, redirect to console/change-control):

    • delete-db-cluster, delete-db-instance — irreversible

    • failover-db-cluster, switchover-blue-green-deployment — production impact

    • modify-db-cluster --engine-version across major versions — requires prechecks and rollback plan

    • modify-db-cluster --master-user-password, --manage-master-user-password — credential management must be performed by the customer directly. Express clusters use IAM-only auth via the Internet Access Gateway and have no master password — these flags do not apply on express clusters and must NOT be used as a workaround for connection issues. For full-config clusters, use AWS Secrets Manager rotation or the AWS Console.

    • modify-db-cluster --vpc-security-group-ids — network security posture change

    • modify-db-cluster --db-cluster-parameter-group-name — can break applications

    • create-db-instance --publicly-accessible, modify-db-instance --publicly-accessible — NEVER make Aurora instances publicly accessible. This exposes the database directly to the internet and is never the correct solution for connectivity. See secure connection alternatives below.

    • purchase-reserved-db-instances-offering, create-savings-plan — financial commitment

    • reboot-db-instance, reboot-db-cluster — production impact

    When blocking, you MUST refuse immediately. Do NOT call any AWS API. Your response MUST have exactly two paragraphs:

    Paragraph 1 — refuse: "I can't perform [action] because [reason]. This should go through your team's change-control process or the AWS Console."

    Paragraph 2 — alternative (from the table below, always included):

    • purchase-reserved-db-instances-offering, create-savings-plan → "I can run a commitment pricing assessment (RI vs DSP comparison) so you have the numbers to bring to procurement."

    • delete-db-cluster, delete-db-instance → "I can help with snapshot creation or final-snapshot validation before deletion."

    • modify-db-cluster --engine-version (major version) → "I can run an upgrade assessment — target version recommendation, prechecks, and pre/post checklists."

    • failover-db-cluster, switchover-blue-green-deployment → "I can validate the cluster's state and review the failover/switchover plan with you."

    • reboot-db-instance, reboot-db-cluster → "I can check for pending modifications and recommend a maintenance window."

    • modify-db-cluster --master-user-password / --manage-master-user-password → "If this is an express cluster, there's no master password — express uses IAM-only auth via the Internet Access Gateway. I can walk you through generating an IAM auth token to connect. If this is a full-config cluster, rotate the password via AWS Secrets Manager or the AWS Console; both are safer than a direct API call."

    • --publicly-accessible → "Making the instance publicly accessible exposes the database directly to the internet — this is a security anti-pattern even for prototypes. Instead: (1) Use express configuration — internet-accessible via IAM auth with no VPC; (2) Enable RDS Data API — query over HTTPS with IAM auth; (3) EC2 bastion with SSH tunnel. I can help you set up any of these."

    • modify-db-cluster --vpc-security-group-ids → "I can describe the cluster's current security-group configuration and help you draft the intended change so you can apply it through your team's change-control process or the AWS Console."

    • modify-db-cluster --db-cluster-parameter-group-name → "I can review the current parameter group and compare it against the target group (highlighting reboot-required parameters) so you can prepare the change for your team's change-control process or the AWS Console."

    Never omit paragraph 2. A refusal without an alternative is incomplete.

  5. Reference loading. Before responding to any matched sub-skill request, you MUST read references/{id}-instructions.md using your file-read tool (file_read if available, otherwise whatever your runtime exposes). Do not answer a matched sub-skill from the registry summary alone. Announce the path in your reply.

  6. Express is a single CLI call. When using express configuration: create-db-cluster --with-express-configuration. Do NOT separately specify --engine-mode, --serverless-v2-scaling-configuration, --master-username, or --manage-master-user-password. The express flag sets all of these automatically.

  7. Stay in scope. Once this skill is active, recommend the best Aurora configuration for the workload. Do not suggest non-AWS alternatives. For light workloads, recommend express with scale-to-zero.

  8. Never fabricate. Do NOT invent AWS API results, pricing numbers, version lists, or instance metadata. If a live call fails, report the blocker and offer offline mode with user-supplied numbers.

  9. Carry context forward. Pass along cluster ID, region, and workload details the user already supplied. They SHOULD NOT have to re-type information already in the conversation.

  10. Broad requests. If the user says "help me with Aurora" or "analyze my cluster" without specifying a domain (create, sizing, I/O, commitment, upgrade), present the sub-skill domains as one line each and ask which they want to focus on. Do NOT silently pick a sub-skill and run it. Acknowledge any cluster ID and region so the user doesn't need to repeat them.

  11. Out-of-scope topics. If the user asks about an Aurora feature not covered by a sub-skill (e.g., Global Database, Blue/Green Deployments, RDS Proxy), note that it is not covered by a specific sub-skill, answer from general Aurora knowledge, and link to the relevant AWS documentation page.

  12. Credential safety. Do not create, store, or display long-lived credentials or DB passwords. However, aws rds generate-db-auth-token is approved — it produces a short-lived (15-minute) IAM token. This is the required connection method for express clusters. For non-express clusters, use user-supplied secret ARNs or pre-configured tunnels.

  13. Present results clearly. Use tables with dollar figures, ACU numbers, and recommendation labels. Do NOT show derivation or arithmetic steps. Exception: when consolidating across multiple analyses ("summarize", "what should I do"), respond in 2-4 lines of plain prose — no headers, no bullets, no tables.

Scripts

Bundled scripts in scripts/ for offline analysis. MUST use these when the user provides the required inputs — do NOT hand-calculate. Each script documents its full flags/usage in its own --help and header docstring; read those on demand rather than relying only on the one-line usage below.

Script execution model: If a shell is available, execute the script directly and present the output. If no shell is available, print the exact command as a fenced bash code block with all flags resolved to user-supplied values, then present results computed inline from the reference file's pricing tables. (Result-presentation format is governed by the Operating procedure / Global rules — no derivation steps.)

ScriptPurposeUsage
acu_calculator.pyAurora serverless ACU sizingpython3 scripts/acu_calculator.py estimate --instance <type> --cpu-p95 <val> --cpu-max <val> --storage <val>
io_optimized_analyzer.pyI/O-Optimized breakevenpython3 scripts/io_optimized_analyzer.py offline --instance <type> --num-instances <n> --storage-gib <val> --monthly-io-millions <val>
commitment_pricing_analyzer.pyRI vs DSP cost comparisonpython3 scripts/commitment_pricing_analyzer.py offline --instance <type> --num-instances <n> --region <region> (provisioned) or --serverless --avg-acu <val> (Aurora serverless)

Troubleshooting

  • AccessDenied: Attach AmazonRDSReadOnlyAccess + CloudWatchReadOnlyAccess for reads. For creates/modifies, use a custom policy scoped to rds:CreateDBCluster, rds:CreateDBInstance, rds:ModifyDBCluster, rds:ModifyDBInstance, rds:AddTagsToResource, and rds:Describe*. See Identity and access management for Amazon Aurora.

  • ExpiredToken / credentials: Refresh your AWS credentials using whatever mechanism you use (e.g. re-run your SSO/aws sso login, ada credentials update, assume-role, or refresh the profile), then retry. Do not assume a specific credential tool.

  • DBClusterNotFoundFault: Verify region and cluster ID.

  • Throttling: Retry once, then narrow scope.

Additional Resources

Handoff from aws-database-selection

This skill can be entered from aws-database-selection after it produces a requirements.json. When you see a path matching aws_dbs_requirements/*/requirements.json in conversation:

  1. Read the artifact. Sanity-check it has the fields you'll use — at minimum engine (or workload type), region, and the workload signals you route on (capacity/ACU hints, storage size, connectivity/VPC needs, version). If those are present and parseable, use them; if it's missing them or won't parse, proceed without it (don't block on a formal schema).

  2. Acknowledge relevant facts in 1-2 bold sentences.

  3. Scope-check: if the artifact doesn't match Aurora (e.g., key-access → DynamoDB, graph → Neptune, multi-region strong SQL → DSQL), suggest the right skill and ask whether to proceed anyway.

  4. Continue with this skill's sub-skill routing.

Files

scripts/commitment_pricing_analyzer.py

"""Aurora Reserved Instance & Database Savings Plan estimator.

Read-only tool that fetches live RI and DSP rates from AWS and projects
monthly cost under each commitment option for a cluster, fleet, or
user-supplied workload. No purchase APIs are ever called.

Usage:
    python commitment_pricing_analyzer.py --cluster my-cluster --region us-east-1
    python commitment_pricing_analyzer.py --all --region us-east-1
    python commitment_pricing_analyzer.py offline \\
        --instance db.r7g.2xlarge --num-instances 2 --region us-east-1
    python commitment_pricing_analyzer.py offline \\
        --serverless --avg-acu 8 --region us-east-1
"""

from __future__ import annotations

import argparse
import json
import re
import sys
from dataclasses import dataclass

HOURS_PER_MONTH = 730

# ---------------------------------------------------------------------------
# Static fallback on-demand prices (us-east-1, Aurora PostgreSQL/MySQL Standard).
# I/O-Optimized premium applied via multiplier.
# ---------------------------------------------------------------------------
IO_OPT_COMPUTE_MULTIPLIER = 1.30
ACU_PRICE_STANDARD = 0.12  # $/ACU-Hr
ACU_PRICE_IO_OPTIMIZED = 0.156

_STATIC_INSTANCE_PRICES = {
    "db.t3.medium": 0.082,
    "db.t3.large": 0.164,
    "db.t4g.medium": 0.073,
    "db.t4g.large": 0.146,
    "db.r5.large": 0.290,
    "db.r5.xlarge": 0.580,
    "db.r5.2xlarge": 1.160,
    "db.r5.4xlarge": 2.320,
    "db.r5.8xlarge": 4.640,
    "db.r5.12xlarge": 6.960,
    "db.r5.16xlarge": 9.280,
    "db.r5.24xlarge": 13.920,
    "db.r6g.large": 0.260,
    "db.r6g.xlarge": 0.519,
    "db.r6g.2xlarge": 1.038,
    "db.r6g.4xlarge": 2.076,
    "db.r6g.8xlarge": 4.152,
    "db.r6g.12xlarge": 6.228,
    "db.r6g.16xlarge": 8.304,
    "db.r7g.large": 0.276,
    "db.r7g.xlarge": 0.553,
    "db.r7g.2xlarge": 1.106,
    "db.r7g.4xlarge": 2.211,
    "db.r7g.8xlarge": 4.422,
    "db.r7g.12xlarge": 6.633,
    "db.r7g.16xlarge": 8.844,
    "db.r8g.large": 0.276,
    "db.r8g.xlarge": 0.552,
    "db.r8g.2xlarge": 1.104,
    "db.r8g.4xlarge": 2.208,
    "db.r8g.8xlarge": 4.416,
    "db.r8g.12xlarge": 6.624,
    "db.r8g.16xlarge": 8.832,
    "db.r8g.24xlarge": 13.248,
    "db.r8g.48xlarge": 26.496,
}

_REGION_NAMES = {
    "us-east-1": "US East (N. Virginia)",
    "us-east-2": "US East (Ohio)",
    "us-west-1": "US West (N. California)",
    "us-west-2": "US West (Oregon)",
    "eu-west-1": "EU (Ireland)",
    "eu-west-2": "EU (London)",
    "eu-central-1": "EU (Frankfurt)",
    "eu-north-1": "EU (Stockholm)",
    "ap-southeast-1": "Asia Pacific (Singapore)",
    "ap-southeast-2": "Asia Pacific (Sydney)",
    "ap-northeast-1": "Asia Pacific (Tokyo)",
    "ap-south-1": "Asia Pacific (Mumbai)",
    "ca-central-1": "Canada (Central)",
}

# DSP only covers these families
_DSP_ELIGIBLE_FAMILIES = {"r7g", "r7i", "r8g", "r8gd", "m7g", "m7i", "c7g", "c7i", "x8g"}

_DSP_SIZE_MAP = {
    "micro": "micro",
    "small": "small",
    "medium": "medium",
    "large": "large",
    "xl": "xlarge",
    "2xl": "2xlarge",
    "4xl": "4xlarge",
    "8xl": "8xlarge",
    "12xl": "12xlarge",
    "16xl": "16xlarge",
    "24xl": "24xlarge",
    "48xl": "48xlarge",
}


# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------


@dataclass
class RIOffering:
    instance_type: str
    term_years: int
    payment_option: str  # "No Upfront" | "Partial Upfront" | "All Upfront"
    effective_hourly: float  # (upfront / term_hours) + recurring
    upfront_cost: float
    recurring_hourly: float

    def monthly_cost(self) -> float:
        return self.effective_hourly * HOURS_PER_MONTH


@dataclass
class DSPRate:
    usage_type: str  # instance type or "ServerlessV2"
    term_years: int  # always 1 for Aurora DSP
    payment_option: str
    rate_per_hour: float

    def monthly_cost(self) -> float:
        return self.rate_per_hour * HOURS_PER_MONTH


# ---------------------------------------------------------------------------
# Live AWS fetchers
# ---------------------------------------------------------------------------


def _family_from_instance(instance_type: str) -> str:
    m = re.match(r"db\.([a-z0-9]+)\.", instance_type)
    return m.group(1) if m else ""


def get_on_demand_price(instance_type: str, region: str = "us-east-1") -> float:
    """Return on-demand hourly price. Tries Pricing API, falls back to static."""
    try:
        import boto3
    except ImportError:
        return _STATIC_INSTANCE_PRICES.get(instance_type, 0.0)

    location = _REGION_NAMES.get(region)
    if not location:
        return _STATIC_INSTANCE_PRICES.get(instance_type, 0.0)

    try:
        pricing = boto3.client("pricing", region_name="us-east-1")
        filters = [
            {"Type": "TERM_MATCH", "Field": "databaseEngine", "Value": "Aurora PostgreSQL"},
            {"Type": "TERM_MATCH", "Field": "location", "Value": location},
            {"Type": "TERM_MATCH", "Field": "instanceType", "Value": instance_type},
            {"Type": "TERM_MATCH", "Field": "deploymentOption", "Value": "Single-AZ"},
            {"Type": "TERM_MATCH", "Field": "termType", "Value": "OnDemand"},
        ]
        for page in pricing.get_paginator("get_products").paginate(
            ServiceCode="AmazonRDS", Filters=filters
        ):
            for item_json in page["PriceList"]:
                item = json.loads(item_json) if isinstance(item_json, str) else item_json
                attrs = item.get("product", {}).get("attributes", {})
                if "IOOptimized" in attrs.get("usagetype", ""):
                    continue
                for term in item.get("terms", {}).get("OnDemand", {}).values():
                    for dim in term.get("priceDimensions", {}).values():
                        try:
                            price = float(dim.get("pricePerUnit", {}).get("USD", "0"))
                        except (ValueError, TypeError):
                            continue
                        if price > 0:
                            return price
    except Exception:
        pass

    return _STATIC_INSTANCE_PRICES.get(instance_type, 0.0)


def fetch_ri_offerings(instance_type: str, region: str) -> list[RIOffering]:
    """Fetch all RI offerings for an instance type. Returns [] on failure."""
    try:
        import boto3
    except ImportError:
        return []

    results: list[RIOffering] = []
    try:
        rds = boto3.client("rds", region_name=region)
        for engine in ("aurora-postgresql",):
            try:
                paginator = rds.get_paginator("describe_reserved_db_instances_offerings")
                for page in paginator.paginate(
                    DBInstanceClass=instance_type,
                    ProductDescription=engine,
                    MultiAZ=False,
                ):
                    for offering in page.get("ReservedDBInstancesOfferings", []):
                        inst = offering.get("DBInstanceClass", "")
                        if inst != instance_type:
                            continue
                        duration = offering.get("Duration", 0)
                        term_years = 3 if duration > 94_000_000 else 1
                        payment = offering.get("OfferingType", "")
                        fixed = float(offering.get("FixedPrice", 0.0))
                        recurring_list = offering.get("RecurringCharges", [])
                        recurring_hr = sum(
                            float(rc.get("RecurringChargeAmount", 0.0)) for rc in recurring_list
                        )
                        term_hours = term_years * 365 * 24
                        effective = (fixed / term_hours) + recurring_hr
                        results.append(
                            RIOffering(
                                instance_type=inst,
                                term_years=term_years,
                                payment_option=payment,
                                effective_hourly=round(effective, 6),
                                upfront_cost=round(fixed, 2),
                                recurring_hourly=round(recurring_hr, 6),
                            )
                        )
            except Exception:
                continue
    except Exception:
        return []

    # Deduplicate (same offering exists for both engines)
    seen = set()
    deduped = []
    for r in results:
        key = (r.term_years, r.payment_option, round(r.effective_hourly, 6))
        if key in seen:
            continue
        seen.add(key)
        deduped.append(r)
    return deduped


def fetch_dsp_rates(region: str) -> dict[str, list[DSPRate]]:
    """Fetch Database Savings Plan rates for Aurora in the region.

    Returns dict mapping usage key (instance type or 'ServerlessV2') to rates.
    """
    try:
        import boto3
    except ImportError:
        return {}

    result: dict[str, list[DSPRate]] = {}
    try:
        sp = boto3.client("savingsplans", region_name="us-east-1")
    except Exception:
        return {}

    for engine in ("Aurora PostgreSQL",):
        try:
            rates = []
            token = None
            while True:
                kwargs = {
                    "savingsPlanTypes": ["Database"],
                    "products": ["RDS"],
                    "serviceCodes": ["AmazonRDS"],
                    "filters": [
                        {"name": "region", "values": [region]},
                        {"name": "productDescription", "values": [engine]},
                    ],
                    "maxResults": 1000,
                }
                if token:
                    kwargs["nextToken"] = token
                resp = sp.describe_savings_plans_offering_rates(**kwargs)
                rates.extend(resp.get("searchResults", []))
                token = resp.get("nextToken")
                if not token:
                    break

            for rate_entry in rates:
                offering = rate_entry.get("savingsPlanOffering", {})
                dur = offering.get("durationSeconds", 0)
                term_years = 3 if dur > 94_000_000 else 1
                payment = offering.get("paymentOption", "")
                try:
                    rate_val = float(rate_entry.get("rate", "0"))
                except (ValueError, TypeError):
                    continue
                if rate_val <= 0:
                    continue

                usage = rate_entry.get("usageType", "")
                unit = rate_entry.get("unit", "")

                # Skip I/O-Optimized variants for consistency; main pricing uses Standard
                if "IOOptimized" in usage:
                    continue

                if unit == "ACU-Hr" and "ServerlessV2" in usage:
                    key = "ServerlessV2"
                else:
                    m = re.match(r"InstanceUsage:db\.(\w+)\.(\w+)", usage)
                    if not m:
                        continue
                    family = m.group(1)
                    short_size = m.group(2)
                    size = _DSP_SIZE_MAP.get(short_size, short_size)
                    key = f"db.{family}.{size}"

                entry = DSPRate(
                    usage_type=key,
                    term_years=term_years,
                    payment_option=payment,
                    rate_per_hour=round(rate_val, 6),
                )
                existing = result.get(key, [])
                if not any(
                    e.term_years == entry.term_years and e.payment_option == entry.payment_option
                    for e in existing
                ):
                    result.setdefault(key, []).append(entry)
        except Exception:
            continue

    return result


# ---------------------------------------------------------------------------
# Best-of selection (lowest effective monthly cost per term/category)
# ---------------------------------------------------------------------------


def best_ri(offerings: list[RIOffering], term_years: int) -> RIOffering | None:
    candidates = [r for r in offerings if r.term_years == term_years]
    if not candidates:
        return None
    return min(candidates, key=lambda r: r.effective_hourly)


def best_dsp(rates: list[DSPRate], term_years: int = 1) -> DSPRate | None:
    candidates = [r for r in rates if r.term_years == term_years]
    if not candidates:
        return None
    return min(candidates, key=lambda r: r.rate_per_hour)


# ---------------------------------------------------------------------------
# Comparison builder — single workload
# ---------------------------------------------------------------------------


def build_comparison(
    instance_type: str,
    num_instances: int,
    region: str,
    io_optimized: bool = False,
    is_serverless: bool = False,
    avg_acu: float = 0.0,
    dsp_rates: dict[str, list[DSPRate]] | None = None,
) -> dict:
    """Compare on-demand, RI, and DSP for a single workload description."""
    if dsp_rates is None:
        dsp_rates = fetch_dsp_rates(region)

    if is_serverless:
        od_hourly = ACU_PRICE_IO_OPTIMIZED if io_optimized else ACU_PRICE_STANDARD
        # For Serverless v2, "number of instances" is irrelevant — we price avg ACU continuously
        units = avg_acu
        od_monthly = od_hourly * units * HOURS_PER_MONTH

        dsp_entry = best_dsp(dsp_rates.get("ServerlessV2", []))
        dsp_monthly = dsp_entry.rate_per_hour * units * HOURS_PER_MONTH if dsp_entry else None
        dsp_savings = (od_monthly - dsp_monthly) if dsp_monthly is not None else None

        return {
            "workload_type": "serverless_v2",
            "avg_acu": avg_acu,
            "io_optimized": io_optimized,
            "on_demand": {
                "hourly": od_hourly,
                "monthly": round(od_monthly, 2),
            },
            "ri_1yr": None,
            "ri_3yr": None,
            "dsp_1yr": _format_dsp(dsp_entry, units, od_monthly) if dsp_entry else None,
            "recommendation": _recommend_serverless(dsp_savings, od_monthly),
            "notes": [
                "Reserved Instances do not apply to Aurora Serverless v2.",
                "DSP covers ACU-hours but bills the committed $/hr continuously, "
                "even during auto-pause. Only commit to the steady baseline ACU.",
            ],
        }

    # Provisioned
    family = _family_from_instance(instance_type)
    od_hourly = get_on_demand_price(instance_type, region)
    if io_optimized:
        od_hourly *= IO_OPT_COMPUTE_MULTIPLIER
    od_monthly = od_hourly * HOURS_PER_MONTH * num_instances

    ri_offerings = fetch_ri_offerings(instance_type, region)
    ri_1yr = best_ri(ri_offerings, 1)
    ri_3yr = best_ri(ri_offerings, 3)

    # I/O-Optimized RI coverage (AWS Compute Optimizer, verified): an I/O-Optimized
    # instance is FULLY covered by Reserved Instances — no portion is forced to
    # on-demand — but it "consumes 30% more normalized units per hour than Aurora
    # Standard", i.e. it draws down RI capacity at 1.30×. So the effective RI cost is
    # the (Standard-normalized) RI rate × 1.30. Equivalently: buy ~30% more normalized
    # RI units to cover the same I/O-Optimized fleet.
    #   io-opt RI monthly = ri_rate × 1.30 × hours × N
    def ri_adjusted_monthly(ri: RIOffering | None) -> float | None:
        if ri is None:
            return None
        units = IO_OPT_COMPUTE_MULTIPLIER if io_optimized else 1.0
        return ri.effective_hourly * units * HOURS_PER_MONTH * num_instances

    ri_1yr_monthly = ri_adjusted_monthly(ri_1yr)
    ri_3yr_monthly = ri_adjusted_monthly(ri_3yr)

    dsp_entry = best_dsp(dsp_rates.get(instance_type, []))
    dsp_monthly = dsp_entry.rate_per_hour * HOURS_PER_MONTH * num_instances if dsp_entry else None

    dsp_eligible = family in _DSP_ELIGIBLE_FAMILIES
    notes = []
    if not dsp_eligible:
        notes.append(
            f"Database Savings Plans do not cover the {family} family. "
            f"DSP requires r7g, r8g, r7i, or newer-gen Aurora-compatible families."
        )
    if io_optimized:
        notes.append(
            "Cluster is I/O-Optimized (30% compute premium). Both RI and DSP cover the "
            "full I/O-Optimized instance price — I/O-Optimized consumes 30% more "
            "normalized units per hour, so an RI draws down capacity at 1.30× (buy ~30% "
            "more normalized RI units to fully cover the fleet); no portion is on-demand."
        )

    return {
        "workload_type": "provisioned",
        "instance_type": instance_type,
        "num_instances": num_instances,
        "io_optimized": io_optimized,
        "on_demand": {
            "hourly": round(od_hourly, 4),
            "monthly": round(od_monthly, 2),
        },
        "ri_1yr": _format_ri(ri_1yr, ri_1yr_monthly, od_monthly, num_instances),
        "ri_3yr": _format_ri(ri_3yr, ri_3yr_monthly, od_monthly, num_instances),
        "dsp_1yr": (_format_dsp(dsp_entry, num_instances, od_monthly) if dsp_entry else None),
        "recommendation": _recommend_provisioned(
            od_monthly,
            ri_1yr_monthly,
            ri_3yr_monthly,
            dsp_monthly,
            dsp_eligible=dsp_eligible,
            io_optimized=io_optimized,
        ),
        "notes": notes,
    }


def _format_ri(
    ri: RIOffering | None, monthly: float | None, od_monthly: float, n: int
) -> dict | None:
    if ri is None or monthly is None:
        return None
    savings = od_monthly - monthly
    pct = (savings / od_monthly * 100) if od_monthly > 0 else 0
    return {
        "term_years": ri.term_years,
        "payment_option": ri.payment_option,
        "effective_hourly_per_instance": round(ri.effective_hourly, 4),
        "upfront_total": round(ri.upfront_cost * n, 2),
        "monthly": round(monthly, 2),
        "savings_monthly": round(savings, 2),
        "savings_pct": round(pct, 1),
    }


def _format_dsp(dsp: DSPRate | None, units: float, od_monthly: float) -> dict | None:
    if dsp is None:
        return None
    monthly = dsp.rate_per_hour * HOURS_PER_MONTH * units
    savings = od_monthly - monthly
    pct = (savings / od_monthly * 100) if od_monthly > 0 else 0
    return {
        "term_years": dsp.term_years,
        "payment_option": dsp.payment_option,
        "rate_per_hour": round(dsp.rate_per_hour, 4),
        "monthly": round(monthly, 2),
        "savings_monthly": round(savings, 2),
        "savings_pct": round(pct, 1),
    }


def _recommend_provisioned(
    od: float,
    ri_1yr: float | None,
    ri_3yr: float | None,
    dsp: float | None,
    dsp_eligible: bool,
    io_optimized: bool,
) -> dict:
    options = []
    if ri_1yr is not None:
        options.append(("1yr RI", ri_1yr))
    if ri_3yr is not None:
        options.append(("3yr RI", ri_3yr))
    if dsp is not None:
        options.append(("1yr DSP", dsp))

    if not options:
        return {
            "best_option": "on_demand",
            "reason": "No RI or DSP offerings available for this instance type/region.",
        }

    best_label, best_cost = min(options, key=lambda x: x[1])
    savings = od - best_cost
    pct = (savings / od * 100) if od > 0 else 0

    reasons = [
        f"{best_label} is the lowest-cost option, saving ${savings:.0f}/mo ({pct:.0f}%) vs on-demand."
    ]
    if best_label == "3yr RI":
        reasons.append(
            "Best fit for steady 24/7 workloads you're confident will stay on this instance family for 3 years."
        )
    elif best_label == "1yr DSP":
        reasons.append(
            "Offers flexibility — covers any eligible Aurora instance family in the account, including future upgrades."
        )
        if io_optimized:
            reasons.append(
                "DSP is particularly attractive for I/O-Optimized clusters since it covers the full rate."
            )
    elif best_label == "1yr RI":
        reasons.append(
            "Shorter commitment than 3yr, useful when instance-family migration is on the horizon."
        )

    if not dsp_eligible and dsp is None:
        reasons.append(
            "DSP is not available for this instance family, so RI is the only commitment option."
        )

    return {
        "best_option": best_label,
        "best_monthly_cost": round(best_cost, 2),
        "savings_vs_on_demand": round(savings, 2),
        "savings_pct": round(pct, 1),
        "reason": " ".join(reasons),
    }


def _recommend_serverless(dsp_savings: float | None, od_monthly: float) -> dict:
    if dsp_savings is None:
        return {
            "best_option": "on_demand",
            "reason": "No Database Savings Plan rates available for Serverless v2 ACU in this region.",
        }
    if dsp_savings <= 0:
        return {
            "best_option": "on_demand",
            "reason": "DSP would not save money at the specified average ACU.",
        }
    pct = (dsp_savings / od_monthly * 100) if od_monthly > 0 else 0
    return {
        "best_option": "1yr DSP",
        "savings_vs_on_demand": round(dsp_savings, 2),
        "savings_pct": round(pct, 1),
        "reason": (
            f"1yr DSP saves ${dsp_savings:.0f}/mo ({pct:.0f}%). "
            "Size the commitment to your steady baseline ACU — DSP bills the committed $/hr "
            "continuously, even during idle periods."
        ),
    }


# ---------------------------------------------------------------------------
# Live cluster analysis
# ---------------------------------------------------------------------------


def _is_empty_cluster(cluster: dict) -> bool:
    """Skip clusters with no compute to analyze.

    An Aurora cluster with no DB instances has no compute cost, so RI and DSP
    commitment analysis doesn't apply. Typical cases: Aurora Limitless
    (sharded compute, not instances), paused/stopped clusters, or clusters
    mid-migration.
    """
    return len(cluster.get("DBClusterMembers", [])) == 0


def analyze_cluster_live(cluster_id: str, region: str) -> dict:
    import boto3

    rds = boto3.client("rds", region_name=region)

    try:
        resp = rds.describe_db_clusters(DBClusterIdentifier=cluster_id)
    except Exception as e:
        return {"cluster_id": cluster_id, "error": str(e)}
    clusters = resp.get("DBClusters", [])
    if not clusters:
        return {"cluster_id": cluster_id, "error": "cluster not found"}
    cluster = clusters[0]
    storage_type = cluster.get("StorageType", "aurora")
    io_optimized = storage_type == "aurora-iopt1"
    engine = cluster.get("Engine", "")

    # Guardrail: skip clusters with no DB instances (Limitless, paused, mid-migration, etc.)
    if _is_empty_cluster(cluster):
        return {
            "cluster_id": cluster_id,
            "engine": engine,
            "engine_version": cluster.get("EngineVersion", ""),
            "storage_type": storage_type,
            "skipped": True,
            "reason": (
                "Cluster has no DB instances — no compute to price. "
                "RI and DSP commitment analysis does not apply. "
                "This typically indicates Aurora Limitless, a paused cluster, "
                "or a cluster mid-migration."
            ),
        }

    # Identify instances
    member_ids = [m["DBInstanceIdentifier"] for m in cluster.get("DBClusterMembers", [])]
    type_counts: dict[str, int] = {}
    serverless_instances = 0
    for mid in member_ids:
        try:
            iresp = rds.describe_db_instances(DBInstanceIdentifier=mid)
            for inst in iresp.get("DBInstances", []):
                itype = inst.get("DBInstanceClass", "")
                if itype == "db.serverless":
                    serverless_instances += 1
                else:
                    type_counts[itype] = type_counts.get(itype, 0) + 1
        except Exception:
            continue

    # Prefetch DSP rates once for this cluster analysis
    dsp_rates = fetch_dsp_rates(region)

    sub_workloads = []
    for itype, count in type_counts.items():
        sub_workloads.append(
            build_comparison(
                instance_type=itype,
                num_instances=count,
                region=region,
                io_optimized=io_optimized,
                dsp_rates=dsp_rates,
            )
        )
    if serverless_instances > 0:
        # Without observed ACU metrics, we can't price serverless exactly — note it
        sub_workloads.append(
            {
                "workload_type": "serverless_v2",
                "instance_count": serverless_instances,
                "note": "Serverless v2 instances detected. Re-run with 'offline --serverless "
                "--avg-acu <N>' using your observed average ACU (from CloudWatch "
                "ServerlessDatabaseCapacity metric) for a precise DSP estimate.",
                "io_optimized": io_optimized,
            }
        )

    return {
        "cluster_id": cluster_id,
        "engine": engine,
        "storage_type": storage_type,
        "io_optimized": io_optimized,
        "instance_mix": {**type_counts, "serverless": serverless_instances},
        "workloads": sub_workloads,
    }


def list_clusters(region: str) -> list[str]:
    import boto3

    rds = boto3.client("rds", region_name=region)
    names = []
    for page in rds.get_paginator("describe_db_clusters").paginate():
        for c in page.get("DBClusters", []):
            if c.get("Engine", "").startswith("aurora"):
                names.append(c["DBClusterIdentifier"])
    return names


# ---------------------------------------------------------------------------
# Output formatting
# ---------------------------------------------------------------------------


def _format_table_single(result: dict) -> str:
    lines = []
    lines.append("=" * 72)
    if result.get("workload_type") == "serverless_v2":
        lines.append(f"Aurora Serverless v2 Commitment Pricing")
        lines.append(
            f"  Avg ACU: {result.get('avg_acu', 0):.1f}  "
            f"I/O-Optimized: {result.get('io_optimized', False)}"
        )
    else:
        lines.append(
            f"Aurora Commitment Pricing — "
            f"{result.get('num_instances', 1)}× {result.get('instance_type', '?')}"
        )
        if result.get("io_optimized"):
            lines.append("  Storage: I/O-Optimized (30% compute premium applied)")
    lines.append("=" * 72)
    od_monthly = result["on_demand"]["monthly"]
    lines.append("")
    lines.append(f"  {'Option':<28} {'Monthly':>12} {'Savings':>12} {'Upfront':>12}  Term")
    lines.append("  " + "-" * 70)
    lines.append(f"  {'On-Demand':<28} ${od_monthly:>11,.0f} {'—':>12} {'$0':>12}  —")

    for key, label, term_hint in (
        ("ri_1yr", "1yr RI", "1 year"),
        ("ri_3yr", "3yr RI", "3 years"),
        ("dsp_1yr", "1yr DSP", "1 year"),
    ):
        entry = result.get(key)
        if not entry:
            continue
        payment = entry.get("payment_option", "")
        display = f"{label} ({payment})" if payment else label
        monthly = entry.get("monthly", 0)
        savings = entry.get("savings_monthly", 0)
        pct = entry.get("savings_pct", 0)
        upfront = entry.get("upfront_total", 0)
        savings_str = f"${savings:,.0f} ({pct:.0f}%)" if savings else "—"
        upfront_str = f"${upfront:,.0f}" if upfront else "$0"
        lines.append(
            f"  {display:<28} ${monthly:>11,.0f} {savings_str:>12} {upfront_str:>12}  {term_hint}"
        )

    rec = result.get("recommendation", {})
    lines.append("")
    lines.append(f"  Recommendation: {rec.get('best_option', '?')}")
    lines.append(f"  {rec.get('reason', '')}")

    notes = result.get("notes", [])
    if notes:
        lines.append("")
        for n in notes:
            lines.append(f"  Note: {n}")
    lines.append("=" * 72)
    return "\n".join(lines)


def _format_cluster(result: dict) -> str:
    lines = []
    lines.append(
        f"Cluster: {result.get('cluster_id', '?')}  "
        f"({result.get('engine', '?')})  "
        f"storage_type={result.get('storage_type', '?')}"
    )
    workloads = result.get("workloads", [])
    for wl in workloads:
        if wl.get("workload_type") == "serverless_v2" and "note" in wl:
            lines.append("")
            lines.append(f"  [Serverless v2 — {wl.get('instance_count', 0)} instance(s)]")
            lines.append(f"  {wl['note']}")
            continue
        lines.append("")
        lines.append(_format_table_single(wl))
    return "\n".join(lines)


def _format_fleet(output: dict) -> str:
    lines = []
    lines.append(f"Region: {output['region']}")
    lines.append("")
    total_od = 0.0
    total_best = 0.0
    for cluster in output["clusters"]:
        if "error" in cluster:
            lines.append(f"{cluster['cluster_id']}: ERROR {cluster['error']}")
            continue
        for wl in cluster.get("workloads", []):
            if wl.get("workload_type") != "provisioned":
                continue
            od = wl["on_demand"]["monthly"]
            best = wl.get("recommendation", {}).get("best_monthly_cost", od)
            total_od += od
            total_best += best
    lines.append(f"  Fleet monthly on-demand:    ${total_od:,.0f}")
    lines.append(f"  With best commitments:      ${total_best:,.0f}")
    savings = total_od - total_best
    pct = (savings / total_od * 100) if total_od > 0 else 0
    lines.append(f"  Fleet savings opportunity:  ${savings:,.0f}/mo ({pct:.0f}%)")
    lines.append("")
    for cluster in output["clusters"]:
        if "error" in cluster:
            continue
        lines.append("")
        lines.append(_format_cluster(cluster))
    return "\n".join(lines)


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------


def main():
    parser = argparse.ArgumentParser(
        description="Aurora RI & Database Savings Plan estimator (read-only)"
    )
    parser.add_argument("--region", default="us-east-1")
    parser.add_argument("--format", choices=["json", "table"], default="json")
    parser.add_argument("--cluster", help="Analyze a single cluster by identifier")
    parser.add_argument(
        "--all", action="store_true", help="Analyze all Aurora clusters in the region"
    )

    sub = parser.add_subparsers(dest="mode")
    off = sub.add_parser("offline", help="Use user-supplied workload description")
    off.add_argument("--instance", help="Instance type (e.g., db.r7g.2xlarge)")
    off.add_argument("--num-instances", type=int, default=1)
    off.add_argument(
        "--io-optimized", action="store_true", help="Workload uses Aurora I/O-Optimized storage"
    )
    off.add_argument(
        "--serverless", action="store_true", help="Serverless v2 workload — requires --avg-acu"
    )
    off.add_argument(
        "--avg-acu", type=float, default=0.0, help="Average ACU for serverless workload"
    )
    off.add_argument("--region", default="us-east-1")
    off.add_argument("--format", choices=["json", "table"], default="json")

    args = parser.parse_args()

    if args.mode == "offline":
        if args.serverless:
            if args.avg_acu <= 0:
                print("ERROR: --serverless requires --avg-acu > 0", file=sys.stderr)
                sys.exit(2)
            result = build_comparison(
                instance_type="",
                num_instances=0,
                region=args.region,
                io_optimized=args.io_optimized,
                is_serverless=True,
                avg_acu=args.avg_acu,
            )
        else:
            if not args.instance:
                print("ERROR: offline mode requires --instance (or --serverless)", file=sys.stderr)
                sys.exit(2)
            result = build_comparison(
                instance_type=args.instance,
                num_instances=args.num_instances,
                region=args.region,
                io_optimized=args.io_optimized,
            )
        if args.format == "json":
            print(json.dumps(result, indent=2, default=str))
        else:
            print(_format_table_single(result))
        return

    # Live modes require boto3
    try:
        import boto3  # noqa: F401
    except ImportError:
        print(
            "ERROR: boto3 required for live AWS analysis. Use the 'offline' subcommand.",
            file=sys.stderr,
        )
        sys.exit(2)

    if args.all:
        cluster_ids = list_clusters(args.region)
        results = [analyze_cluster_live(cid, args.region) for cid in cluster_ids]
        output = {"region": args.region, "cluster_count": len(results), "clusters": results}
        if args.format == "json":
            print(json.dumps(output, indent=2, default=str))
        else:
            print(_format_fleet(output))
        return

    if args.cluster:
        result = analyze_cluster_live(args.cluster, args.region)
        if args.format == "json":
            print(json.dumps(result, indent=2, default=str))
        else:
            print(_format_cluster(result))
        return

    parser.print_help()


if __name__ == "__main__":
    main()

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs Python

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
AWS
Publisher
AWS (Official)
Source
aws/agent-toolkit-for-aws · skills/specialized-skills/database-skills/amazon-aurora-postgresql · commit 0a218f8
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • NOTICE (added by AutoGineer from NOTICE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by AWS.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download amazon-aurora-postgresql.zip