

# 例: Datadog と Splunk からの通知を統合する
<a name="example_integrating_notifications"></a>

この例では、Datadog と Splunk からの通知を AWS Incident Detection and Response に統合するための詳細な手順を示します。

**Topics**
+ [ステップ 1: APM を Amazon EventBridge のイベントソースとしてセットアップする](#example_integrating_notifications_step1)
+ [ステップ 2: カスタムイベントバスを作成する](#example_integrating_notifications_step2)
+ [ステップ 3: 変換用の AWS Lambda 関数を作成する](#example_integrating_notifications_step3)
+ [ステップ 4: カスタムの Amazon EventBridge ルールを作成する](#example_integrating_notifications_step4)

## ステップ 1: APM を Amazon EventBridge のイベントソースとしてセットアップする
<a name="example_integrating_notifications_step1"></a>

AWS アカウントの Amazon EventBridge で、各 APM をイベントソースとしてセットアップします。APM をイベントソースとして設定する手順については、「[event source set up instructions for your tool in Amazon EventBridge partners](https://console.aws.amazon.com/events/home#/partners)」を参照してください。

APM をイベントソースとして設定することで、APM から AWS アカウントのイベントバスに通知を取り込むことができます。セットアップ後にイベントバスがイベントを受信すると、AWS Incident Detection and Response がインシデント管理プロセスを開始できます。このプロセスにより、Amazon EventBridge が APM の送信先として追加されます。

## ステップ 2: カスタムイベントバスを作成する
<a name="example_integrating_notifications_step2"></a>

カスタムイベントバスを使用するのがベストプラクティスです。AWS Incident Detection and Response は、カスタムイベントバスを使用して、変換されたイベントを取り込みます。AWS Lambda 関数はパートナーイベントバスのイベントを変換し、カスタムイベントバスに送信します。AWS Incident Detection and Response は、カスタムイベントバスからイベントを取り込むためのマネージドルールをインストールします。

カスタムイベントバスの代わりにデフォルトのイベントバスを使用することもできます。AWS Incident Detection and Response では、カスタムイベントバスの代わりに、デフォルトのイベントバスから取り込むようにマネージドルールを変更します。

**AWS アカウントにカスタムイベントバスを作成する方法:**

1. Amazon EventBridge コンソール ([https://console.aws.amazon.com/events/](https://console.aws.amazon.com/events/)) を開きます。

1. **[バス]**、**[イベントバス]** の順に選択します。

1. **[カスタムイベントバス]** で、**[作成]** を選択します。

1. **[名前]** でイベントバスの名前を指定します。推奨される形式は、**[APMName-AWSIncidentDetectionResponse-EventBus]** です。

   例として、Datadog または Splunk を使用する場合は、次のいずれかを使用します。
   + **[Datadog]**: Datadog-AWSIncidentDetectionResponse-EventBus
   + **[Splunk]**: Splunk-AWSIncidentDetectionResponse-EventBus

## ステップ 3: 変換用の AWS Lambda 関数を作成する
<a name="example_integrating_notifications_step3"></a>

Lambda 関数は、ステップ 1 のパートナーイベントバスとステップ 2 のカスタム (またはデフォルト) イベントバスの間でイベントを変換します。Lambda 関数による変換は、AWS Incident Detection and Response マネージドルールと一致します。

**AWS アカウントに AWS Lambda 関数を作成する**

1. AWS Lambda コンソールの [[Functions](https://console.aws.amazon.com/lambda/home#/functions)] (関数) ページを開きます。

1. [**関数の作成**] を選択してください。

1. **[一から作成]** タブを選択します。

1. **[関数名]** には、`APMName-AWSIncidentDetectionResponse-LambdaFunction` の形式を使って名前を入力します。

   Datadog と Splunk の例を次に示します。
   + **[Datadog]**: Datadog-AWSIncidentDetectionResponse-LambdaFunction
   + **[Splunk]**: Splunk-AWSIncidentDetectionResponse-LambdaFunction

1. **[ランタイム]** には、「**Python 3.10**」と入力します。

1. 残りのフィールドはデフォルト値のままにします。[**関数の作成**] を選択してください。

1. **[コード編集]** ページで、デフォルトの Lambda 関数コンテンツを次のコード例の関数に置き換えます。

   次のコード例の \$1 で始まるコメントに注意してください。これらのコメントは、変更する値を示します。

   **Datadog 変換コードテンプレート**:

   ```
   import logging
   import json
   import boto3
   
   logger = logging.getLogger()
   logger.setLevel(logging.INFO)
   
   # Change the EventBusName to the custom event bus name you created previously or use your default event bus which is called 'default'.
   # Example 'Datadog-AWSIncidentDetectionResponse-EventBus'
   EventBusName = "Datadog-AWSIncidentDetectionResponse-EventBus" 
   
   def lambda_handler(event, context):
       # Set the event["detail"]["incident-detection-response-identifier"] value to the name of your alert that is coming from your APM. Each APM is different and each unique alert will have a different name. 
       # Replace the dictionary path, event["detail"]["meta"]["monitor"]["name"], with the path to your alert name based on your APM payload. 
       # This example is for finding the alert name for Datadog.
       event["detail"]["incident-detection-response-identifier"] = event["detail"]["meta"]["monitor"]["name"] 
       logger.info(f"We got: {json.dumps(event, indent=2)}")
       
       client = boto3.client('events')
       response = client.put_events(
        Entries=[
                 {
                  'Detail': json.dumps(event["detail"], indent=2),
                  'DetailType': 'ams.monitoring/generic-apm', # Do not modify. This DetailType value is required.
                  'Source': 'GenericAPMEvent', # Do not modify. This Source value is required.
                  'EventBusName': EventBusName # Do not modify. This variable is set at the top of this code as a global variable. Change the variable value for your eventbus name at the top of this code.    
                }
        ]
       )
       print(response['Entries'])
   ```

   **Splunk 変換コードテンプレート**:

   ```
   import logging
   import json
   import boto3
   
   logger = logging.getLogger()
   logger.setLevel(logging.INFO)
   
   # Change the EventBusName to the custom event bus name you created previously or use your default event bus which is called 'default'. 
   # Example Splunk-AWSIncidentDetectionResponse-EventBus
   EventBusName = "Splunk-AWSIncidentDetectionResponse-EventBus" 
   
   def lambda_handler(event, context):
       # Set the event["detail"]["incident-detection-response-identifier"] value to the name of your alert that is coming from your APM. Each APM is different and each unique alert will have a different name. 
       # replace the dictionary path event["detail"]["ruleName"] with the path to your alert name based on your APM payload. 
       # This example is for finding the alert name in Splunk.
       event["detail"]["incident-detection-response-identifier"] = event["detail"]["ruleName"]
       logger.info(f"We got: {json.dumps(event, indent=2)}")
       
       client = boto3.client('events')
       response = client.put_events(
       Entries=[
                {
                 'Detail': json.dumps(event["detail"], indent=2),
                 'DetailType': 'ams.monitoring/generic-apm', # Do not modify. This DetailType value is required.
                 'Source': 'GenericAPMEvent', # Do not modify. This Source value is required.
                 'EventBusName': EventBusName # Do not modify. This variable is set at the top of this code as a global variable. Change the variable value for your eventbus name at the top of this code. 
               }
           ]
       )
       print(response['Entries'])
   ```

1. **[デプロイ]** をクリックします。

1. 変換されたデータの送信先となるイベントバスの Lambda 実行ロールに **[PutEvents]** のアクセス許可を追加します。

   1. AWS Lambda コンソールの [[Functions](https://console.aws.amazon.com/lambda/home#/functions)] (関数) ページを開きます。

   1. 関数を選択してから、**[設定]** タブで **[アクセス許可]** を選択します。

   1. **[実行ロール]** で **[ロール名]** を選択して、AWS Identity and Access Management コンソールで実行ロールを開きます。

   1. **[アクセス許可ポリシー]** で、既存のポリシー名を選択してポリシーを開きます。

   1. **[このポリシーで定義されている許可]** で、**[編集]** を選択します。

   1. **[ポリシーエディタ]** ページで、**[新しいステートメントを追加]** を選択します。

   1. **[ポリシーエディタ]** により、次のような新しい空白のステートメントが追加されます。  
![\[IAM コンソールの JSON ポリシーエディタのスクリーンショット。\]](http://docs.aws.amazon.com/ja_jp/IDR/latest/userguide/images/iam-add-new-statement.png)

   1. 自動生成された新しいステートメントを以下に置き換えます。

      ```
      {
        "Sid": "AWSIncidentDetectionResponseEventBus0",
        "Effect": "Allow",
        "Action": "events:PutEvents",
        "Resource": "arn:aws:events:{region}:{accountId}:event-bus/{custom-eventbus-name}"
      }
      ```

   1. **[リソース]** は、[ステップ 2: カスタムイベントバスを作成する](#example_integrating_notifications_step2) で作成したカスタムイベントバスの ARN、または Lambda コードでデフォルトのイベントバスを使用している場合はデフォルトのイベントバスの ARN です。

1. 必要なアクセス許可がロールに追加されていることを確認します。

1. **[この新しいバージョンをデフォルトとして設定]** を選択し、**[変更を保存]** を選択します。

**ペイロード変換には何が必要ですか?**

AWS Incident Detection and Response によって取り込まれるイベントバスのイベントには、次の JSON キーと値のペアが必要です。

```
{
    "detail-type": "ams.monitoring/generic-apm",
    "source": "GenericAPMEvent"
    "detail" : {
        "incident-detection-response-identifier": "Your alarm name from your APM",
    }
}
```

次の例は、変換前と変換後のパートナーイベントバスからのイベントを示しています。

```
{
    "version": "0",
    "id": "a6150a80-601d-be41-1a1f-2c5527a99199",
    "detail-type": "Datadog Alert Notification",
    "source": "aws.partner/datadog.com/Datadog-aaa111bbbc",
    "account": "123456789012",
    "time": "2023-10-25T14:42:25Z",
    "region": "us-east-1",
    "resources": [],
    "detail": {
      "alert_type": "error",
      "event_type": "query_alert_monitor",
      "meta": {
        "monitor": {
          "id": 222222,
          "org_id": 3333333333,
          "type": "query alert",
          "name": "UnHealthyHostCount",
          "message": "@awseventbridge-Datadog-aaa111bbbc",
          "query": "max(last_5m):avg:aws.applicationelb.un_healthy_host_count{aws_account:123456789012} \u003c\u003d 1",
          "created_at": 1686884769000,
          "modified": 1698244915000,
          "options": {
            "thresholds": {
              "critical": 1.0
            }
          },
        },
        "result": {
          "result_id": 7281010972796602670,
          "result_ts": 1698244878,
          "evaluation_ts": 1698244868,
          "scheduled_ts": 1698244938,
          "metadata": {   
            "monitor_id": 222222,
            "metric": "aws.applicationelb.un_healthy_host_count"
          }
        },
        "transition": {
          "trans_name": "Triggered",
          "trans_type": "alert"
        },
        "states": {
          "source_state": "OK",
          "dest_state": "Alert"
        },
        "duration": 0
      },
      "priority": "normal",
      "source_type_name": "Monitor Alert",
      "tags": [
        "aws_account:123456789012",
        "monitor"
      ]
    }
}
```

イベントが変換される前は、`detail-type` はアラートが発生した APM、ソースはパートナー APM、そして `incident-detection-response-identifier` キーが存在していないことに注意してください。

Lambda 関数は上記のイベントを変換し、ターゲットのカスタムイベントバスまたはデフォルトのイベントバスに配置します。変換されたペイロードに、必要なキーと値のペアが含まれるようになりました。

```
{
    "version": "0",
    "id": "7f5e0fc1-e917-2b5d-a299-50f4735f1283",
    "detail-type": "ams.monitoring/generic-apm",
    "source": "GenericAPMEvent",
    "account": "123456789012",
    "time": "2023-10-25T14:42:25Z",
    "region": "us-east-1",
    "resources": [],
    "detail": {
      "incident-detection-response-identifier": "UnHealthyHostCount",
      "alert_type": "error",
      "event_type": "query_alert_monitor",
      "meta": {
        "monitor": {
          "id": 222222,
          "org_id": 3333333333,
          "type": "query alert",
          "name": "UnHealthyHostCount",
          "message": "@awseventbridge-Datadog-aaa111bbbc",
          "query": "max(last_5m):avg:aws.applicationelb.un_healthy_host_count{aws_account:123456789012} \u003c\u003d 1",
          "created_at": 1686884769000,
          "modified": 1698244915000,
          "options": {
            "thresholds": {
              "critical": 1.0
            }
          },
        },
        "result": {
          "result_id": 7281010972796602670,
          "result_ts": 1698244878,
          "evaluation_ts": 1698244868,
          "scheduled_ts": 1698244938,
          "metadata": {
            "monitor_id": 222222,
            "metric": "aws.applicationelb.un_healthy_host_count"
          }
        },
        "transition": {
          "trans_name": "Triggered",
          "trans_type": "alert"
        },
        "states": {
          "source_state": "OK",
          "dest_state": "Alert"
        },
        "duration": 0
      },
      "priority": "normal",
      "source_type_name": "Monitor Alert",
      "tags": [
        "aws_account:123456789012",
        "monitor"
      ]
    }
}
```

`detail-type` は `ams.monitoring/generic-apm`、ソースは `GenericAPMEvent` になり、詳細には新しいキーと値のペアである `incident-detection-response-identifier` が存在するようになりました。

 前の例では、`incident-detection-response-identifier` 値はパス `$.detail.meta.monitor.name` の下のアラート名から取得されています。APM アラート名のパスは、APM ごとに異なります。Lambda 関数を変更して、正しいパートナーイベント JSON パスからアラーム名を取得し、`incident-detection-response-identifier` 値に使用する必要があります。

`incident-detection-response-identifier` で設定される一意の名前はそれぞれ、オンボーディング中に AWS Incident Detection and Response チームに提供されます。`incident-detection-response-identifier` の名前が不明なイベントは処理されません。

## ステップ 4: カスタムの Amazon EventBridge ルールを作成する
<a name="example_integrating_notifications_step4"></a>

ステップ 1 で作成したパートナーイベントバスには、お客様が作成する EventBridge ルールが必要です。このルールは、パートナーイベントバスから、ステップ 3 で作成した Lambda 関数に目的のイベントを送信します。

EventBridge ルールの定義に関するガイドラインについては、「[Amazon EventBridge ルール](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html)」を参照してください。

1. Amazon EventBridge コンソール ([https://console.aws.amazon.com/events/](https://console.aws.amazon.com/events/)) を開きます。

1. **[ルール]** を選択し、APM に関連付けられたパートナーイベントバスを選択します。パートナーイベントバスの例を次に示します。
   + **[Datadog]:** aws.partner/datadog.com/eventbus-name
   + **[Splunk]:** aws.partner/signalfx.com/RandomString

1. **[ルールを作成]** を選択して、新しい EventBridge ルールを作成します。

1. ルール名には、次の形式 `APMName-AWS Incident Detection and Response-EventBridgeRule` で名前を入力し、**[次へ]** を選択します。以下は名前の例です。
   + **[Datadog]:** Datadog-AWSIncidentDetectionResponse-EventBridgeRule
   + **[Splunk]:** Splunk-AWSIncidentDetectionResponse-EventBridgeRule

1. **[イベントソース]** で、**[AWS イベントまたは EventBridge パートナーイベント]** を選択します。

1. **[サンプルイベント]** と **[作成方法]** をデフォルト値のままにします。

1. **[イベントパターン]** の場合は、次のいずれかを実行します。

   1. **[イベントソース]:** EventBridge パートナー。

   1. **[パートナー]:** APM パートナーを選択します。

   1. **[イベントタイプ]:** すべてのイベント。

   イベントパターンの例を次に示します。

   **Datadog イベントパターンの例**  
![\[Datadog イベントパターンの例。\]](http://docs.aws.amazon.com/ja_jp/IDR/latest/userguide/images/datadog-event-pattern.png)

   **Splunk イベントパターンの例**  
![\[Splunk イベントパターンの例。\]](http://docs.aws.amazon.com/ja_jp/IDR/latest/userguide/images/splunk-event-pattern.png)

1. **[ターゲット]** で、以下を選択します。

   1. **[ターゲットタイプ]:** AWS サービス

   1. **[ターゲットを選択]:** Lambda 関数を選択します。

   1. **[関数]:** ステップ 2 で作成した Lambda 関数の名前。

1. **[次へ]**、**[ルールを保存]** の順に選択します。