

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 通过 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：
+ **特定于集成的网络挂钩 — 在配置第三方集成**（例如 Dynatrace、Splunk、Datadog、New Relic 或 Slack）时自动生成。 ServiceNow这些 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 端点 URL 和凭据是在集成设置过程结束时提供的。

**对于通用 Webhook：**

1. 点击**生成 webhook**

1. 系统将生成 HMAC key pair

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 端点将不再接受请求，直到您生成新的凭据。

**重新生成凭证**-要生成新证书，请先删除现有证书，然后生成新的 key pair 或令牌。

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

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

要触发调查，您的外部系统应向 webhook 端点 URL 发送 HTTP POST 请求。

**对于版本 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"
```

## 网络挂钩疑难解答
<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 代理 Web 应用程序？](about-aws-devops-agent-what-is-a-devops-agent-web-app.md)
+ [DevOps 代理 IAM 权限](aws-devops-agent-security-devops-agent-iam-permissions.md)