

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

# 使用 AWS Lambda 處理 EventBridge 事件
<a name="using_lambda"></a>

您可以使用 Amazon EBS 和 Amazon EventBridge 自動化您的資料備份工作流程。這需要您建立 IAM 政策、處理事件的 AWS Lambda 函數，以及符合傳入事件並將其路由至 Lambda 函數的 EventBridge 規則。

下列程序使用 `createSnapshot` 事件自動將完成的快照複製到另一個區域，做為災難復原用途。

**將完成的快照複製到另一個區域**

1. 建立 IAM 政策 (如下列範例所示)，以提供執行 `CopySnapshot` 動作和寫入 EventBridge 日誌的許可。將政策指派給處理 EventBridge 事件的使用者。

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Action": [
           "logs:CreateLogGroup",
           "logs:CreateLogStream",
           "logs:PutLogEvents"
         ],
         "Resource": "arn:aws:logs:*:*:*"
       },
       {
         "Effect": "Allow",
         "Action": [
           "ec2:CopySnapshot"
         ],
         "Resource": "*"
       }
     ]
   }
   ```

------

1. 在 Lambda 中定義可從 EventBridge 主控台使用的函數。以下範例 Lambda 函數以 Node.js 撰寫，並會在 Amazon EBS 發出符合的 `createSnapshot` 事件時由 EventBridge 呼叫 (表示快照已完成)。當呼叫時，函數會將快照從 `us-east-2` 複製到 `us-east-1`。

   ```
   // Sample Lambda function to copy an EBS snapshot to a different Region
    
   var AWS = require('aws-sdk');
   var ec2 = new AWS.EC2();
    
   // define variables
   var destinationRegion = 'us-east-1';
   var sourceRegion = 'us-east-2';
   console.log ('Loading function');
    
   //main function
   exports.handler = (event, context, callback) => {
    
       // Get the EBS snapshot ID from the event details
       var snapshotArn = event.detail.snapshot_id.split('/');
       const snapshotId = snapshotArn[1];
       const description = `Snapshot copy from ${snapshotId} in ${sourceRegion}.`;
       console.log ("snapshotId:", snapshotId);
   
       // Load EC2 class and update the configuration to use destination Region to initiate the snapshot.
       AWS.config.update({region: destinationRegion});
       var ec2 = new AWS.EC2();
   
       // Prepare variables for ec2.modifySnapshotAttribute call
       const copySnapshotParams = {
           Description: description,
           DestinationRegion: destinationRegion,
           SourceRegion: sourceRegion,
           SourceSnapshotId: snapshotId
       };
    
       // Execute the copy snapshot and log any errors
       ec2.copySnapshot(copySnapshotParams, (err, data) => {
           if (err) {
               const errorMessage = `Error copying snapshot ${snapshotId} to Region ${destinationRegion}.`;
               console.log(errorMessage);
               console.log(err);
               callback(errorMessage);
           } else {
               const successMessage = `Successfully started copy of snapshot ${snapshotId} to Region ${destinationRegion}.`;
               console.log(successMessage);
               console.log(data);
               callback(null, successMessage);
           }
       });
   };
   ```

   為確保您能夠從 EventBridge 主控台使用 Lambda 函數，請在 EventBridge 事件發生的區域內建立該函數。如需詳細資訊，請參閱《AWS Lambda 開發人員指南》[https://docs.aws.amazon.com/lambda/latest/dg/](https://docs.aws.amazon.com/lambda/latest/dg/)。

1. 前往 [https://console.aws.amazon.com/events/](https://console.aws.amazon.com/events/) 開啟 Amazon EventBridge 主控台。

1. 在導覽窗格中，選擇 **Rules** (規則)，然後選擇 **Create rule** (建立規則)。

1. 對於 **Step 1: Define rule detail** (步驟 1：定義規則詳細資訊)，執行下列動作：

   1. 輸入 **Name** (名稱) 與 **Description** (描述) 的值。

   1. 針對 **Event bus** (事件匯流排)，保持 **default** (預設值)。

   1. 確保 **Enable the rule on the selected event bus (在選取的事件匯流排上啟用規則)** 已開啟。

   1. 對於 **Event type** (事件類型)，選取 **Rule with an event pattern** (具有事件模式的規則)。

   1. 選擇**下一步**。

1. 對於 **Step 2: Build event pattern** (步驟 2：建置事件模式)，執行下列動作：

   1. 在 **Event source** (事件來源) 欄位中，選取 **AWS events or EventBridge partner events** ( 事件或 EventBridge 合作夥伴事件)。

   1. 在**事件模式**區段中，對於**事件來源**，確保已選取 **AWS 服務**，對於 **AWS 服務**，選取 **EC2**。

   1. 對於 **Event type** (事件類型)，選取 **EBS Snapshot Notification** (EBS 快照通知)，選取 **Specific event(s)** (特定事件)，然後選取 **createSnapshot** (建立快照)。

   1. 選取 **Specific result(s)** (特定結果)，然後選取 **succeeded** (成功)。

   1. 選擇**下一步**。

1. 對於 **Step 3: Select targets** (步驟 3：選取目標)，執行下列動作：

   1. 在**目標類型**欄位中，選擇 **AWS 服務**。

   1. 對於 **Select target** (選取目標)，選取 **Lambda function** (Lambda 函數)，並為 **Function** (函數) 選取您先前建立的函數。

   1. 選擇 **Next** (下一步)

1. 對於 **Step 4: Configure tags** (步驟 4：設定標籤)，視需要指定規則的標籤，然後選擇 **Next** (下一步)。

1. 對於 **Step 5: Review and create** (步驟 5：檢閱和建立)，檢閱規則，然後選擇 **Create rule** (建立規則)。

您的規則現在應該會出現在 **Rules (規則)** 標籤上。在上述範例中，EBS 應該會在您下次複製快照時發出所設定的事件。