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): implement the aws systems manager import source (#110810)

Tom Owers250b12fcade4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 17d2766c22d0..b7f62456de42 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -114,6 +114,7 @@ the row lists both.
| aws_sagemaker | HTTP | requests | ✅ |
| aws_security_hub | HTTP | requests | ✅ |
| aws_ses | HTTP | requests | ✅ |
+| aws_systems_manager | HTTP | requests | ✅ |
| aws_waf | HTTP | requests | ✅ |
| azure_cost_management | HTTP | requests | ✅ |
| azure_devops | HTTP | requests | ✅ |
@@ -932,7 +933,6 @@ doesn't conflict with concurrent PRs.
- aws_savings_plans
- aws_step_functions
- aws_support
-- aws_systems_manager
- aws_trusted_advisor
- aws_xray
- axiom
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/aws_systems_manager.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/aws_systems_manager.py
new file mode 100644
index 000000000000..1cda1012d730
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/aws_systems_manager.py
@@ -0,0 +1,243 @@
+import re
+import json
+import datetime as dt
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.credentials import Credentials
+from botocore.serialize import create_serializer
+from botocore.session import get_session
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_systems_manager.settings import (
+ API_VERSION,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ SystemsManagerEndpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import BoundedRetry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awssystemsmanager import (
+ AwsSystemsManagerSourceConfig,
+)
+
+TRANSPORT_RETRY = BoundedRetry(
+ total=3,
+ backoff_factor=1,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset({"POST"}),
+ raise_on_status=False,
+)
+_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+
+
+@frozen
+class SystemsManagerResumeConfig:
+ next_token: str | None = None
+ completed: bool = False
+
+
+class SystemsManagerError(Exception):
+ def __init__(self, code: str, message: str) -> None:
+ self.code = code
+ self.message = message
+ super().__init__(f"AWS Systems Manager request failed: {code} - {message}")
+
+
+class SystemsManagerThrottledError(SystemsManagerError):
+ pass
+
+
+def error_for_response(response: requests.Response) -> SystemsManagerError:
+ try:
+ body = response.json()
+ except ValueError:
+ body = {}
+ if not isinstance(body, dict):
+ body = {}
+ raw_code = response.headers.get("x-amzn-ErrorType") or body.get("__type") or body.get("code")
+ code = str(raw_code or f"HTTP {response.status_code}").split(":")[0].rsplit("#", 1)[-1]
+ message = str(body.get("Message") or body.get("message") or response.text)[:500]
+ # The HTTP transport cannot detect throttling encoded in a 400 response.
+ if response.status_code == 400 and code in {"Throttling", "ThrottlingException", "TooManyRequestsException"}:
+ return SystemsManagerThrottledError(code, message)
+ return SystemsManagerError(code, message)
+
+
+class SystemsManagerClient:
+ def __init__(self, config: AwsSystemsManagerSourceConfig, api_version: str) -> None:
+ if api_version != API_VERSION:
+ raise ValueError(f"Unsupported AWS Systems Manager API version: {api_version}")
+ if not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-\d+", config.aws_region):
+ raise ValueError("Enter a valid AWS region, such as us-east-1.")
+ session = get_session()
+ self._model = session.get_service_model("ssm", api_version=api_version)
+ self._serializer = create_serializer(self._model.metadata["protocol"])
+ endpoint = session.get_component("endpoint_resolver").construct_endpoint("ssm", config.aws_region)
+ if endpoint is None:
+ raise ValueError("AWS Systems Manager is unavailable in this region. Select another region.")
+ self.url = f"https://{endpoint['hostname']}/"
+ self.region = config.aws_region
+ self._signer = SigV4Auth(
+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),
+ "ssm",
+ self.region,
+ )
+ self._session = make_tracked_session(
+ retry=TRANSPORT_RETRY,
+ redact_values=tuple(
+ value
+ for value in (config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token)
+ if value
+ ),
+ )
+
+ def close(self) -> None:
+ self._session.close()
+
+ @retry(
+ retry=retry_if_exception_type(SystemsManagerThrottledError),
+ stop=stop_after_attempt(6),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ serialized = self._serializer.serialize_to_request(payload, self._model.operation_model(operation))
+ request = AWSRequest(method="POST", url=self.url, data=serialized["body"], headers=serialized["headers"])
+ self._signer.add_auth(request)
+ response = self._session.post(
+ self.url, data=serialized["body"], headers=dict(request.headers), timeout=60, allow_redirects=False
+ )
+ if response.status_code >= 400:
+ raise error_for_response(response)
+ response.raise_for_status()
+ body = response.json()
+ if not isinstance(body, dict):
+ raise ValueError("AWS Systems Manager returned an invalid response.")
+ return body
+
+
+def request_payload(endpoint: SystemsManagerEndpoint, *, probe: bool = False) -> dict[str, Any]:
+ payload: dict[str, Any] = {"MaxResults": endpoint.probe_size if probe else endpoint.page_size}
+ if endpoint.operation == "GetInventory":
+ payload["ResultAttributes"] = [{"TypeName": "AWS:InstanceInformation"}]
+ return payload
+
+
+def _flatten(obj: dict[str, Any], prefix: str = "") -> dict[str, Any]:
+ row: dict[str, Any] = {}
+ for key, value in obj.items():
+ column = prefix + _CAMEL_BOUNDARY.sub("_", key).lower()
+ if key == "Data" and not prefix:
+ # Inventory type names and content keys are dynamic, so retain them in one JSON column.
+ row[column] = json.dumps(value)
+ elif isinstance(value, dict):
+ row.update(_flatten(value, column + "_"))
+ else:
+ row[column] = value
+ return row
+
+
+def normalize_row(item: dict[str, Any], endpoint: SystemsManagerEndpoint, region: str) -> dict[str, Any]:
+ row = _flatten(item)
+ row["region"] = region
+ for name in endpoint.timestamps:
+ value = row.get(name)
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ row[name] = dt.datetime.fromtimestamp(value, tz=dt.UTC)
+ return row
+
+
+def get_rows(
+ config: AwsSystemsManagerSourceConfig,
+ endpoint: SystemsManagerEndpoint,
+ api_version: str,
+ manager: ResumableSourceManager[SystemsManagerResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ state = manager.load_state() if manager.can_resume() else None
+ if state and state.completed:
+ return
+ next_token = state.next_token if state else None
+ resumed = bool(next_token)
+ client = SystemsManagerClient(config, api_version)
+ try:
+ while True:
+ payload = request_payload(endpoint)
+ if next_token:
+ payload["NextToken"] = next_token
+ try:
+ body = client.request(endpoint.operation, payload)
+ except SystemsManagerError as error:
+ if resumed and error.code == "InvalidNextToken":
+ next_token = None
+ resumed = False
+ continue
+ raise
+ resumed = False
+ rows = [normalize_row(item, endpoint, client.region) for item in body.get(endpoint.result_key, [])]
+ token = body.get("NextToken") or None
+ if token is not None and (not isinstance(token, str) or token == next_token):
+ raise ValueError("AWS Systems Manager returned an invalid or repeated page token.")
+ next_token = token
+ manager.save_state(SystemsManagerResumeConfig(next_token=next_token, completed=next_token is None))
+ if rows:
+ yield rows
+ manager.safe_point()
+ if next_token is None:
+ return
+ finally:
+ client.close()
+
+
+def validate_credentials(
+ config: AwsSystemsManagerSourceConfig, api_version: str, schema_name: str | None = None
+) -> tuple[bool, str | None]:
+ if not config.aws_access_key_id or not config.aws_secret_access_key:
+ return False, "Enter both an AWS access key ID and a secret access key."
+ endpoint = ENDPOINTS.get(schema_name or "managed_instances")
+ if endpoint is None:
+ return False, f"Unknown AWS Systems Manager table: {schema_name}"
+ try:
+ client = SystemsManagerClient(config, api_version)
+ except ValueError as error:
+ return False, str(error)
+ try:
+ client.request(endpoint.operation, request_payload(endpoint, probe=True))
+ except SystemsManagerError as error:
+ if error.code in {"AccessDenied", "AccessDeniedException"}:
+ if schema_name is None:
+ return True, None
+ return False, f"Grant ssm:{endpoint.operation} to read this table."
+ return False, ERROR_MESSAGES.get(
+ error.code, "AWS Systems Manager could not validate the credentials. Try again."
+ )
+ except requests.RequestException:
+ return False, "Could not reach AWS Systems Manager. Check the region and try again."
+ finally:
+ client.close()
+ return True, None
+
+
+def aws_systems_manager_source(
+ config: AwsSystemsManagerSourceConfig,
+ schema_name: str,
+ api_version: str,
+ manager: ResumableSourceManager[SystemsManagerResumeConfig],
+) -> SourceResponse:
+ endpoint = ENDPOINTS.get(schema_name)
+ if endpoint is None:
+ raise ValueError(f"Unknown AWS Systems Manager table: {schema_name}")
+ return SourceResponse(
+ name=schema_name,
+ items=lambda: get_rows(config, endpoint, api_version, manager),
+ primary_keys=list(endpoint.primary_key),
+ sort_mode=None,
+ on_complete=manager.clear_state,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/canonical_descriptions.py
new file mode 100644
index 000000000000..3e63f5f0ff47
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/canonical_descriptions.py
@@ -0,0 +1,73 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "managed_instances": {
+ "description": "Managed nodes in the selected region. Stopped and terminated nodes are excluded.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstanceInformation.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "instance_id": "Identifier of the managed node.",
+ "agent_version": "Version of SSM Agent installed on the node.",
+ "ping_status": "Connection status reported by SSM Agent.",
+ "last_ping_date_time": "Time when SSM Agent last contacted Systems Manager.",
+ "platform_type": "Operating system family of the managed node.",
+ "platform_name": "Operating system name reported by the node.",
+ "platform_version": "Operating system version reported by the node.",
+ "ip_address": "IP address of the managed node.",
+ "registration_date": "Time when the node registered with Systems Manager.",
+ },
+ },
+ "inventory": {
+ "description": "Collected instance inventory, including stopped and terminated nodes.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetInventory.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "id": "Identifier of the managed node that owns this inventory.",
+ "data": "JSON containing AWS:InstanceInformation content, capture time, and schema version.",
+ },
+ },
+ "resource_compliance_summaries": {
+ "description": "Compliance results grouped by resource and compliance type in the selected region.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListResourceComplianceSummaries.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "resource_id": "Identifier of the resource checked for compliance.",
+ "resource_type": "Type of resource checked for compliance.",
+ "compliance_type": "Compliance category, such as Patch or Association.",
+ "status": "Overall compliance status of this resource for this category.",
+ "overall_severity": "Highest severity of the compliance results.",
+ "compliant_summary_compliant_count": "Number of compliant items.",
+ "non_compliant_summary_non_compliant_count": "Number of items that are not compliant.",
+ "execution_summary_execution_time": "Time of the execution that produced these compliance results.",
+ },
+ },
+ "associations": {
+ "description": "State Manager associations with their targets, schedules, and execution status.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListAssociations.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "association_id": "Identifier of the association.",
+ "association_name": "Name assigned to the association.",
+ "name": "Name of the SSM document used by the association.",
+ "association_version": "Version of the association.",
+ "document_version": "Version of the SSM document used by the association.",
+ "last_execution_date": "Time when the association last ran.",
+ "schedule_expression": "Schedule that controls when the association runs.",
+ "targets": "Resources selected by the association.",
+ },
+ },
+ "patch_baselines": {
+ "description": "Patch baseline identities and supported operating systems in the selected region.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribePatchBaselines.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "baseline_id": "Identifier of the patch baseline.",
+ "baseline_name": "Name assigned to the patch baseline.",
+ "baseline_description": "Description assigned to the patch baseline.",
+ "default_baseline": "Whether this is the default baseline for its operating system.",
+ "operating_system": "Operating system supported by the patch baseline.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/settings.py
new file mode 100644
index 000000000000..e51b4edd1e61
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/settings.py
@@ -0,0 +1,76 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+API_VERSION = "2014-11-06"
+API_DOCS_URL = "https://docs.aws.amazon.com/systems-manager/latest/APIReference/Welcome.html"
+
+
+@frozen
+class SystemsManagerEndpoint:
+ operation: str
+ result_key: str
+ primary_key: tuple[str, ...]
+ description: str
+ page_size: int = 50
+ probe_size: int = 1
+ timestamps: tuple[str, ...] = ()
+
+
+ENDPOINTS: dict[str, SystemsManagerEndpoint] = {
+ "managed_instances": SystemsManagerEndpoint(
+ operation="DescribeInstanceInformation",
+ result_key="InstanceInformationList",
+ primary_key=("region", "instance_id"),
+ description="Managed nodes with agent, platform, and connection details. Stopped and terminated nodes are excluded.",
+ probe_size=5,
+ timestamps=(
+ "last_ping_date_time",
+ "registration_date",
+ "last_association_execution_date",
+ "last_successful_association_execution_date",
+ ),
+ ),
+ "inventory": SystemsManagerEndpoint(
+ operation="GetInventory",
+ result_key="Entities",
+ primary_key=("region", "id"),
+ description="Collected AWS:InstanceInformation inventory, including stopped and terminated nodes.",
+ ),
+ "resource_compliance_summaries": SystemsManagerEndpoint(
+ operation="ListResourceComplianceSummaries",
+ result_key="ResourceComplianceSummaryItems",
+ primary_key=("region", "resource_type", "resource_id", "compliance_type"),
+ description="Compliance status and severity counts for each resource and compliance type.",
+ timestamps=("execution_summary_execution_time",),
+ ),
+ "associations": SystemsManagerEndpoint(
+ operation="ListAssociations",
+ result_key="Associations",
+ primary_key=("region", "association_id"),
+ description="State Manager associations with schedules, targets, and execution status.",
+ timestamps=("last_execution_date",),
+ ),
+ "patch_baselines": SystemsManagerEndpoint(
+ operation="DescribePatchBaselines",
+ result_key="BaselineIdentities",
+ primary_key=("region", "baseline_id"),
+ description="Patch baseline identities, operating systems, and default baseline flags.",
+ page_size=100,
+ ),
+}
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
+
+ERROR_MESSAGES = {
+ "AccessDenied": "AWS denied access. Grant the ssm read permission for the selected table.",
+ "AccessDeniedException": "AWS denied access. Grant the ssm read permission for the selected table.",
+ "UnrecognizedClientException": "AWS rejected the credentials. Check the access key and secret, and include the token for temporary credentials.",
+ "InvalidClientTokenId": "AWS rejected the access key. Check that the key is active.",
+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and region.",
+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key and region.",
+ "ExpiredToken": "The AWS session token expired. Enter new temporary credentials.",
+ "ExpiredTokenException": "The AWS session token expired. Enter new temporary credentials.",
+ "SubscriptionRequiredException": "Enable AWS Systems Manager for this account and region, then try again.",
+ "OptInRequired": "Enable AWS Systems Manager for this account and region, then try again.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/source.py
index 717fee17ffa2..85e29a40e462 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/source.py
@@ -1,8 +1,38 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_systems_manager.aws_systems_manager import (
+ SystemsManagerResumeConfig,
+ aws_systems_manager_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_systems_manager.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_systems_manager.settings import (
+ API_DOCS_URL,
+ API_VERSION,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awssystemsmanager import (
AwsSystemsManagerSourceConfig,
)
@@ -10,18 +40,115 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AwsSystemsManagerSource(SimpleSource[AwsSystemsManagerSourceConfig]):
+class AwsSystemsManagerSource(ResumableSource[AwsSystemsManagerSourceConfig, SystemsManagerResumeConfig]):
+ lists_tables_without_credentials = True
+ # SSM uses an unversioned target; the pinned botocore model serializes every request.
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AWSSYSTEMSMANAGER
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {f"AWS Systems Manager request failed: {code}": message for code, message in ERROR_MESSAGES.items()}
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AwsSystemsManagerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ descriptions={name: endpoint.description for name, endpoint in ENDPOINTS.items()},
+ )
+
+ def validate_credentials(
+ self,
+ config: AwsSystemsManagerSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, self.resolve_api_version(api_version), schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SystemsManagerResumeConfig]:
+ return ResumableSourceManager(inputs, SystemsManagerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AwsSystemsManagerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SystemsManagerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aws_systems_manager_source(
+ config, inputs.schema_name, self.resolve_api_version(inputs.api_version), resumable_source_manager
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.AWSSYSTEMSMANAGER,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Amazon Web Services (AWS Systems Manager)",
+ label="AWS Systems Manager",
+ caption="""Sync fleet inventory, compliance summaries, associations, and patch baselines from one AWS region.
+
+Grant these IAM permissions for the tables you select:
+`ssm:DescribeInstanceInformation`, `ssm:GetInventory`, `ssm:ListResourceComplianceSummaries`,
+`ssm:ListAssociations`, and `ssm:DescribePatchBaselines`.
+
+Enter an access key ID and secret access key. Include a session token for temporary credentials.
+All tables use full refresh. Create a separate source for each region.""",
iconPath="/static/services/aws_systems_manager.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl=API_DOCS_URL,
+ keywords=["aws", "ssm"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="aws_access_key_id",
+ label="AWS access key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="AKIA...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="aws_secret_access_key",
+ label="AWS secret access key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="aws_region",
+ label="AWS region",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="us-east-1",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="aws_session_token",
+ label="AWS session token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="Only needed for temporary credentials",
+ secret=True,
+ caption="Temporary credentials expire. Update them before the next scheduled sync.",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/tests/test_aws_systems_manager.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/tests/test_aws_systems_manager.py
new file mode 100644
index 000000000000..76f5c0b5e478
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/tests/test_aws_systems_manager.py
@@ -0,0 +1,447 @@
+import json
+import datetime as dt
+from collections.abc import Generator, Iterable, Iterator
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+import structlog
+from tenacity import wait_none
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_systems_manager import (
+ aws_systems_manager as transport,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_systems_manager.aws_systems_manager import (
+ SystemsManagerClient,
+ SystemsManagerError,
+ SystemsManagerResumeConfig,
+ SystemsManagerThrottledError,
+ aws_systems_manager_source,
+ error_for_response,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_systems_manager.settings import API_VERSION
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_systems_manager.source import (
+ AwsSystemsManagerSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awssystemsmanager import (
+ AwsSystemsManagerSourceConfig,
+)
+
+
+def response(body: object, status: int = 200, headers: dict[str, str] | None = None) -> requests.Response:
+ result = requests.Response()
+ result.status_code = status
+ result._content = json.dumps(body).encode()
+ result.headers.update(headers or {})
+ return result
+
+
+def iter_batches(source: SourceResponse) -> Iterator[list[dict[str, Any]]]:
+ return iter(cast(Iterable[list[dict[str, Any]]], source.items()))
+
+
+def config() -> AwsSystemsManagerSourceConfig:
+ return AwsSystemsManagerSourceConfig(
+ aws_access_key_id="AKIAEXAMPLE",
+ aws_secret_access_key="fake-secret",
+ aws_region="eu-west-1",
+ aws_session_token="fake-token",
+ )
+
+
+def http() -> Iterator[MagicMock]:
+ with patch.object(transport, "make_tracked_session") as factory:
+ session = factory.return_value
+ session.post.return_value = response({})
+ yield session
+
+
+def manager() -> MagicMock:
+ result = MagicMock(spec=ResumableSourceManager)
+ result.can_resume.return_value = False
+ return result
+
+
+ "region,host",
+ [
+ ("eu-west-1", "ssm.eu-west-1.amazonaws.com"),
+ ("cn-north-1", "ssm.cn-north-1.amazonaws.com.cn"),
+ ("us-gov-west-1", "ssm.us-gov-west-1.amazonaws.com"),
+ ],
+)
[email protected]("token", [None, "fake-token"])
+def test_signs_serialized_body_for_selected_region(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, region: str, host: str, token: str | None
+) -> None:
+ config.aws_region = region
+ config.aws_session_token = token
+ client = SystemsManagerClient(config, API_VERSION)
+ client.request("DescribeInstanceInformation", {"MaxResults": 5})
+ call = http.post.call_args
+ assert call.args == (f"https://{host}/",)
+ assert json.loads(call.kwargs["data"]) == {"MaxResults": 5}
+ headers = call.kwargs["headers"]
+ assert headers["X-Amz-Target"] == "AmazonSSM.DescribeInstanceInformation"
+ assert headers["Content-Type"] == "application/x-amz-json-1.1"
+ assert headers.get("X-Amz-Security-Token") == token
+ assert f"/{region}/ssm/aws4_request" in headers["Authorization"]
+ assert "content-type;host;x-amz-date;" in headers["Authorization"]
+ assert "x-amz-target" in headers["Authorization"]
+ assert headers["X-Amz-Date"]
+ assert call.kwargs["allow_redirects"] is False
+ assert call.kwargs["timeout"] == 60
+ factory = cast(MagicMock, transport.make_tracked_session)
+ assert config.aws_secret_access_key in factory.call_args.kwargs["redact_values"]
+ if token:
+ assert token in factory.call_args.kwargs["redact_values"]
+
+
+ "region", ["", "https://example.com", "us-east-1.example.com", "../us-east-1", "us-east-1/path"]
+)
+def test_rejects_region_before_sending_credentials(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, region: str
+) -> None:
+ config.aws_region = region
+ valid, reason = validate_credentials(config, API_VERSION)
+ assert not valid and reason and "valid AWS region" in reason
+ http.post.assert_not_called()
+
+
+def test_rejects_unsupported_model_version(config: AwsSystemsManagerSourceConfig, http: MagicMock) -> None:
+ valid, reason = validate_credentials(config, "2099-01-01")
+ assert not valid and reason and "Unsupported" in reason
+ http.post.assert_not_called()
+
+
+ "name,operation,key,item,expected_key,page_size",
+ [
+ (
+ "managed_instances",
+ "DescribeInstanceInformation",
+ "InstanceInformationList",
+ {"InstanceId": "i-example"},
+ "instance_id",
+ 50,
+ ),
+ ("inventory", "GetInventory", "Entities", {"Id": "i-example"}, "id", 50),
+ (
+ "resource_compliance_summaries",
+ "ListResourceComplianceSummaries",
+ "ResourceComplianceSummaryItems",
+ {"ResourceId": "i-example", "ResourceType": "ManagedInstance", "ComplianceType": "Patch"},
+ "resource_id",
+ 50,
+ ),
+ (
+ "associations",
+ "ListAssociations",
+ "Associations",
+ {"AssociationId": "association-example"},
+ "association_id",
+ 50,
+ ),
+ (
+ "patch_baselines",
+ "DescribePatchBaselines",
+ "BaselineIdentities",
+ {"BaselineId": "pb-example"},
+ "baseline_id",
+ 100,
+ ),
+ ],
+)
[email protected]("terminal_token", [None, ""])
+def test_paginates_empty_and_terminal_pages(
+ config: AwsSystemsManagerSourceConfig,
+ http: MagicMock,
+ manager: MagicMock,
+ name: str,
+ operation: str,
+ key: str,
+ item: dict[str, Any],
+ expected_key: str,
+ page_size: int,
+ terminal_token: str | None,
+) -> None:
+ http.post.side_effect = [
+ response({key: [], "NextToken": "next"}),
+ response({key: [item], "NextToken": terminal_token}),
+ ]
+ source = aws_systems_manager_source(config, name, API_VERSION, manager)
+ rows = [row for batch in iter_batches(source) for row in batch]
+ assert len(rows) == 1
+ assert rows[0][expected_key] == next(iter(item.values()))
+ assert rows[0]["region"] == "eu-west-1"
+ assert len({tuple(row[column] for column in source.primary_keys or []) for row in rows}) == 1
+ calls = http.post.call_args_list
+ expected: dict[str, Any] = {"MaxResults": page_size}
+ if name == "inventory":
+ expected["ResultAttributes"] = [{"TypeName": "AWS:InstanceInformation"}]
+ assert json.loads(calls[0].kwargs["data"]) == expected
+ assert json.loads(calls[1].kwargs["data"]) == {**expected, "NextToken": "next"}
+ assert calls[0].kwargs["headers"]["X-Amz-Target"] == f"AmazonSSM.{operation}"
+ assert manager.save_state.call_args_list[0].args[0] == SystemsManagerResumeConfig(next_token="next")
+ assert manager.save_state.call_args_list[1].args[0] == SystemsManagerResumeConfig(completed=True)
+ assert manager.safe_point.call_count == 2
+ manager.clear_state.assert_not_called()
+ assert source.on_complete is not None
+ source.on_complete()
+ manager.clear_state.assert_called_once()
+ http.close.assert_called_once()
+
+
+def test_resume_state_is_staged_before_yield(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, manager: MagicMock
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SystemsManagerResumeConfig(next_token="saved")
+ http.post.return_value = response({"Associations": [{"AssociationId": "a-example"}], "NextToken": "later"})
+ rows = cast(
+ Generator[list[dict[str, Any]]],
+ aws_systems_manager_source(config, "associations", API_VERSION, manager).items(),
+ )
+ assert next(rows)[0]["association_id"] == "a-example"
+ assert json.loads(http.post.call_args.kwargs["data"]) == {"MaxResults": 50, "NextToken": "saved"}
+ manager.save_state.assert_called_once_with(SystemsManagerResumeConfig(next_token="later"))
+ rows.close()
+ http.close.assert_called_once()
+
+
+def test_completed_resume_does_not_restart_walk(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, manager: MagicMock
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SystemsManagerResumeConfig(completed=True)
+ assert list(iter_batches(aws_systems_manager_source(config, "associations", API_VERSION, manager))) == []
+ http.post.assert_not_called()
+
+
[email protected]("resumed", [False, True])
+def test_expired_token_restarts_only_saved_walk(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, manager: MagicMock, resumed: bool
+) -> None:
+ manager.can_resume.return_value = resumed
+ manager.load_state.return_value = SystemsManagerResumeConfig(next_token="expired")
+ http.post.side_effect = [
+ response({"__type": "InvalidNextToken", "Message": "The specified token isn't valid."}, 400),
+ response({"Associations": [{"AssociationId": "a-example"}]}),
+ ]
+ source = aws_systems_manager_source(config, "associations", API_VERSION, manager)
+ if resumed:
+ batches = list(iter_batches(source))
+ assert batches[0][0]["association_id"] == "a-example"
+ assert json.loads(http.post.call_args_list[1].kwargs["data"]) == {"MaxResults": 50}
+ else:
+ with pytest.raises(SystemsManagerError, match="InvalidNextToken"):
+ list(iter_batches(source))
+ assert http.post.call_count == 1
+
+
[email protected]("token", ["same", 123])
+def test_invalid_pagination_fails_without_loop(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, manager: MagicMock, token: object
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SystemsManagerResumeConfig(next_token="same")
+ http.post.return_value = response({"NextToken": token})
+ with pytest.raises(ValueError, match="invalid or repeated page token"):
+ list(iter_batches(aws_systems_manager_source(config, "associations", API_VERSION, manager)))
+ assert http.post.call_count == 1
+ manager.save_state.assert_not_called()
+
+
+ "code,fragment",
+ [
+ ("UnrecognizedClientException", "Check the access key"),
+ ("InvalidClientTokenId", "active"),
+ ("InvalidSignatureException", "signature"),
+ ("SignatureDoesNotMatch", "signature"),
+ ("ExpiredTokenException", "expired"),
+ ("ExpiredToken", "expired"),
+ ("SubscriptionRequiredException", "Enable AWS Systems Manager"),
+ ("OptInRequired", "Enable AWS Systems Manager"),
+ ],
+)
+def test_authentication_errors_are_terminal_and_actionable(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, code: str, fragment: str
+) -> None:
+ http.post.return_value = response({"__type": f"com.amazonaws.ssm#{code}", "message": "Rejected"}, 400)
+ valid, reason = validate_credentials(config, API_VERSION)
+ assert not valid and reason and fragment in reason
+ error = error_for_response(http.post.return_value)
+ matches = [
+ message
+ for pattern, message in AwsSystemsManagerSource().get_non_retryable_errors().items()
+ if pattern in str(error)
+ ]
+ assert reason in matches
+ assert http.post.call_count == 1
+
+
[email protected]("code", ["AccessDenied", "AccessDeniedException"])
[email protected]("schema,expected", [(None, True), ("inventory", False)])
+def test_permission_denial_only_allows_source_creation(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, code: str, schema: str | None, expected: bool
+) -> None:
+ http.post.return_value = response({"__type": code, "Message": "Access denied"}, 400)
+ valid, reason = validate_credentials(config, API_VERSION, schema)
+ assert valid is expected
+ assert reason is None if expected else reason == "Grant ssm:GetInventory to read this table."
+ assert http.post.call_count == 1
+
+
+ "schema,operation,size",
+ [
+ (None, "DescribeInstanceInformation", 5),
+ ("inventory", "GetInventory", 1),
+ ("patch_baselines", "DescribePatchBaselines", 1),
+ ],
+)
+def test_validation_uses_one_small_request(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, schema: str | None, operation: str, size: int
+) -> None:
+ assert validate_credentials(config, API_VERSION, schema) == (True, None)
+ assert http.post.call_count == 1
+ assert json.loads(http.post.call_args.kwargs["data"])["MaxResults"] == size
+ assert http.post.call_args.kwargs["headers"]["X-Amz-Target"] == f"AmazonSSM.{operation}"
+ http.close.assert_called_once()
+
+
[email protected]("field", ["aws_access_key_id", "aws_secret_access_key"])
+def test_missing_credentials_do_not_send_request(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, field: str
+) -> None:
+ setattr(config, field, "")
+ valid, reason = validate_credentials(config, API_VERSION)
+ assert not valid and reason and "Enter both" in reason
+ http.post.assert_not_called()
+
+
+def test_unknown_table_fails_before_request(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, manager: MagicMock
+) -> None:
+ valid, reason = validate_credentials(config, API_VERSION, "unknown")
+ assert not valid and reason and "Unknown" in reason
+ with pytest.raises(ValueError, match="Unknown AWS Systems Manager table"):
+ aws_systems_manager_source(config, "unknown", API_VERSION, manager)
+ http.post.assert_not_called()
+
+
+ "status,body,headers,code",
+ [
+ (400, {"__type": "com.amazonaws.ssm#AccessDeniedException", "Message": "denied"}, {}, "AccessDeniedException"),
+ (403, {}, {"x-amzn-ErrorType": "InvalidSignatureException:detail"}, "InvalidSignatureException"),
+ (400, {"code": "OptInRequired"}, {}, "OptInRequired"),
+ (502, [], {}, "HTTP 502"),
+ ],
+)
+def test_decodes_aws_errors(status: int, body: object, headers: dict[str, str], code: str) -> None:
+ error = error_for_response(response(body, status, headers))
+ assert error.code == code
+ assert not isinstance(error, SystemsManagerThrottledError)
+
+
[email protected]("code", ["Throttling", "ThrottlingException", "TooManyRequestsException"])
+def test_retries_body_throttling(config: AwsSystemsManagerSourceConfig, http: MagicMock, code: str) -> None:
+ http.post.side_effect = [response({"__type": code}, 400), response({"Associations": []})]
+ client = SystemsManagerClient(config, API_VERSION)
+ request = cast(Any, client.request).retry_with(wait=wait_none())
+ assert request(client, "ListAssociations", {"MaxResults": 50}) == {"Associations": []}
+ assert http.post.call_count == 2
+
+
[email protected]("status", [429, 500, 502, 503, 504])
+def test_status_retries_belong_only_to_tracked_transport(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, status: int
+) -> None:
+ http.post.return_value = response({"__type": "InternalServerError"}, status)
+ with pytest.raises(SystemsManagerError):
+ SystemsManagerClient(config, API_VERSION).request("ListAssociations", {"MaxResults": 50})
+ assert http.post.call_count == 1
+ factory = cast(MagicMock, transport.make_tracked_session)
+ assert factory.call_args.kwargs["retry"].is_retry("POST", status)
+
+
+def test_network_failure_is_not_reported_as_valid_credentials(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock
+) -> None:
+ http.post.side_effect = requests.ConnectionError("unreachable")
+ valid, reason = validate_credentials(config, API_VERSION)
+ assert not valid and reason and "Could not reach" in reason
+ http.close.assert_called_once()
+
+
+def test_normalizes_nested_counts_timestamps_and_composite_keys(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, manager: MagicMock
+) -> None:
+ http.post.return_value = response(
+ {
+ "ResourceComplianceSummaryItems": [
+ {
+ "ResourceId": "i-example",
+ "ResourceType": "ManagedInstance",
+ "ComplianceType": compliance,
+ "CompliantSummary": {"CompliantCount": 2},
+ "ExecutionSummary": {"ExecutionTime": 1735689600},
+ }
+ for compliance in ["Patch", "Association"]
+ ]
+ }
+ )
+ source = aws_systems_manager_source(config, "resource_compliance_summaries", API_VERSION, manager)
+ batches = list(iter_batches(source))
+ rows = batches[0]
+ assert len({tuple(row[key] for key in source.primary_keys or []) for row in rows}) == 2
+ assert rows[0]["compliant_summary_compliant_count"] == 2
+ assert rows[0]["execution_summary_execution_time"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+
+
+def test_preserves_inventory_content(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, manager: MagicMock
+) -> None:
+ data = {
+ "AWS:InstanceInformation": {
+ "CaptureTime": "2025-01-01T00:00:00Z",
+ "Content": [{"InstanceId": "i-example", "InstanceStatus": "Stopped"}],
+ }
+ }
+ http.post.return_value = response({"Entities": [{"Id": "i-example", "Data": data}]})
+ batches = list(iter_batches(aws_systems_manager_source(config, "inventory", API_VERSION, manager)))
+ row = batches[0][0]
+ assert json.loads(row["data"]) == data
+
+
[email protected]("incremental", [False, True])
+def test_snapshot_requests_never_filter_by_watermark(
+ config: AwsSystemsManagerSourceConfig, http: MagicMock, manager: MagicMock, incremental: bool
+) -> None:
+ inputs = SourceInputs(
+ schema_name="managed_instances",
+ schema_id="schema",
+ source_id="source",
+ team_id=1,
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=dt.datetime(2025, 1, 1, tzinfo=dt.UTC),
+ db_incremental_field_earliest_value=None,
+ incremental_field="last_ping_date_time",
+ incremental_field_type=None,
+ job_id="job",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+ list(iter_batches(AwsSystemsManagerSource().source_for_pipeline(config, manager, inputs)))
+ assert json.loads(http.post.call_args.kwargs["data"]) == {"MaxResults": 50}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssystemsmanager.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssystemsmanager.py
index ad9998875caf..e5d7f1229be7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssystemsmanager.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssystemsmanager.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AwsSystemsManagerSourceConfig(config.Config):
- pass
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ aws_region: str
+ aws_session_token: str | None = None