

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 透過 Webhook 叫用 DevOps 代理程式
<a name="configuring-capabilities-for-aws-devops-agent-invoking-devops-agent-through-webhook"></a>

Webhook 可讓外部系統自動觸發 AWS DevOps 代理程式調查。這可整合票證系統、監控工具，以及可在事件發生時傳送 HTTP 請求的其他平台。

## 先決條件
<a name="prerequisites"></a>

在設定 Webhook 存取之前，請確定您有：
+ 在 AWS DevOps 代理程式中設定的代理程式空間
+ 存取 AWS DevOps 代理程式主控台
+ 將傳送 Webhook 請求的外部系統

## Webhook 類型
<a name="webhook-types"></a>

AWS DevOps 代理程式支援下列類型的 Webhook：
+ **整合特定的 Webhook** – 當您設定第三方整合時自動產生，例如 Dynatrace、Splunk、Datadog、New Relic、ServiceNow 或 Slack。這些 Webhook 與特定整合相關聯，並使用整合類型決定的身分驗證方法
+ **一般 Webhook** – 可以手動建立，以觸發來自特定整合未涵蓋之任何來源的調查。一般 Webhook 目前使用 **HMAC** 身分驗證 （目前無法使用承載字符）。
+ **Grafana 提醒 Webhook** – Grafana 可以透過 Webhook 聯絡點將提醒通知直接傳送至 AWS DevOps 代理程式。如需包含自訂通知範本的設定說明，請參閱[連接 Grafana](connecting-telemetry-sources-connecting-grafana.md)。

## Webhook 身分驗證方法
<a name="webhook-authentication-methods"></a>

Webhook 的身分驗證方法取決於其與哪個整合相關聯：

**HMAC 身分驗證** – 用於：
+ Dynatrace 整合 Webhook
+ 一般 Webhook （未連結至特定的第三方整合）

**承載字符身分驗證** – 用於：
+ Splunk 整合 Webhook
+ Datadog 整合 Webhook
+ 新的 Relic 整合 Webhook
+ ServiceNow 整合 Webhook
+ Slack 整合 Webhook

## 設定 Webhook 存取
<a name="configuring-webhook-access"></a>

### 步驟 1：導覽至 Webhook 組態
<a name="step-1-navigate-to-the-webhook-configuration"></a>

1. 登入 AWS 管理主控台並導覽至 AWS DevOps 代理程式主控台

1. 選取您的客服人員空間

1. 前往**功能**索引標籤

1. 在 **Webhook** 區段中，按一下**設定**

### 步驟 2：產生 Webhook 登入資料
<a name="step-2-generate-webhook-credentials"></a>

**對於整合特定的 Webhook：**

當您完成第三方整合的組態時，Webhook 會自動產生。Webhook 端點 URL 和登入資料會在整合設定程序結束時提供。

**對於一般 Webhook：**

1. 按一下**產生 Webhook**

1. 系統會產生 HMAC 金鑰對

1. 安全地存放產生的金鑰和秘密 - 您將無法再次擷取它們

1. 複製提供的 Webhook 端點 URL

### 步驟 3：設定外部系統
<a name="step-3-configure-your-external-system"></a>

使用 Webhook 端點 URL 和登入資料，將外部系統設定為將請求傳送至 AWS DevOps 代理程式。特定組態步驟取決於您的外部系統。

## 管理 Webhook 登入資料
<a name="managing-webhook-credentials"></a>

**移除登入**資料 – 若要刪除 Webhook 登入資料，請前往 Webhook 組態區段，然後按一下**移除**。移除登入資料後，Webhook 端點將不再接受請求，直到您產生新的登入資料為止。

**重新產生登入**資料 – 若要產生新的登入資料，請先移除現有的登入資料，然後產生新的金鑰對或字符。

## 使用 Webhook
<a name="using-the-webhook"></a>

### Webhook 請求格式
<a name="webhook-request-format"></a>

若要觸發調查，您的外部系統應將 HTTP POST 請求傳送至 Webhook 端點 URL。

**對於第 1 版 (HMAC 身分驗證）：**

標頭：
+ `Content-Type: application/json`
+ `x-amzn-event-signature: <HMAC signature>`
+ `x-amzn-event-timestamp: <+%Y-%m-%dT%H:%M:%S.000Z>`

HMAC 簽章是透過使用 SHA-256 使用您的私密金鑰簽署請求內文來產生。

**對於第 2 版 （承載字符身分驗證）：**

標頭：
+ `Content-Type: application/json`
+ `Authorization: Bearer <your-token>`

**請求內文：**

請求內文應包含事件的相關資訊：

```
json

{
  "title": "Incident title",
  "severity": "high",
  "affectedResources": ["resource-id-1", "resource-id-2"],
  "timestamp": "2025-11-23T18:00:00Z",
  "description": "Detailed incident description",
  "data": {
    "metadata": {
        "region": "us-east-1",
        "environment": "production"
    }
  }
}
```

### 範例程式碼
<a name="example-code"></a>

**第 1 版 (HMAC 身分驗證） - JavaScript：**

```
const crypto = require('crypto');

// Webhook configuration
const webhookUrl = 'https://your-webhook-endpoint.amazonaws.com/invoke';
const webhookSecret = 'your-webhook-secret-key';

// Incident data
const incidentData = {  
    eventType: 'incident',
    incidentId: 'incident-123',
    action: 'created',
    priority: "HIGH",
    title: 'High CPU usage on production server',
    description: 'High CPU usage on production server host ABC in AWS account 1234 region us-east-1',
    timestamp: new Date().toISOString(),
    service: 'MyTestService',
    data: {
      metadata: {
        region: 'us-east-1',
        environment: 'production'
      }
    }
};

// Convert data to JSON string
const payload = JSON.stringify(incidentData);
const timestamp = new Date().toISOString();
const hmac = crypto.createHmac("sha256", webhookSecret);
hmac.update(`${timestamp}:${payload}`, "utf8");
const signature = hmac.digest("base64");

// Send the request
fetch(webhookUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-amzn-event-timestamp': timestamp,
    'x-amzn-event-signature': signature
  },
  body: payload
})
.then(res => {
  console.log(`Status Code: ${res.status}`);
  return res.text();
})
.then(data => {
  console.log('Response:', data);
})
.catch(error => {
  console.error('Error:', error);
});
```

**第 1 版 (HMAC 身分驗證） - cURL：**

```
#!/bin/bash

# Configuration
WEBHOOK_URL="https://event-ai.us-east-1.api.aws/webhook/generic/YOUR_WEBHOOK_ID"
SECRET="YOUR_WEBHOOK_SECRET"

# Create payload
TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%S.000Z)
INCIDENT_ID="test-alert-$(date +%s)"

PAYLOAD=$(cat <<EOF
{
"eventType": "incident",
"incidentId": "$INCIDENT_ID",
"action": "created",
"priority": "HIGH",
"title": "Test Alert",
"description": "Test alert description",
"service": "TestService",
"timestamp": "$TIMESTAMP"
}
EOF
)

# Generate HMAC signature
SIGNATURE=$(echo -n "${TIMESTAMP}:${PAYLOAD}" | openssl dgst -sha256 -hmac "$SECRET" -binary | base64)

# Send webhook
curl -X POST "$WEBHOOK_URL" \
-H "Content-Type: application/json" \
-H "x-amzn-event-timestamp: $TIMESTAMP" \
-H "x-amzn-event-signature: $SIGNATURE" \
-d "$PAYLOAD"
```

**第 2 版 （承載字符身分驗證） - JavaScript：**

```
function sendEventToWebhook(webhookUrl, secret) {
  const timestamp = new Date().toISOString();
  
  const payload = {
    eventType: 'incident',
    incidentId: 'incident-123',
    action: 'created',
    priority: "HIGH",
    title: 'Test Alert',
    description: 'Test description',
    timestamp: timestamp,
    service: 'TestService',
    data: {}
  };

  fetch(webhookUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-amzn-event-timestamp": timestamp,
      "Authorization": `Bearer ${secret}`,  // Fixed: template literal
    },
    body: JSON.stringify(payload),
  });
}
```

**第 2 版 （承載字符身分驗證） - cURL：**

```
#!/bin/bash

# Configuration
WEBHOOK_URL="https://event-ai.us-east-1.api.aws/webhook/generic/YOUR_WEBHOOK_ID"
SECRET="YOUR_WEBHOOK_SECRET"

# Create payload
TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%S.000Z)
INCIDENT_ID="test-alert-$(date +%s)"

PAYLOAD=$(cat <<EOF
{
"eventType": "incident",
"incidentId": "$INCIDENT_ID",
"action": "created",
"priority": "HIGH",
"title": "Test Alert",
"description": "Test alert description",
"service": "TestService",
"timestamp": "$TIMESTAMP"
}
EOF
)

# Send webhook
curl -X POST "$WEBHOOK_URL" \
-H "Content-Type: application/json" \
-H "x-amzn-event-timestamp: $TIMESTAMP" \
-H "Authorization: Bearer $SECRET" \
-d "$PAYLOAD"
```

## 故障診斷 Webhook
<a name="troubleshooting-webhooks"></a>

### 如果您沒有收到 200
<a name="if-you-do-not-receive-a-200"></a>

收到 200 和 Webhook 等訊息表示已通過身分驗證，且訊息已排入佇列，供系統驗證和處理。如果您沒有得到 200，但 4xx 很可能存在身分驗證或標頭錯誤。嘗試使用 curl 選項手動傳送，以協助偵錯身分驗證。

### 如果您收到 200，但調查未開始
<a name="if-you-receive-a-200-but-an-investigation-does-not-start"></a>

可能的原因是承載格式錯誤。

1. 檢查時間戳記和事件 ID 是否已更新且是唯一的。重複的訊息會刪除重複訊息。

1. 檢查訊息是否為有效的 JSON

1. 檢查格式是否正確

### 如果您收到 200 且調查立即取消
<a name="if-you-receive-a-200-and-investigation-is-immediately-cancelled"></a>

您很可能已達到當月的限制。如果適用，請與您的 AWS 聯絡人討論，要求變更費率限制。

## 相關主題
<a name="related-topics"></a>
+ [建立 代理程式空間](getting-started-with-aws-devops-agent-creating-an-agent-space.md)
+ [什麼是 DevOps Agent Web 應用程式？](about-aws-devops-agent-what-is-a-devops-agent-web-app.md)
+ [DevOps Agent IAM 許可](aws-devops-agent-security-devops-agent-iam-permissions.md)