from typing import List import boto3 from ddtrace import tracer from datadog_tools.models.aws import AWSResource class AWS: def __init__(self, resource_explorer_view_arn: str, region="us-east-1", resource_explorer_client=None): self.resource_explorer_view_arn = resource_explorer_view_arn self.resource_explorer_client = ( resource_explorer_client if resource_explorer_client else boto3.client("resource-explorer-2", region_name=region) ) @tracer.wrap(service="datadog-tools", resource="AWS.find_resources_by_type_and_service_name") def find_resources_by_type_and_service_name(self, resource_type: str, service_name: str): return self.resource_search(f"tag:service_name={service_name} resourcetype:{resource_type}") @tracer.wrap(service="datadog-tools", resource="AWS.resource_search") def resource_search(self, query_string: str) -> List[AWSResource]: """ Searches for AWS resources using the specified query string. :param query_string: The query string to search for resources. :return: A list of resources matching the query. """ print(f"Searching for resources with query: {query_string} using view arn {self.resource_explorer_view_arn}") response = self.resource_explorer_client.search( ViewArn=self.resource_explorer_view_arn, QueryString=query_string, ) resources = [] for resource in response["Resources"]: properties = resource.get("Properties", []) tags_list = next( (property.get("Data", []) for property in properties if property.get("Name") == "tags"), [] ) tags_dict = {tag["Key"]: tag["Value"] for tag in tags_list} environment = tags_dict["environment"].lower() if "environment" in tags_dict else None application_family = tags_dict.get("application_family") runtime = tags_dict.get("runtime") terraform_github_repository = tags_dict.get("terraform_github_repository") terraform_github_path = tags_dict.get("terraform_github_path") terraformed = tags_dict.get("terraformed", "").lower() == "true" resources.append( AWSResource( arn=resource["Arn"], account_id=resource["OwningAccountId"], application_family=application_family, environment=environment, resource_type=resource["ResourceType"], region=resource["Region"], runtime=runtime, terraform_github_repository=terraform_github_repository, terraform_github_path=terraform_github_path, terraformed=terraformed, ) ) return resources