

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

# 创建测试环境
<a name="getting-started-with-aws-devops-agent-creating-a-test-environment"></a>

本指南提供动手测试，以使用示例架构验证 AWS DevOps 代理的事件响应功能。如果您想在连接生产系统之前测试 DevOps Agent，请使用此补充内容。

## 先决条件
<a name="prerequisites"></a>
+ AWS 具有管理权限的账户
+ AWS DevOps 使用自动创建代理角色流程创建和配置的 DevOps 代理空间

## 成本和安全概述
<a name="cost-and-safety-overview"></a>

### 成本保护
<a name="cost-protection"></a>
+ **EC2 测试**：免费（AWS 免费套餐）或 2 小时约 0.02 美元
+ **Lambda 测试**：免费（100 万 requests/month 免费套餐）
+ **CloudWatch**: 免费（10 个警报，包括基本指标）
+ **预计总成本：完整测试费用**为 0.00-0.05 美元

### 这些测试中的安全功能
<a name="safety-features-in-these-tests"></a>
+ **自动终止**：内置自动关机
+ **符合免费套餐资格**：使用最小的实例类型
+ **范围有限**：极少的隔离测试资源
+ **易于清理**：只需简单的控制台步骤即可删除所有内容
+ **不影响生产**：完全独立的测试环境

## 设置您的 AWS 账户进行测试
<a name="set-up-your-aws-account-for-testing"></a>

**重要**  
**基础设施资源需要部署在您创建 DevOps Agent Space 主云帐户的账户中。 AWS 具体区域无关紧要。

1. 登录 AWS 控制台：[https://console.aws.amazon.com](https://console.aws.amazon.com/)

1. 确保您使用的是 DevOps 代理空间所在的同一个 AWS 账户

1. 您可以将任何区域用作测试资源

**注意**  
 DevOps 代理的主帐户与您正在创建的测试环境资源之间的 1:1 映射简化了测试设置。您可以轻松地将 DevOps 代理空间扩展到包括次要账户，并启用跨账户调查。

## 选择你的测试
<a name="choose-your-test"></a>

你可以单独运行任一测试，也可以同时运行两者兼而有之：

### 测试选项 A：EC2 CPU 容量测试
<a name="test-option-a-ec2-cpu-capacity-test"></a>

**目的**：验证 AWS DevOps 代理检测和调查 EC2 性能问题的能力

**预计时间**：5 分钟设置 \+ 10 分钟自动执行

**难度**：全自动（无需手动步骤）

### 测试选项 B：Lambda 错误率测试
<a name="test-option-b-lambda-error-rate-test"></a>

**目的**：验证 AWS DevOps 代理检测和调查 Lambda 函数错误的能力

**预计时间**：10 分钟设置 \+ 2 分钟触发

**难度**：非常简单

## 测试选项 A：EC2 CPU 容量测试
<a name="test-option-a-ec2-cpu-capacity-test"></a>

### 步骤 1：部署用于 EC2 测试的 CloudFormation 堆栈
<a name="step-1-deploy-cloudformation-stack-for-ec2-test"></a>

我们将使用它 CloudFormation 来创建我们的测试资源，这样 AWS DevOps Agent 就可以正确地跟踪和调查它们。

1. **导航至 CloudFormation**：

   1. 在 AWS 控制台中，搜索 “CloudFormation”，然后单击 **CloudFormation**

   1. 点击**创建堆栈** > **使用新资源（标准）**

1. **上传模板**：

   1. 新建一个名为的本地文件 `AWS-DevOpsAgent-ec2-test.yaml`

   1. 将此 CloudFormation 模板复制并粘贴到文件中：

      1. 

         ```
         AWSTemplateFormatVersion: '2010-09-09'
         Description: 'AWS DevOps Agent EC2 CPU Test Stack'
         Parameters:
           MyIP:
             Type: String
             Description: Your current IP address for SSH access (find at https://whatismyipaddress.com)
             Default: '0.0.0.0/0'
         Resources:
           # Security Group for SSH access
           TestSecurityGroup:
             Type: AWS::EC2::SecurityGroup
             Properties:
               GroupName: AWS-DevOpsAgent-test-sg
               GroupDescription: AWS DevOps Agent beta testing security group
               SecurityGroupIngress:
                 - IpProtocol: tcp
                   FromPort: 22
                   ToPort: 22
                   CidrIp: !Ref MyIP
                   Description: SSH access from your IP
               Tags:
                 - Key: Name
                   Value: AWS-DevOpsAgent-Test-SG
                 - Key: Purpose
                   Value: AWS-DevOpsAgent-Testing
           # Key Pair for SSH access
           TestKeyPair:
             Type: AWS::EC2::KeyPair
             Properties:
               KeyName: AWS-DevOpsAgent-test-key
               KeyType: rsa
               Tags:
                 - Key: Name
                   Value: AWS-DevOpsAgent-Test-Key
                 - Key: Purpose
                   Value: AWS-DevOpsAgent-Testing
           # EC2 Instance for CPU testing
           TestInstance:
             Type: AWS::EC2::Instance
             Properties:
               InstanceType: t3.micro
               ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64}}'
               KeyName: !Ref TestKeyPair
               SecurityGroupIds:
                 - !Ref TestSecurityGroup
               UserData:
                 Fn::Base64: !Sub |
                   #!/bin/bash
                   yum update -y
                   yum install -y htop
                   
                   # Create the CPU stress test script
                   cat > /home/ec2-user/cpu-stress-test.sh << 'EOF'
                   #!/bin/bash
                   echo "Starting AWS DevOpsAgent CPU Stress Test"
                   echo "Time: $(date)"
                   echo "Instance: $(curl -s http://169.254.169.254/latest/meta-data/instance-id)"
                   echo ""
                   
                   # Get number of CPU cores
                   CORES=$(nproc)
                   echo "CPU Cores: $CORES"
                   echo ""
                   
                   echo "Starting stress test (5 minutes)..."
                   echo "This will generate >70% CPU usage to trigger CloudWatch alarm"
                   echo ""
                   
                   # Create CPU load using yes command
                   echo "Starting CPU load processes..."
                   for i in $(seq 1 $CORES); do
                       (yes > /dev/null) &
                       CPU_PID=$!
                       echo "Started CPU load process $i (PID: $CPU_PID)"
                       echo $CPU_PID >> /tmp/cpu_test_pids
                   done
                   
                   # Auto-cleanup after 5 minutes
                   (sleep 300 && echo "Stopping CPU load processes..." && kill $(cat /tmp/cpu_test_pids 2>/dev/null) 2>/dev/null && rm -f /tmp/cpu_test_pids) &
                   
                   echo ""
                   echo "CPU load processes started for 5 minutes"
                   echo "Check CloudWatch for alarm trigger in 3-5 minutes"
                   EOF
                   
                   chmod +x /home/ec2-user/cpu-stress-test.sh
                   chown ec2-user:ec2-user /home/ec2-user/cpu-stress-test.sh
                   
                   # Create auto-shutdown script (safety mechanism)
                   cat > /home/ec2-user/auto-shutdown.sh << 'SHUTDOWN_EOF'
                   #!/bin/bash
                   echo "Auto-shutdown scheduled for 2 hours from now: $(date)"
                   sleep 7200
                   echo "Auto-shutdown executing at: $(date)"
                   sudo shutdown -h now
                   SHUTDOWN_EOF
                   
                   chmod +x /home/ec2-user/auto-shutdown.sh
                   nohup /home/ec2-user/auto-shutdown.sh > /home/ec2-user/auto-shutdown.log 2>&1 &
                   
                   echo "AWS DevOpsAgent test setup completed at $(date)" > /home/ec2-user/setup-complete.txt
               Tags:
                 - Key: Name
                   Value: AWS-DevOpsAgent-Test-Instance
                 - Key: Purpose
                   Value: AWS-DevOpsAgent-Testing
           # CloudWatch Alarm for CPU utilization
           CPUAlarm:
             Type: AWS::CloudWatch::Alarm
             Properties:
               AlarmName: AWS-DevOpsAgent-EC2-CPU-Test
               AlarmDescription: AWS-DevOpsAgent beta test - EC2 CPU utilization alarm
               MetricName: CPUUtilization
               Namespace: AWS/EC2
               Statistic: Average
               Period: 60
               EvaluationPeriods: 1
               Threshold: 70
               ComparisonOperator: GreaterThanThreshold
               Dimensions:
                 - Name: InstanceId
                   Value: !Ref TestInstance
               TreatMissingData: notBreaching
         Outputs:
           InstanceId:
             Description: EC2 Instance ID for testing
             Value: !Ref TestInstance
           
           SecurityGroupId:
             Description: Security Group ID
             Value: !Ref TestSecurityGroup
             
           AlarmName:
             Description: CloudWatch Alarm Name
             Value: !Ref CPUAlarm
             
           SSHCommand:
             Description: SSH command to connect to instance
             Value: !Sub 'ssh -i "AWS-DevOpsAgent-test-key.pem" ec2-user@${TestInstance.PublicDnsName}'
         ```

   1. 在 CloudFormation 控制台中，选择**上传模板文件**

   1. 单击 “**选择文件”**

   1. 选择`AWS-DevOpsAgent-ec2-test.yaml`文件

   1. 单击**下一步**

1. **配置堆栈**：

   1. **堆栈名称**：`AWS-DevOpsAgent-EC2-Test`

   1. **参数：**

      1. **MyIP**：保留为默认值`0.0.0.0/0`（如果需要，你可以稍后保护它）

   1. 单击**下一步**

1. **配置堆栈选项**：

   1. 保留默认值，单击 “**下一步**”

1. **审核和创建**：

   1. 勾选**我确认 AWS CloudFormation 可能会创建 IAM 资源**

   1. 点击**提交**

1. **等待完成**：

   1. 创建堆栈需要 3-5 分钟

   1. 状态将从变`CREATE_IN_PROGRESS`为 `CREATE_COMPLETE`

   1. **重要**：您的 EC2 实例现在是 AWS DevOpsAgent 可以跟踪的 CloudFormation 堆栈的一部分！

#### 可选：安全 SSH 访问（仅当您计划连接到实例时）
<a name="optional-secure-ssh-access-only-if-you-plan-to-connect-to-the-instance"></a>

如果您只想运行自动测试，请跳过此步骤

1. **导航到 EC2 安全组**：

   1. 在 AWS 控制台中，前往 **EC2** → **安全组**

   1. 查找 `AWS-DevOpsAgent-test-sg`

1. **更新 SSH 规则**：

   1. 选择安全组 → **入站规则**选项卡 → **编辑入站规则**

   1. 找到 SSH 规则（端口 22）

   1. 将来源从更改`0.0.0.0/0`为你的 IP：`[YOUR_IP]/32`

   1. 从中获取您的 IP [https://whatismyipaddress.com](https://whatismyipaddress.com/)

   1. 点击**保存规则**

### 步骤 2：等待自动执行测试
<a name="step-2-wait-for-automatic-test-execution"></a>

1. **自动执行测试**：
   + CPU 压力测试将在实例**启动 5 分钟后自动开始**
   + 无需手动干预-只需等待，测试完全在后台运行

1. **监控测试**：
   + 实例会自动启动并准备测试
   + 该脚本将运行 5 分钟并生成 > 70% 的 CPU 使用率
   + CloudWatch 警报应在总计 8-10 分钟内触发（延迟 5 分钟 \+ 警报 3-5 分钟）

1. **可选：手动重新运行**（用于其他测试）：
   + 连接到您的实例：EC2 控制台 → **Connect `AWS-DevOpsAgent-Test-Instance`** → **会话管理器**
   + 再次运行 stress 测试：`./cpu-stress-test.sh`
   + 非常适合多次测试 AWS DevOpsAgent响应

## 测试选项 B：Lambda 错误率测试
<a name="test-option-b-lambda-error-rate-test"></a>

### 步骤 1：为 Lambda 测试部署 CloudFormation 堆栈
<a name="step-1-deploy-cloudformation-stack-for-lambda-test"></a>

1. **导航至 CloudFormation**：

   1. 在 AWS 控制台中，前往 **CloudFormation**

   1. 点击**创建堆栈** → **使用新资源（标准）**

1. **上传模板**：

   1. 新建一个名为的本地文件 `AWS-DevOpsAgent-lambda-test.yaml`

   1. 将此 CloudFormation 模板复制并粘贴到文件中：

      1. 

         ```
         AWSTemplateFormatVersion: '2010-09-09'
         Description: 'AWS DevOpsAgent Lambda Error Test Stack'
         Resources:
           # IAM Role for Lambda function
           LambdaExecutionRole:
             Type: AWS::IAM::Role
             Properties:
               RoleName: AWS-DevOpsAgentLambdaTestRole
               AssumeRolePolicyDocument:
                 Version: '2012-10-17'
                 Statement:
                   - Effect: Allow
                     Principal:
                       Service: lambda.amazonaws.com
                     Action: sts:AssumeRole
               ManagedPolicyArns:
                 - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
               Tags:
                 - Key: Name
                   Value: AWS-DevOpsAgent-Lambda-Test-Role
                 - Key: Purpose
                   Value: AWS-DevOpsAgent-Testing
           # Lambda function that generates errors
           TestLambdaFunction:
             Type: AWS::Lambda::Function
             Properties:
               FunctionName: AWS-DevOpsAgent-test-lambda
               Runtime: python3.12
               Handler: index.lambda_handler
               Role: !GetAtt LambdaExecutionRole.Arn
               Code:
                 ZipFile: |
                   import json
                   import random
                   import time
                   from datetime import datetime
                   def lambda_handler(event, context):
                       print(f"AWS DevOpsAgent Test Lambda - {datetime.now()}")
                       print(f"Event: {json.dumps(event)}")
                       
                       # Intentionally generate errors for testing
                       error_scenarios = [
                           "Simulated database connection timeout",
                           "Test API rate limit exceeded", 
                           "Intentional validation error for AWS DevOpsAgent testing"
                       ]
                       
                       # Always throw an error for testing purposes
                       error_message = random.choice(error_scenarios)
                       print(f"Generating test error: {error_message}")
                       
                       # This will create a Lambda error that CloudWatch will detect
                       raise Exception(f"AWS DevOpsAgent Test Error: {error_message}")
               Description: AWS DevOpsAgent beta test function - intentionally generates errors
               Timeout: 30
               Tags:
                 - Key: Name
                   Value: AWS-DevOpsAgent-Test-Lambda
                 - Key: Purpose
                   Value: AWS-DevOpsAgent-Testing
           # CloudWatch Alarm for Lambda errors
           LambdaErrorAlarm:
             Type: AWS::CloudWatch::Alarm
             Properties:
               AlarmName: AWS-DevOpsAgent-Lambda-Error-Test
               AlarmDescription: AWS-DevOpsAgent beta test - Lambda error rate alarm
               MetricName: Errors
               Namespace: AWS/Lambda
               Statistic: Sum
               Period: 60
               EvaluationPeriods: 1
               Threshold: 0
               ComparisonOperator: GreaterThanThreshold
               Dimensions:
                 - Name: FunctionName
                   Value: !Ref TestLambdaFunction
               TreatMissingData: notBreaching
         Outputs:
           LambdaFunctionName:
             Description: Lambda Function Name for testing
             Value: !Ref TestLambdaFunction
             
           LambdaFunctionArn:
             Description: Lambda Function ARN
             Value: !GetAtt TestLambdaFunction.Arn
             
           AlarmName:
             Description: CloudWatch Alarm Name
             Value: !Ref LambdaErrorAlarm
             
           TestCommand:
             Description: AWS CLI command to test the function
             Value: !Sub 'aws lambda invoke --function-name ${TestLambdaFunction} --payload "{\"test\":\"AWS DevOpsAgent validation\"}" response.json'
         ```

   1. 在 CloudFormation 控制台中，选择**上传模板文件**

   1. 单击 “**选择文件”**

   1. 选择`AWS-DevOpsAgent-lambda-test.yaml`文件

   1. 单击**下一步**

1. **配置堆栈**：

   1. **堆栈名称**：`AWS-DevOpsAgent-Lambda-Test`

   1. 单击**下一步**

1. **配置堆栈选项**：

   1. 保留默认值，单击 “**下一步**”

1. **审核和创建**：

   1. 勾选**我确认 AWS CloudFormation 可能会创建 IAM 资源**

   1. 点击**提交**

1. **等待完成**：

   1. 创建堆栈需要 2-3 分钟

   1. 状态将更改为 `CREATE_COMPLETE`

### 步骤 2：触发 Lambda 错误
<a name="step-2-trigger-lambda-errors"></a>

1. **导航到 Lambda 控制台**：

   1. 前往 **AWS Lambda 控制台**

   1. 找到你的职能 `AWS-DevOpsAgent-test-lambda`

1. **测试函数**：

   1. 单击 “**测试**” 选项卡

   1. 点击**创建新活动**

   1. **活动名称**：`AWS-DevOpsAgent-test-event`

   1. 使用这个 JSON 有效负载：

      1. 

         ```
         {
         "test": "AWS DevOpsAgent validation",
         "timestamp": "2024-01-01T00:00:00Z"
         }
         ```

   1. 单击 “**保存**”

1. **生成错误**：

   1. 单击 “**测试**” 按钮 3 次（每次之间等待 10 秒）

   1. 每次测试都会产生一个故意的错误

   1. **CloudWatch 警报**应在 2-3 分钟内触发

   1. **AWS DevOpsAgent**现在应该能够通过**操作员应用程序中的**调查**来检测警报，接下来你将设置该应用程序**。

## 验证 AWS DevOps 代理检测
<a name="validate-aws-devops-agent-detection"></a>

### 步骤 1：Sanity 检查 CloudWatch 警报（可选）
<a name="step-1-sanity-check-cloudwatch-alarms-optional"></a>

此步骤用于确保上述测试现在处于警报状态。

**对于 EC2 测试：**
+ 在 CloudWatch 控制台中，前往 “**警报**”
+ 开始压力测试后@@ **等待 3-5 分钟**
+ 您的闹钟应显示**为处于警报**状态
+ **如果仍然 “正常”**：再等待 2-3 分钟（CloudWatch 指标可能会延迟）

**对于 Lambda 测试：**
+ 查看`AWS-DevOpsAgent-Lambda-Error-Test`警报
+ 应**在运行测试后的 2-3 分钟内显示警报**

### 步骤 2：开始 AWS DevOps 代理调查
<a name="step-2-start-a-aws-devops-agent-investigation"></a>

1. 打开你的**AWS DevOps 代理 AgentSpace**

1. 单击 “**管理员访问权限**”。这将在新窗口中打开 A DevOps gent Space Web 应用程序

1. 点击屏幕右侧的 “**开始调查**” 按钮

1. 填写以下表格：

   1. **调查详情：**描述你想开展的调查。尽可能提供有关调查目标、要探索的领域或相关信息的所有细节。

   1. **调查起点**：描述您想要开始调查的信息。您可以提及警报、指标、日志片段或其他任何内容，为 DevOps 代理提供工作起点。在这种情况下，请提供您刚刚创建的警报的摘要。

   1. **事件发生日期和时间**（首选 ISO 8601）:: MMZ YYYY-MM-DDTHH

   1. **命名您的调查：**示例：`Oncall_investigation_1:2025-10-27`

   1. AWS 事件的@@ **账户 ID**

   1. 事件发生的地@@ **区**

   1. **优先级**- AWS DevOpsAgent 允许同时进行两次调查。优先级允许您定义调查的执行顺序。

1. 单击 “调查” 启动调查。

1. 点击控制面板中列出的您的调查。您将被带到 “调查详情” 屏幕，您可以在其中查看 DevOps 特工正在采取的详细步骤。

### 预期结果
<a name="expected-results"></a>

#### EC2 测试结果：
<a name="ec2-test-results"></a>
+ 检测 EC2 CPU 警报
+ 确定根本原因：“CPU 压力测试工作负载”
+ 显示时间轴：压力测试 → CPU 峰值 → 警报
+ 提供监控和扩展建议

**Lambda 测试结果：**
+ 检测 Lambda 错误率峰值
+ 确定根本原因：“故意测试异常”
+ 显示时间轴：函数调用 → 错误 → 警报
+ 为错误处理和监控提供建议

## 清理说明
<a name="cleanup-instructions"></a>

### 清理测试 A（EC2 测试）
<a name="cleanup-test-a-ec2-test"></a>

#### 自动清理
<a name="automatic-cleanup"></a>
+ 实例将在 2 小时后自动终止（内置于 CloudFormation 模板中）

#### 手动清理（立即）
<a name="manual-cleanup-immediate"></a>

1. **删除 CloudFormation 堆栈**：

   1. 前往 CloudFormation 控制台

   1. 选择`AWS-DevOpsAgent-EC2-Test`堆栈

   1. 单击 “**删除”**

   1. 确认删除

   1. **这将自动删除所有资源**：EC2 实例、安全组、key pair 和 CloudWatch 警报

### 清理测试 B（Lambda 测试）
<a name="cleanup-test-b-lambda-test"></a>

1. **删除 CloudFormation 堆栈**：

   1. 前往 CloudFormation 控制台

   1. 选择`AWS-DevOpsAgent-Lambda-Test`堆栈

   1. 单击 “**删除”**

   1. 确认删除

   1. **这将自动删除所有资源**：Lambda 函数、IAM 角色和警报 CloudWatch 

## 问题排查
<a name="troubleshooting"></a>

### 常见问题
<a name="common-issues"></a>

#### “无法连接到 EC2 实例”
<a name="cant-connect-to-ec2-instance"></a>
+ **检查安全组**：确保您的 IP 已打开 SSH（端口 22）
+ **检查密钥权限**：运行 `chmod 400 AWS-DevOpsAgent-test-key.pem`
+ **验证公有 IP**：必须为实例分配公有 IP
+ **等待实例**：确保实例处于 “正在运行” 状态

#### “警报未触发”
<a name="alarm-not-triggering"></a>
+ **等待指标**： CloudWatch 指标可能需要 2-5 分钟才能显示
+ **检查 CPU 负载**：通过 SSH 连接到实例并运行`top`以验证 CPU 大于 70%
+ **验证压力测试**：运行`ps aux | grep yes`以查看加载进程是否正在运行
+ **延长等待**：有时首次触发警报最多需要 7-8 分钟

## 测试验证
<a name="test-validation"></a>

在以下情况下，您的 AWS DevOp 代理测试成功：

### 技术验证
<a name="technical-validation"></a>
+ **调查精度**：EC2 测试的结果应正确表明警报是由于 CPU 负载而触发的。Lambda 测试的结果应表明这是故意失败。
+ **时间轴精度**：显示的事件顺序正确
+ **推荐质量**：提供可行的建议