SDK for Python (Boto3) を使用した AWS Support の例 - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

SDK for Python (Boto3) を使用した AWS Support の例

次のコードサンプルは、AWS Support で AWS SDK for Python (Boto3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

開始方法

次のコード例は、AWS Support の使用を開始する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) def hello_support(support_client): """ Use the AWS SDK for Python (Boto3) to create an AWS Support client and count the available services in your account. This example uses the default settings specified in your shared credentials and config files. :param support_client: A Boto3 Support Client object. """ try: print("Hello, AWS Support! Let's count the available Support services:") response = support_client.describe_services() print(f"There are {len(response['services'])} services available.") except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't count services. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise if __name__ == "__main__": hello_support(boto3.client("support"))
  • API の詳細については、DescribeServicesAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

アクション

次のコード例は、添付ファイルを含む AWS Support コミュニケーションをサポートケースに追加する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def add_communication_to_case(self, attachment_set_id, case_id): """ Add a communication and an attachment set to a case. :param attachment_set_id: The ID of an existing attachment set. :param case_id: The ID of the case. """ try: self.support_client.add_communication_to_case( caseId=case_id, communicationBody="This is an example communication added to a support case.", attachmentSetId=attachment_set_id, ) except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't add communication. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • API の詳細については、AddCommunicationToCaseAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

次のコード例は、AWS Support 添付ファイルを添付セットに追加する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def add_attachment_to_set(self): """ Add an attachment to a set, or create a new attachment set if one does not exist. :return: The attachment set ID. """ try: response = self.support_client.add_attachments_to_set( attachments=[ { "fileName": "attachment_file.txt", "data": b"This is a sample file for attachment to a support case.", } ] ) new_set_id = response["attachmentSetId"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't add attachment. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return new_set_id
  • API の詳細については、AddAttachmentsToSetAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

次のコード例は、新しい AWS Support ケースを作成する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def create_case(self, service, category, severity): """ Create a new support case. :param service: The service to use for the new case. :param category: The category to use for the new case. :param severity: The severity to use for the new case. :return: The caseId of the new case. """ try: response = self.support_client.create_case( subject="Example case for testing, ignore.", serviceCode=service["code"], severityCode=severity["code"], categoryCode=category["code"], communicationBody="Example support case body.", language="en", issueType="customer-service", ) case_id = response["caseId"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't create case. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return case_id
  • API の詳細については、CreateCaseAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

次のコード例は、AWS Support ケースの添付ファイルを説明する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def describe_attachment(self, attachment_id): """ Get information about an attachment by its attachmentID. :param attachment_id: The ID of the attachment. :return: The name of the attached file. """ try: response = self.support_client.describe_attachment( attachmentId=attachment_id ) attached_file = response["attachment"]["fileName"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't get attachment description. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return attached_file
  • API の詳細については、DescribeAttachmentAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

次のコード例は、AWS Support ケースを説明する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def describe_cases(self, after_time, before_time, resolved): """ Describe support cases over a period of time, optionally filtering by status. :param after_time: The start time to include for cases. :param before_time: The end time to include for cases. :param resolved: True to include resolved cases in the results, otherwise results are open cases. :return: The final status of the case. """ try: cases = [] paginator = self.support_client.get_paginator("describe_cases") for page in paginator.paginate( afterTime=after_time, beforeTime=before_time, includeResolvedCases=resolved, language="en", ): cases += page["cases"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't describe cases. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: if resolved: cases = filter(lambda case: case["status"] == "resolved", cases) return cases
  • API の詳細については、DescribeCasesAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

次のコード例は、ケースの AWS Support コミュニケーションを説明する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def describe_all_case_communications(self, case_id): """ Describe all the communications for a case using a paginator. :param case_id: The ID of the case. :return: The communications for the case. """ try: communications = [] paginator = self.support_client.get_paginator("describe_communications") for page in paginator.paginate(caseId=case_id): communications += page["communications"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't describe communications. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return communications
  • API の詳細については、DescribeCommunicationsAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

次のコード例は、AWS サービスのリストについての説明方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def describe_services(self, language): """ Get the descriptions of AWS services available for support for a language. :param language: The language for support services. Currently, only "en" (English) and "ja" (Japanese) are supported. :return: The list of AWS service descriptions. """ try: response = self.support_client.describe_services(language=language) services = response["services"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't get Support services for language %s. Here's why: %s: %s", language, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return services
  • API の詳細については、DescribeServicesAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

次のコード例は、AWS Support 重要度レベルを説明する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def describe_severity_levels(self, language): """ Get the descriptions of available severity levels for support cases for a language. :param language: The language for support severity levels. Currently, only "en" (English) and "ja" (Japanese) are supported. :return: The list of severity levels. """ try: response = self.support_client.describe_severity_levels(language=language) severity_levels = response["severityLevels"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't get severity levels for language %s. Here's why: %s: %s", language, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return severity_levels
  • API の詳細については、DescribeSeverityLevelsAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

次のコード例は、AWS Support ケースを解決する方法を示しています。

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def resolve_case(self, case_id): """ Resolve a support case by its caseId. :param case_id: The ID of the case to resolve. :return: The final status of the case. """ try: response = self.support_client.resolve_case(caseId=case_id) final_status = response["finalCaseStatus"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't resolve case. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return final_status
  • API の詳細については、 ResolveCase AWS SDK for Python (Boto3) API リファレンスの「」を参照してください。

シナリオ

次のコードサンプルは、以下の操作方法を示しています。

  • ケースの利用可能なサービスと重要度レベルを取得して表示する方法

  • 選択したサービス、カテゴリ、重要度レベルを使用してサポートケースを作成する方法

  • 当日のオープンケースのリストを取得して表示する方法

  • 新しいケースに添付セットとコミュニケーションを追加する方法

  • ケースの新しい添付ファイルとコミュニケーションについて説明する方法

  • ケースを解決する方法

  • 当日の解決済みケースのリストを取得して表示する方法

SDK for Python (Boto3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

コマンドプロンプトからインタラクティブのシナリオを実行します。

class SupportCasesScenario: """Runs an interactive scenario that shows how to get started using AWS Support.""" def __init__(self, support_wrapper): """ :param support_wrapper: An object that wraps AWS Support actions. """ self.support_wrapper = support_wrapper def display_and_select_service(self): """ Lists support services and prompts the user to select one. :return: The support service selected by the user. """ print("-" * 88) services_list = self.support_wrapper.describe_services("en") print(f"AWS Support client returned {len(services_list)} services.") print("Displaying first 10 services:") service_choices = [svc["name"] for svc in services_list[:10]] selected_index = q.choose( "Select an example support service by entering a number from the preceding list:", service_choices, ) selected_service = services_list[selected_index] print("-" * 88) return selected_service def display_and_select_category(self, service): """ Lists categories for a support service and prompts the user to select one. :param service: The service of the categories. :return: The selected category. """ print("-" * 88) print( f"Available support categories for Service {service['name']} {len(service['categories'])}:" ) categories_choices = [category["name"] for category in service["categories"]] selected_index = q.choose( "Select an example support category by entering a number from the preceding list:", categories_choices, ) selected_category = service["categories"][selected_index] print("-" * 88) return selected_category def display_and_select_severity(self): """ Lists available severity levels and prompts the user to select one. :return: The selected severity level. """ print("-" * 88) severity_levels_list = self.support_wrapper.describe_severity_levels("en") print(f"Available severity levels:") severity_choices = [level["name"] for level in severity_levels_list] selected_index = q.choose( "Select an example severity level by entering a number from the preceding list:", severity_choices, ) selected_severity = severity_levels_list[selected_index] print("-" * 88) return selected_severity def create_example_case(self, service, category, severity_level): """ Creates an example support case with the user's selections. :param service: The service for the new case. :param category: The category for the new case. :param severity_level: The severity level for the new case. :return: The caseId of the new support case. """ print("-" * 88) print(f"Creating new case for service {service['name']}.") case_id = self.support_wrapper.create_case(service, category, severity_level) print(f"\tNew case created with ID {case_id}.") print("-" * 88) return case_id def list_open_cases(self): """ List the open cases for the current day. """ print("-" * 88) print("Let's list the open cases for the current day.") start_time = str(datetime.utcnow().date()) end_time = str(datetime.utcnow().date() + timedelta(days=1)) open_cases = self.support_wrapper.describe_cases(start_time, end_time, False) for case in open_cases: print(f"\tCase: {case['caseId']}: status {case['status']}.") print("-" * 88) def create_attachment_set(self): """ Create an attachment set with a sample file. :return: The attachment set ID of the new attachment set. """ print("-" * 88) print("Creating attachment set with a sample file.") attachment_set_id = self.support_wrapper.add_attachment_to_set() print(f"\tNew attachment set created with ID {attachment_set_id}.") print("-" * 88) return attachment_set_id def add_communication(self, case_id, attachment_set_id): """ Add a communication with an attachment set to the case. :param case_id: The ID of the case for the communication. :param attachment_set_id: The ID of the attachment set to add to the communication. """ print("-" * 88) print(f"Adding a communication and attachment set to the case.") self.support_wrapper.add_communication_to_case(attachment_set_id, case_id) print( f"Added a communication and attachment set {attachment_set_id} to the case {case_id}." ) print("-" * 88) def list_communications(self, case_id): """ List the communications associated with a case. :param case_id: The ID of the case. :return: The attachment ID of an attachment. """ print("-" * 88) print("Let's list the communications for our case.") attachment_id = "" communications = self.support_wrapper.describe_all_case_communications(case_id) for communication in communications: print( f"\tCommunication created on {communication['timeCreated']} " f"has {len(communication['attachmentSet'])} attachments." ) if len(communication["attachmentSet"]) > 0: attachment_id = communication["attachmentSet"][0]["attachmentId"] print("-" * 88) return attachment_id def describe_case_attachment(self, attachment_id): """ Describe an attachment associated with a case. :param attachment_id: The ID of the attachment. """ print("-" * 88) print("Let's list the communications for our case.") attached_file = self.support_wrapper.describe_attachment(attachment_id) print(f"\tAttachment includes file {attached_file}.") print("-" * 88) def resolve_case(self, case_id): """ Shows how to resolve an AWS Support case by its ID. :param case_id: The ID of the case to resolve. """ print("-" * 88) print(f"Resolving case with ID {case_id}.") case_status = self.support_wrapper.resolve_case(case_id) print(f"\tFinal case status is {case_status}.") print("-" * 88) def list_resolved_cases(self): """ List the resolved cases for the current day. """ print("-" * 88) print("Let's list the resolved cases for the current day.") start_time = str(datetime.utcnow().date()) end_time = str(datetime.utcnow().date() + timedelta(days=1)) resolved_cases = self.support_wrapper.describe_cases(start_time, end_time, True) for case in resolved_cases: print(f"\tCase: {case['caseId']}: status {case['status']}.") print("-" * 88) def run_scenario(self): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Welcome to the AWS Support get started with support cases demo.") print("-" * 88) selected_service = self.display_and_select_service() selected_category = self.display_and_select_category(selected_service) selected_severity = self.display_and_select_severity() new_case_id = self.create_example_case( selected_service, selected_category, selected_severity ) wait(10) self.list_open_cases() new_attachment_set_id = self.create_attachment_set() self.add_communication(new_case_id, new_attachment_set_id) new_attachment_id = self.list_communications(new_case_id) self.describe_case_attachment(new_attachment_id) self.resolve_case(new_case_id) wait(10) self.list_resolved_cases() print("\nThanks for watching!") print("-" * 88) if __name__ == "__main__": try: scenario = SupportCasesScenario(SupportWrapper.from_client()) scenario.run_scenario() except Exception: logging.exception("Something went wrong with the demo.")

サポートされるクライアントアクションをラップするクラスを定義します。

class SupportWrapper: """Encapsulates Support actions.""" def __init__(self, support_client): """ :param support_client: A Boto3 Support client. """ self.support_client = support_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ support_client = boto3.client("support") return cls(support_client) def describe_services(self, language): """ Get the descriptions of AWS services available for support for a language. :param language: The language for support services. Currently, only "en" (English) and "ja" (Japanese) are supported. :return: The list of AWS service descriptions. """ try: response = self.support_client.describe_services(language=language) services = response["services"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't get Support services for language %s. Here's why: %s: %s", language, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return services def describe_severity_levels(self, language): """ Get the descriptions of available severity levels for support cases for a language. :param language: The language for support severity levels. Currently, only "en" (English) and "ja" (Japanese) are supported. :return: The list of severity levels. """ try: response = self.support_client.describe_severity_levels(language=language) severity_levels = response["severityLevels"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't get severity levels for language %s. Here's why: %s: %s", language, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return severity_levels def create_case(self, service, category, severity): """ Create a new support case. :param service: The service to use for the new case. :param category: The category to use for the new case. :param severity: The severity to use for the new case. :return: The caseId of the new case. """ try: response = self.support_client.create_case( subject="Example case for testing, ignore.", serviceCode=service["code"], severityCode=severity["code"], categoryCode=category["code"], communicationBody="Example support case body.", language="en", issueType="customer-service", ) case_id = response["caseId"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't create case. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return case_id def add_attachment_to_set(self): """ Add an attachment to a set, or create a new attachment set if one does not exist. :return: The attachment set ID. """ try: response = self.support_client.add_attachments_to_set( attachments=[ { "fileName": "attachment_file.txt", "data": b"This is a sample file for attachment to a support case.", } ] ) new_set_id = response["attachmentSetId"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't add attachment. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return new_set_id def add_communication_to_case(self, attachment_set_id, case_id): """ Add a communication and an attachment set to a case. :param attachment_set_id: The ID of an existing attachment set. :param case_id: The ID of the case. """ try: self.support_client.add_communication_to_case( caseId=case_id, communicationBody="This is an example communication added to a support case.", attachmentSetId=attachment_set_id, ) except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't add communication. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def describe_all_case_communications(self, case_id): """ Describe all the communications for a case using a paginator. :param case_id: The ID of the case. :return: The communications for the case. """ try: communications = [] paginator = self.support_client.get_paginator("describe_communications") for page in paginator.paginate(caseId=case_id): communications += page["communications"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't describe communications. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return communications def describe_attachment(self, attachment_id): """ Get information about an attachment by its attachmentID. :param attachment_id: The ID of the attachment. :return: The name of the attached file. """ try: response = self.support_client.describe_attachment( attachmentId=attachment_id ) attached_file = response["attachment"]["fileName"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't get attachment description. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return attached_file def resolve_case(self, case_id): """ Resolve a support case by its caseId. :param case_id: The ID of the case to resolve. :return: The final status of the case. """ try: response = self.support_client.resolve_case(caseId=case_id) final_status = response["finalCaseStatus"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't resolve case. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return final_status def describe_cases(self, after_time, before_time, resolved): """ Describe support cases over a period of time, optionally filtering by status. :param after_time: The start time to include for cases. :param before_time: The end time to include for cases. :param resolved: True to include resolved cases in the results, otherwise results are open cases. :return: The final status of the case. """ try: cases = [] paginator = self.support_client.get_paginator("describe_cases") for page in paginator.paginate( afterTime=after_time, beforeTime=before_time, includeResolvedCases=resolved, language="en", ): cases += page["cases"] except ClientError as err: if err.response["Error"]["Code"] == "SubscriptionRequiredException": logger.info( "You must have a Business, Enterprise On-Ramp, or Enterprise Support " "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these " "examples." ) else: logger.error( "Couldn't describe cases. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: if resolved: cases = filter(lambda case: case["status"] == "resolved", cases) return cases