Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add four aws cost explorer tables (#116962)

Tom Owerse75c47d7f4c1
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index dec3d8c30bb0..720e8c70b36e 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -279,7 +279,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/aviator/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/awin/awin.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/awin/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/azure_devops.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/babelforce.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 9ef7d9a9b058..dcae3bf83848 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1162,10 +1162,10 @@ Today (4): `cost_and_usage_daily`, `cost_and_usage_monthly`, `reservation_utiliz
Diffed against: <https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/ce/2017-10-25/service-2.json>
-- [ ] `Dimension values (GetDimensionValues, POST /)` — resolves linked account IDs in cost tables to account names and provides dimension metadata (high)
-- [ ] `Cost and usage with resources (GetCostAndUsageWithResources, POST /)` — attributes spend to individual resources for cost allocation and investigation (high)
-- [ ] `Reservation coverage (GetReservationCoverage, POST /)` — measures eligible usage covered by Reserved Instances, which utilization totals cannot establish (high)
-- [ ] `Savings Plans coverage (GetSavingsPlansCoverage, POST /)` — measures eligible spend covered by Savings Plans and the remaining on-demand exposure (high)
+- [x] `Dimension values (GetDimensionValues, POST /)` — resolves linked account IDs in cost tables to account names and provides dimension metadata (high)
+- [x] `Cost and usage with resources (GetCostAndUsageWithResources, POST /)` — attributes spend to individual resources for cost allocation and investigation (high)
+- [x] `Reservation coverage (GetReservationCoverage, POST /)` — measures eligible usage covered by Reserved Instances, which utilization totals cannot establish (high)
+- [x] `Savings Plans coverage (GetSavingsPlansCoverage, POST /)` — measures eligible spend covered by Savings Plans and the remaining on-demand exposure (high)
- [ ] `Savings Plans utilization details (GetSavingsPlansUtilizationDetails, POST /)` — shows utilization, savings, commitments, and attributes for each Savings Plan (medium)
- [ ] `Cost forecast (GetCostForecast, POST /)` — supports budget planning with predicted spend and confidence intervals (medium)
- [ ] `Rightsizing recommendations (GetRightsizingRecommendation, POST /)` — identifies idle or oversized EC2 instances and estimates savings (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py
index 719afad77cc8..cceb34872226 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py
@@ -65,12 +65,14 @@ class AwsCostExplorerThrottledError(AwsCostExplorerError):
pass
[email protected](frozen=True)
class AwsCostExplorerResumeConfig:
"""Where a previous attempt stopped: the request window plus its page token."""
window_start: str
next_page_token: Optional[str] = None
+ # The dimension or service the saved page belongs to, for operations that slice by one.
+ slice_key: Optional[str] = None
@dataclasses.dataclass(frozen=True)
@@ -130,6 +132,9 @@ def resolve_start_date(
periods until the bill finalizes, but never before the user's configured start date.
"""
floor = coerce_date(configured_start_date) or (end - dt.timedelta(days=DEFAULT_LOOKBACK_DAYS))
+ if endpoint_config.max_lookback_days is not None:
+ today = end - dt.timedelta(days=1) if endpoint_config.includes_current_day else end
+ floor = max(floor, today - dt.timedelta(days=endpoint_config.max_lookback_days))
start = floor
if should_use_incremental_field:
@@ -152,12 +157,24 @@ def build_windows(start: dt.date, end: dt.date, window_days: int) -> list[TimeWi
def build_payload(
- endpoint_config: CostExplorerEndpointConfig, window: TimeWindow, page_token: Optional[str]
+ endpoint_config: CostExplorerEndpointConfig,
+ window: TimeWindow,
+ page_token: Optional[str],
+ slice_key: Optional[str] = None,
+ window_services: Optional[list[str]] = None,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"TimePeriod": {"Start": window.start.isoformat(), "End": window.end.isoformat()},
- "Granularity": endpoint_config.granularity,
}
+ if endpoint_config.granularity:
+ payload["Granularity"] = endpoint_config.granularity
+ if endpoint_config.dimensions and slice_key:
+ payload["Dimension"] = slice_key
+ payload["Context"] = "COST_AND_USAGE"
+ if endpoint_config.services and slice_key:
+ payload["Filter"] = {"Dimensions": {"Key": "SERVICE", "Values": [slice_key]}}
+ if window_services is not None:
+ payload["Filter"] = {"Dimensions": {"Key": "SERVICE", "Values": window_services}}
if endpoint_config.metrics:
payload["Metrics"] = list(endpoint_config.metrics)
if endpoint_config.group_by:
@@ -212,7 +229,23 @@ def _cost_rows(
return rows
-def normalize_results(endpoint_config: CostExplorerEndpointConfig, body: dict[str, Any]) -> list[dict[str, Any]]:
+def _dimension_rows(dimension: str, body: dict[str, Any]) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for item in body.get("DimensionValues") or []:
+ # LINKED_ACCOUNT values carry the account name as a `description` attribute. Attributes are
+ # labels, so they skip the numeric coercion a name like `0010` would not survive.
+ row: dict[str, Any] = {"dimension": dimension, "value": item.get("Value")}
+ row.update({_snake(key): value for key, value in (item.get("Attributes") or {}).items()})
+ rows.append(row)
+ return rows
+
+
+def normalize_results(
+ endpoint_config: CostExplorerEndpointConfig, body: dict[str, Any], slice_key: Optional[str] = None
+) -> list[dict[str, Any]]:
+ if endpoint_config.dimensions and slice_key is not None:
+ return _dimension_rows(slice_key, body)
+
rows: list[dict[str, Any]] = []
for result in body.get(endpoint_config.result_key) or []:
@@ -223,7 +256,7 @@ def normalize_results(endpoint_config: CostExplorerEndpointConfig, body: dict[st
"granularity": endpoint_config.granularity,
}
- if endpoint_config.metrics:
+ if not endpoint_config.nested_keys:
# Recent periods come back estimated and are restated later; the lookback rewind
# re-merges them once finalized. Only the cost operations report it.
base["estimated"] = result.get("Estimated")
@@ -231,6 +264,8 @@ def normalize_results(endpoint_config: CostExplorerEndpointConfig, body: dict[st
continue
row = dict(base)
+ if endpoint_config.services:
+ row["service"] = slice_key
for member, prefix in endpoint_config.nested_keys:
row.update(_flatten(prefix, result.get(member) or {}))
rows.append(row)
@@ -322,7 +357,7 @@ VALIDATION_ERROR_MESSAGES: dict[str, str] = {
"SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",
"InvalidSignatureException": "AWS rejected the request signature. If you are using temporary credentials, the session token has expired.",
"ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",
- "AccessDeniedException": "These AWS credentials are missing Cost Explorer permissions. Grant ce:GetCostAndUsage, ce:GetReservationUtilization and ce:GetSavingsPlansUtilization to the IAM user or role.",
+ "AccessDeniedException": "These AWS credentials are missing Cost Explorer permissions. Grant ce:GetCostAndUsage, ce:GetCostAndUsageWithResources, ce:GetDimensionValues, ce:GetReservationUtilization, ce:GetReservationCoverage, ce:GetSavingsPlansUtilization and ce:GetSavingsPlansCoverage to the IAM user or role.",
"DataUnavailableException": "AWS has no Cost Explorer data for the requested dates. Cost Explorer has to be enabled on the account, and it can take up to 24 hours to prepare data.",
"BillExpirationException": "The requested dates are older than the data AWS keeps. Move the start date forward and try again.",
}
@@ -374,19 +409,37 @@ def validate_credentials(
def _resume_index(
- windows: list[TimeWindow], resume: Optional[AwsCostExplorerResumeConfig]
+ slices: list[tuple[TimeWindow, Optional[str]]], resume: Optional[AwsCostExplorerResumeConfig]
) -> tuple[int, Optional[str]]:
- """Where to pick up. A saved window that no longer exists (the range moved) restarts the run."""
+ """Where to pick up. A saved slice that no longer exists (the range moved) restarts the run."""
if resume is None:
return 0, None
- for index, window in enumerate(windows):
- if window.start.isoformat() == resume.window_start:
+ for index, (window, slice_key) in enumerate(slices):
+ if window.start.isoformat() == resume.window_start and slice_key == resume.slice_key:
return index, resume.next_page_token
return 0, None
+def list_window_services(session: requests.Session, credentials: Credentials, window: TimeWindow) -> list[str]:
+ services: list[str] = []
+ page_token: Optional[str] = None
+ while True:
+ payload: dict[str, Any] = {
+ "TimePeriod": {"Start": window.start.isoformat(), "End": window.end.isoformat()},
+ "Dimension": "SERVICE",
+ "Context": "COST_AND_USAGE",
+ }
+ if page_token:
+ payload["NextPageToken"] = page_token
+ body = send_operation(session, credentials, "GetDimensionValues", payload)
+ services.extend(item["Value"] for item in body.get("DimensionValues") or [] if item.get("Value"))
+ page_token = body.get("NextPageToken")
+ if not page_token:
+ return services
+
+
def get_rows(
aws_access_key_id: str,
aws_secret_access_key: str,
@@ -416,17 +469,30 @@ def get_rows(
resumable_source_manager.clear_state()
return
+ slice_keys: tuple[Optional[str], ...] = endpoint_config.dimensions or endpoint_config.services or (None,)
+ slices = [(window, slice_key) for window in windows for slice_key in slice_keys]
+
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- index, page_token = _resume_index(windows, resume)
+ index, page_token = _resume_index(slices, resume)
if resume is not None:
- logger.debug(f"Resuming AWS Cost Explorer sync. endpoint={endpoint}, window={windows[index].start}")
+ logger.debug(f"Resuming AWS Cost Explorer sync. endpoint={endpoint}, window={slices[index][0].start}")
+
+ for window, slice_key in slices[index:]:
+ window_services: Optional[list[str]] = None
+ if endpoint_config.filter_by_window_services:
+ window_services = list_window_services(session, credentials, window)
+ if not window_services:
+ page_token = None
+ continue
- for window in windows[index:]:
while True:
body = send_operation(
- session, credentials, endpoint_config.operation, build_payload(endpoint_config, window, page_token)
+ session,
+ credentials,
+ endpoint_config.operation,
+ build_payload(endpoint_config, window, page_token, slice_key, window_services),
)
- rows = normalize_results(endpoint_config, body)
+ rows = normalize_results(endpoint_config, body, slice_key)
if rows:
yield rows
@@ -434,7 +500,9 @@ def get_rows(
# Saved after yielding: a crash re-yields the last batch, which merges away on the
# primary key, rather than skipping it.
resumable_source_manager.save_state(
- AwsCostExplorerResumeConfig(window_start=window.start.isoformat(), next_page_token=page_token)
+ AwsCostExplorerResumeConfig(
+ window_start=window.start.isoformat(), next_page_token=page_token, slice_key=slice_key
+ )
)
if not page_token:
@@ -472,8 +540,8 @@ def aws_cost_explorer_source(
logger=logger,
),
primary_keys=endpoint_config.primary_key,
- partition_keys=["period_start"],
- partition_mode="datetime",
- partition_format="month",
+ partition_keys=None if endpoint_config.dimensions else ["period_start"],
+ partition_mode=None if endpoint_config.dimensions else "datetime",
+ partition_format=None if endpoint_config.dimensions else "month",
sort_mode="asc",
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/canonical_descriptions.py
index e0012052c8cb..43849e3cc9b9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/canonical_descriptions.py
@@ -82,4 +82,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"amortized_commitment_total_amortized_commitment": "Total amortized Savings Plans commitment for the period.",
},
},
+ "dimension_values": {
+ "description": "Linked accounts, services and regions that have Cost Explorer data in the synced range. Join on linked_account or service to label cost rows.",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetDimensionValues.html",
+ "columns": {
+ "dimension": "Cost Explorer dimension the value belongs to (LINKED_ACCOUNT, SERVICE or REGION).",
+ "value": "Dimension value, for example an account ID, a service name or a region code.",
+ "description": "Account name of a LINKED_ACCOUNT value.",
+ },
+ },
+ "cost_and_usage_with_resources_daily": {
+ "description": "Daily AWS cost and usage per resource for the last 14 days, grouped by service and resource ID. Needs resource-level data enabled in Cost Explorer settings.",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostAndUsageWithResources.html",
+ "columns": {
+ **{k: v for k, v in _COST_AND_USAGE_COLUMNS.items() if k != "linked_account"},
+ "resource_id": "ID of the resource the cost belongs to, from the RESOURCE_ID dimension. 'NoResourceId' groups usage AWS does not attribute to a resource.",
+ },
+ },
+ "reservation_coverage_daily": {
+ "description": "Daily share of reservation eligible usage that reservations covered, per service (EC2, RDS, ElastiCache and Redshift).",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetReservationCoverage.html",
+ "columns": {
+ "period_start": "Inclusive start of the period the coverage covers.",
+ "period_end": "Exclusive end of the period the coverage covers.",
+ "granularity": "Bucket size AWS aggregated the period to (DAILY).",
+ "service": "AWS service the coverage belongs to, for example 'Amazon Relational Database Service'.",
+ "coverage_hours_on_demand_hours": "Instance hours that ran at On-Demand rates.",
+ "coverage_hours_reserved_hours": "Instance hours that reservations covered.",
+ "coverage_hours_total_running_hours": "Total instance hours that ran in the period.",
+ "coverage_hours_coverage_hours_percentage": "Percentage of the running instance hours that reservations covered.",
+ "coverage_normalized_units_on_demand_normalized_units": "Normalized units that ran at On-Demand rates.",
+ "coverage_normalized_units_reserved_normalized_units": "Normalized units that reservations covered.",
+ "coverage_normalized_units_total_running_normalized_units": "Total normalized units that ran in the period.",
+ "coverage_normalized_units_coverage_normalized_units_percentage": "Percentage of the running normalized units that reservations covered.",
+ "coverage_cost_on_demand_cost": "Cost of the instances that ran at On-Demand rates.",
+ },
+ },
+ "savings_plans_coverage_daily": {
+ "description": "Daily share of Savings Plans eligible spend that Savings Plans covered, across the account.",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansCoverage.html",
+ "columns": {
+ "period_start": "Inclusive start of the period the coverage covers.",
+ "period_end": "Exclusive end of the period the coverage covers.",
+ "granularity": "Bucket size AWS aggregated the period to (DAILY).",
+ "spend_covered_by_savings_plans": "Eligible spend that Savings Plans covered.",
+ "on_demand_cost": "Eligible spend that ran at On-Demand rates.",
+ "total_cost": "Total eligible spend, covered and On-Demand.",
+ "coverage_percentage": "Percentage of the eligible spend that Savings Plans covered.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/settings.py
index 9acf1ebae2c8..c9afa6aba6e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/settings.py
@@ -29,7 +29,8 @@ class CostExplorerEndpointConfig:
name: str
# Operation name, dispatched through the `X-Amz-Target` header.
operation: str
- granularity: str
+ # `None` for GetDimensionValues, which has no granularity member.
+ granularity: str | None
# Response key holding the list of per-time-period results.
result_key: str
primary_key: list[str]
@@ -51,6 +52,17 @@ class CostExplorerEndpointConfig:
# still-in-progress day. The utilization operations have no such concept and reject a
# request whose window includes today with DataUnavailableException.
includes_current_day: bool = False
+ # GetDimensionValues: one request series per dimension, each row keyed by dimension + value.
+ dimensions: tuple[str, ...] = ()
+ # One request series per service, filtered on SERVICE and tagged with a `service` column.
+ # GetReservationCoverage reports only EC2 when the request has no SERVICE filter.
+ services: tuple[str, ...] = ()
+ # Days before today the operation serves at all. GetCostAndUsageWithResources rejects a
+ # start date more than 14 days back.
+ max_lookback_days: int | None = None
+ # GetCostAndUsageWithResources requires a filter, so each window is filtered to the services
+ # GetDimensionValues reports for it, which keeps every service in scope.
+ filter_by_window_services: bool = False
AWS_COST_EXPLORER_ENDPOINTS: dict[str, CostExplorerEndpointConfig] = {
@@ -106,12 +118,70 @@ AWS_COST_EXPLORER_ENDPOINTS: dict[str, CostExplorerEndpointConfig] = {
("AmortizedCommitment", "amortized_commitment"),
),
),
+ "dimension_values": CostExplorerEndpointConfig(
+ name="dimension_values",
+ operation="GetDimensionValues",
+ granularity=None,
+ result_key="DimensionValues",
+ primary_key=["dimension", "value"],
+ page_token_key="NextPageToken",
+ dimensions=("LINKED_ACCOUNT", "SERVICE", "REGION"),
+ # One window over the whole range, so a value active in several windows is listed once.
+ window_days=100 * 366,
+ includes_current_day=True,
+ ),
+ "cost_and_usage_with_resources_daily": CostExplorerEndpointConfig(
+ name="cost_and_usage_with_resources_daily",
+ operation="GetCostAndUsageWithResources",
+ granularity="DAILY",
+ result_key="ResultsByTime",
+ primary_key=["period_start", "service", "resource_id"],
+ page_token_key="NextPageToken",
+ metrics=COST_METRICS,
+ group_by=("SERVICE", "RESOURCE_ID"),
+ window_days=14,
+ restatement_lookback_days=7,
+ includes_current_day=True,
+ max_lookback_days=14,
+ filter_by_window_services=True,
+ ),
+ "reservation_coverage_daily": CostExplorerEndpointConfig(
+ name="reservation_coverage_daily",
+ operation="GetReservationCoverage",
+ granularity="DAILY",
+ result_key="CoveragesByTime",
+ primary_key=["period_start", "service"],
+ page_token_key="NextPageToken",
+ metrics=("Hour", "Unit", "Cost"),
+ services=(
+ "Amazon Elastic Compute Cloud - Compute",
+ "Amazon Relational Database Service",
+ "Amazon ElastiCache",
+ "Amazon Redshift",
+ ),
+ window_days=92,
+ restatement_lookback_days=7,
+ nested_keys=(("Total", ""),),
+ ),
+ "savings_plans_coverage_daily": CostExplorerEndpointConfig(
+ name="savings_plans_coverage_daily",
+ operation="GetSavingsPlansCoverage",
+ granularity="DAILY",
+ result_key="SavingsPlansCoverages",
+ primary_key=["period_start"],
+ page_token_key="NextToken",
+ metrics=("SpendCoveredBySavingsPlans",),
+ window_days=92,
+ restatement_lookback_days=7,
+ nested_keys=(("Coverage", ""),),
+ ),
}
ENDPOINTS = tuple(AWS_COST_EXPLORER_ENDPOINTS.keys())
# `period_start` is the window boundary the API itself filters on, so it is the only honest
-# cursor: every operation takes a server-side `TimePeriod` and nothing else.
+# cursor: every operation takes a server-side `TimePeriod` and nothing else. Dimension values
+# carry no period, so that table is full refresh only.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: [
{
@@ -121,7 +191,8 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
"field_type": IncrementalFieldType.DateTime,
}
]
- for name in ENDPOINTS
+ for name, endpoint_config in AWS_COST_EXPLORER_ENDPOINTS.items()
+ if not endpoint_config.dimensions
}
ENDPOINT_DESCRIPTIONS: dict[str, str] = {
@@ -129,4 +200,8 @@ ENDPOINT_DESCRIPTIONS: dict[str, str] = {
"cost_and_usage_monthly": "Monthly cost and usage metrics grouped by AWS service and linked account.",
"reservation_utilization_daily": "Daily Reserved Instance utilization and savings totals.",
"savings_plans_utilization_daily": "Daily Savings Plans commitment utilization and net savings.",
+ "dimension_values": "Linked accounts, services and regions seen in the synced range, with linked account names.",
+ "cost_and_usage_with_resources_daily": "Daily cost and usage per resource for the last 14 days. Requires resource-level data to be enabled in Cost Explorer settings.",
+ "reservation_coverage_daily": "Daily share of eligible EC2, RDS, ElastiCache and Redshift usage covered by reservations.",
+ "savings_plans_coverage_daily": "Daily share of eligible spend covered by Savings Plans, and the remaining On-Demand cost.",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py
index 6eaddd7fb4da..84443f8983a5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py
@@ -128,7 +128,9 @@ class AwsCostExplorerSource(ResumableSource[AwsCostExplorerSourceConfig, AwsCost
label="AWS Cost Explorer",
caption="""Sync your AWS cost and usage data into the PostHog Data warehouse.
-Create an IAM user or role with the `ce:GetCostAndUsage`, `ce:GetReservationUtilization` and `ce:GetSavingsPlansUtilization` permissions, then paste its access key ID and secret access key. Add a session token too if you are using temporary credentials.
+Create an IAM user or role with the `ce:GetCostAndUsage`, `ce:GetCostAndUsageWithResources`, `ce:GetDimensionValues`, `ce:GetReservationUtilization`, `ce:GetReservationCoverage`, `ce:GetSavingsPlansUtilization` and `ce:GetSavingsPlansCoverage` permissions, then paste its access key ID and secret access key. Add a session token too if you are using temporary credentials.
+
+The per-resource cost table needs resource-level data turned on in your Cost Explorer settings, and only covers the last 14 days.
Connect the management (payer) account to see spend across every member account. AWS charges $0.01 per Cost Explorer API request, so syncs ask for wide date ranges at a time.""",
iconPath="/static/services/aws_cost_explorer.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
index d6a113dd37f8..7a9897a4a808 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
@@ -34,6 +34,7 @@ LOGGER = structlog.get_logger()
COST_DAILY = AWS_COST_EXPLORER_ENDPOINTS["cost_and_usage_daily"]
SAVINGS_PLANS = AWS_COST_EXPLORER_ENDPOINTS["savings_plans_utilization_daily"]
+WITH_RESOURCES = AWS_COST_EXPLORER_ENDPOINTS["cost_and_usage_with_resources_daily"]
def without_retry_backoff(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -110,6 +111,11 @@ class TestResolveStartDate:
def test_ignores_an_unparseable_watermark(self) -> None:
assert resolve_start_date("2024-01-01", COST_DAILY, True, "not-a-date", self.END) == dt.date(2024, 1, 1)
+ def test_resource_level_data_never_reaches_past_the_14_days_aws_serves(self) -> None:
+ # GetCostAndUsageWithResources rejects a start date older than 14 days.
+ # END is exclusive and reaches into tomorrow, so today is 2024-05-31.
+ assert resolve_start_date("2024-01-01", WITH_RESOURCES, False, None, self.END) == dt.date(2024, 5, 17)
+
class TestBuildPayload:
WINDOW = aws_cost_explorer.TimeWindow(start=dt.date(2024, 3, 1), end=dt.date(2024, 4, 1))
@@ -307,3 +313,122 @@ class TestGetRows:
assert batches == []
assert send.call_count == 0
assert manager.cleared is True
+
+ def test_resource_costs_are_filtered_to_the_services_listed_for_the_window(self) -> None:
+ manager = FakeResumeManager()
+
+ batches, send = self._run(
+ [
+ {"DimensionValues": [{"Value": "Amazon Simple Storage Service"}, {"Value": "AWS Lambda"}]},
+ cost_page(
+ [{"Keys": ["AWS Lambda", "arn:aws:lambda:us-east-1:000000000000:function:f"], "Metrics": {}}]
+ ),
+ ],
+ manager,
+ endpoint="cost_and_usage_with_resources_daily",
+ )
+
+ assert [call[0][2] for call in send.call_args_list] == ["GetDimensionValues", "GetCostAndUsageWithResources"]
+ assert send.call_args_list[1][0][3]["Filter"] == {
+ "Dimensions": {"Key": "SERVICE", "Values": ["Amazon Simple Storage Service", "AWS Lambda"]}
+ }
+ assert batches[0][0]["resource_id"] == "arn:aws:lambda:us-east-1:000000000000:function:f"
+
+ def test_a_window_without_services_skips_the_resource_request(self) -> None:
+ manager = FakeResumeManager()
+
+ batches, send = self._run([{"DimensionValues": []}], manager, endpoint="cost_and_usage_with_resources_daily")
+
+ assert batches == []
+ assert send.call_count == 1
+
+ def test_dimension_values_are_listed_per_dimension_with_their_attributes(self) -> None:
+ manager = FakeResumeManager()
+
+ batches, send = self._run(
+ [
+ {"DimensionValues": [{"Value": "111111111111", "Attributes": {"description": "0010"}}]},
+ {"DimensionValues": [{"Value": "AWS Lambda", "Attributes": {}}]},
+ {"DimensionValues": [{"Value": "us-east-1", "Attributes": {}}]},
+ ],
+ manager,
+ endpoint="dimension_values",
+ )
+
+ assert [call[0][3]["Dimension"] for call in send.call_args_list] == ["LINKED_ACCOUNT", "SERVICE", "REGION"]
+ assert "Granularity" not in send.call_args_list[0][0][3]
+ assert batches == [
+ [{"dimension": "LINKED_ACCOUNT", "value": "111111111111", "description": "0010"}],
+ [{"dimension": "SERVICE", "value": "AWS Lambda"}],
+ [{"dimension": "REGION", "value": "us-east-1"}],
+ ]
+
+ def test_a_saved_dimension_resumes_at_that_dimension_and_page(self) -> None:
+ manager = FakeResumeManager(
+ AwsCostExplorerResumeConfig(window_start="2024-03-01", next_page_token="page-2", slice_key="SERVICE")
+ )
+
+ _, send = self._run([{"DimensionValues": []}, {"DimensionValues": []}], manager, endpoint="dimension_values")
+
+ assert [(call[0][3]["Dimension"], call[0][3].get("NextPageToken")) for call in send.call_args_list] == [
+ ("SERVICE", "page-2"),
+ ("REGION", None),
+ ]
+
+ def test_savings_plans_coverage_walks_its_next_token_pages(self) -> None:
+ manager = FakeResumeManager()
+
+ def coverage_page(day: str, next_token: Optional[str]) -> dict[str, Any]:
+ body: dict[str, Any] = {
+ "SavingsPlansCoverages": [
+ {
+ "Attributes": {},
+ "Coverage": {"CoveragePercentage": "40", "OnDemandCost": "6"},
+ "TimePeriod": {"Start": day, "End": "2024-03-03"},
+ }
+ ]
+ }
+ if next_token:
+ body["NextToken"] = next_token
+ return body
+
+ batches, send = self._run(
+ [coverage_page("2024-03-01", "page-2"), coverage_page("2024-03-02", None)],
+ manager,
+ endpoint="savings_plans_coverage_daily",
+ )
+
+ assert send.call_args_list[1][0][3]["NextToken"] == "page-2"
+ assert [row["coverage_percentage"] for batch in batches for row in batch] == [40.0, 40.0]
+ assert batches[0][0]["on_demand_cost"] == 6.0
+
+ def test_reservation_coverage_is_requested_and_tagged_per_service(self) -> None:
+ # Without a SERVICE filter AWS reports EC2 only, so RDS and the others would go missing.
+ manager = FakeResumeManager()
+ coverage = {
+ "CoveragesByTime": [
+ {
+ "TimePeriod": {"Start": "2024-03-01", "End": "2024-03-02"},
+ "Groups": [],
+ "Total": {
+ "CoverageHours": {"ReservedHours": "18", "CoverageHoursPercentage": "75"},
+ "CoverageCost": {"OnDemandCost": "1.5"},
+ },
+ }
+ ]
+ }
+
+ batches, send = self._run([coverage] * 4, manager, endpoint="reservation_coverage_daily")
+
+ services = [call[0][3]["Filter"]["Dimensions"]["Values"] for call in send.call_args_list]
+ assert services == [
+ ["Amazon Elastic Compute Cloud - Compute"],
+ ["Amazon Relational Database Service"],
+ ["Amazon ElastiCache"],
+ ["Amazon Redshift"],
+ ]
+ assert [batch[0]["service"] for batch in batches] == [service[0] for service in services]
+ row = batches[0][0]
+ assert row["coverage_hours_reserved_hours"] == 18.0
+ assert row["coverage_hours_coverage_hours_percentage"] == 75.0
+ assert row["coverage_cost_on_demand_cost"] == 1.5