

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

# 入門：建立 Amazon EventBridge 管道
<a name="pipes-get-started"></a>

為了熟悉管道及其功能，我們將使用 CloudFormation 範本來設定 EventBridge 管道和相關聯的元件。然後，我們可以探索各種管道功能。

**提示**  
如需更全面的實作學習體驗，請嘗試 [EventBridge 管道研討會](https://catalog.workshops.aws/eb-pipes)。此互動式研討會會逐步引導您建置管道並進行故障診斷，以 Lambda 擴充將 DynamoDB 連線至 API Gateway。

範本會建立 EventBridge 管道，將串流從 DynamoDB 資料表連線至 Amazon SQS 佇列。每次在資料庫資料表中建立或修改記錄時，管道都會將產生的事件傳送至佇列。

部署的管道包含：
+ 做為管道來源的 DynamoDB 資料表 （和串流），以及做為目標的 Amazon SQS 佇列。
+ 授予 EventBridge 存取 DynamoDB 資料表和 Amazon SQS 佇列必要許可的執行角色。
+ 管道本身，其中包含事件篩選條件，只會選取建立 （插入） 或修改資料表項目時產生的事件。

如需範本的特定技術詳細資訊，請參閱 [範本詳細資訊](#pipes-get-started-template-details)。

![\[資料庫事件會比對至篩選條件，並在相符時傳送至佇列。\]](http://docs.aws.amazon.com/zh_tw/eventbridge/latest/userguide/images/pipes-get-started_eventbridge_architectural.svg)


## 使用 CloudFormation 建立管道
<a name="pipes-get-started-create"></a>

若要建立管道及其相關資源，我們將建立 CloudFormation 範本，並使用它來建立包含範例管道的堆疊，並完整包含來源和目標。

**重要**  
如果您從此範本建立堆疊，則會向您收取所使用的 Amazon 資源費用。

### 建立範本
<a name="pipes-get-started-file"></a>

首先，建立 CloudFormation 範本。

1. 在 [範本](#pipes-get-started-template) 區段中，按一下 **JSON** 或 **YAML** 索引標籤上的複製圖示，以複製範本內容。

1. 在新檔案中貼上範本內容。

1. 在本機儲存檔案。

### 建立 堆疊
<a name="pipes-get-started-stack"></a>

接下來，使用剛儲存的範本來佈建 CloudFormation 堆疊。

1. 開啟位在 [https://console.aws.amazon.com/cloudformation/](https://console.aws.amazon.com/cloudformation/) 的 CloudFormation​ 主控台。

1. 在**堆疊**頁面上，從**建立堆疊**功能表中選擇**使用新資源 (標準)**。

1. 指定範本：

   1. 在**必要條件**下，選擇**選擇現有範本**。

   1. 在**指定範本**下，選擇**上傳範本檔案**。

   1. 選擇**選擇檔案**，導覽至範本檔案並選取它。

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

1. 指定堆疊詳細資訊：

   1. 輸入堆疊名稱。

   1. 對於參數，請接受預設值或輸入您自己的值。

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

1. 設定堆疊選項：

   1. 在**堆疊失敗選項**下，選擇**刪除所有新建立的資源**。
**注意**  
選擇此選項可避免堆疊建立失敗時，因資源刪除政策指定為保留而可能產生的資源費用。如需詳細資訊，請參閱 *CloudFormation 使用者指南*中的 [`DeletionPolicy` 屬性](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html)。

   1. 接受所有其他預設值。

   1. 在**功能**下，勾選方塊以確認 CloudFormation 可能會在帳戶中建立 IAM 資源。

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

1. 檢閱堆疊詳細資訊，然後選擇**提交**。

**使用 CloudFormation 建立堆疊 (AWS CLI)**

您也可以使用 AWS CLI 來建立堆疊。
+ 使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html) 命令。
  + 接受預設範本參數值，指定堆疊名稱。使用 `template-body` 參數傳遞範本內容，或`template-url`指定 URL 位置。

    ```
    aws cloudformation create-stack \
      --stack-name eventbridge-rule-tutorial \
      --template-body template-contents \
      --capabilities CAPABILITY_IAM
    ```
  + 覆寫一或多個範本參數的預設值 (s)。例如：

    ```
    aws cloudformation create-stack \
      --stack-name eventbridge-rule-tutorial \
      --template-body template-contents \
      --parameters \
        ParameterKey=SourceTableName,ParameterValue=pipe-example-source \
        ParameterKey=TargetQueueName,ParameterValue=pipe-example-target \
        ParameterKey=PipeName,ParameterValue=pipe-with-filtering-example \
      --capabilities CAPABILITY_IAM
    ```

CloudFormation 會建立堆疊。堆疊建立完成後，堆疊資源即可使用。您可以使用堆疊詳細資訊頁面上**的資源**索引標籤來檢視帳戶中佈建的資源。

## 探索管道功能
<a name="pipes-get-started-using"></a>

建立管道之後，您可以使用 EventBridge 主控台來觀察管道操作和測試事件交付。

1. 開啟位於 https：//[https://console.aws.amazon.com/events/home?\$1/pipes](https://console.aws.amazon.com/events/home?#/pipes) 的 EventBridge 主控台。

1. 選擇您建立的管道。

   在管道詳細資訊頁面上，**管道元件**區段會顯示構成管道的資源，並包含提供每個元件詳細資訊的索引標籤。  
![\[管道詳細資訊頁面以圖形方式顯示管道的來源、篩選條件和目標元件。\]](http://docs.aws.amazon.com/zh_tw/eventbridge/latest/userguide/images/pipes-get-started_eventbridge_pipe-detail.png)

   您可以在**設定**索引標籤的**許可**區段中找到我們為管道建立的執行角色。

### 檢查管道篩選條件
<a name="pipes-get-started-using-filter"></a>

在我們測試管道操作之前，讓我們來檢查我們指定的篩選條件，以控制哪些事件會傳送到目標。管道只會將符合篩選條件的事件傳送至目標；所有其他事件都會遭到捨棄。在這種情況下，我們只希望在建立或修改資料表項目時產生的事件傳送到 Amazon SQS 佇列。
+ 在管道詳細資訊頁面的**管道元件**下，選擇**篩選**索引標籤。

  我們包含的篩選條件只會選取 `eventName` 設定為 `INSERT`或 的事件`MODIFY`。

  ```
  {
    "eventName": ["INSERT", "MODIFY"]
  }
  ```

### 透過管道傳送事件
<a name="pipes-get-started-using-source"></a>

接下來，我們將在管道來源中產生事件，以測試管道篩選和交付是否正常運作。若要這樣做，我們會在指定為管道來源的 DynamoDB 資料表中建立和編輯項目。

1. 在管道詳細資訊頁面的**管道元件**下，選擇**來源**索引標籤。

1. 在**來源**下，選擇 DynamoDB 串流名稱。

   這會在單獨的視窗中開啟 DynamoDB 主控台，並顯示來源資料表詳細資訊。

1. 選擇**探索項目**。

1. 透過在 資料表中建立項目來產生`INSERT`事件：

   1. 選擇 **Create item** (建立項目)。

   1. 新增**專輯**和**藝術家**屬性的值。

   1. 選擇 **Create item** (建立項目)。

1. 透過編輯項目產生 `DELETE`和 `INSERT`事件：

   1. 從清單中選擇項目，然後從**動作**功能表中選擇**編輯項目**。

   1. 輸入 **Album** 或 **Artist** 屬性的新值。

   1. 勾選確認您要變更項目索引鍵值的方塊，然後選擇**重新建立項目**。

      這會導致項目遭到刪除，然後重新建立、產生`DELETE`事件，然後是新的`INSERT`事件。

1. 透過將 屬性新增至項目來產生`MODIFY`事件：

   1. 從清單中選擇項目，然後從**動作**功能表中選擇**編輯項目**。

   1. 從**新增屬性**功能表中，選擇**數字**。

   1. 針對屬性名稱，輸入**年份**，然後輸入屬性的值。選擇**儲存與關閉**。

### 透過管道確認事件交付
<a name="pipes-get-started-using-target"></a>

最後，我們將確認管道已成功篩選並交付我們在 DynamoDB 中建立和編輯資料表項目所產生的事件。

1. 在管道詳細資訊頁面的**管道元件**下，選擇**目標**索引標籤。

1. 在**目標**下，選擇 Amazon SQS 佇列名稱。

   這會在單獨的視窗中開啟 Amazon SQS 主控台，並顯示目標佇列詳細資訊。

1. 選擇**傳送及接收訊息**。

1. 在**接收訊息**下，選擇**輪詢訊息**。

   Amazon SQS 會將收到的訊息載入佇列。按一下個別訊息以查看其詳細資訊。

   佇列中應該有三個事件訊息：
   + 類型 的兩個`INSERT`，一個是在您第一次建立資料表項目時產生的，另一個是在您透過變更索引鍵值重新建立項目時產生的。
   + 類型 之一`MODIFY`，當您將屬性新增至資料表項目時產生。

   請注意，佇列`DELETE`中沒有 類型的事件訊息，即使您刪除並變更索引鍵值來重新建立資料表項目時，也一樣。我們指定的管道篩選條件只會選取 `INSERT`和 `MODIFY`，因此管道會篩選出`DELETE`事件，而不是將它交付到佇列。

## 清除：刪除資源
<a name="pipes-get-started-delete"></a>

最後一步，我們將刪除堆疊及其包含的資源。

**重要**  
只要堆疊中包含的 Amazon 資源存在，就會向您收取費用。

1. 開啟位在 [https://console.aws.amazon.com/cloudformation/](https://console.aws.amazon.com/cloudformation/) 的 CloudFormation​ 主控台。

1. 在**堆疊**頁面上，選擇從範本建立的堆疊，然後選擇**刪除**，接著確認**刪除**。

   CloudFormation 會啟動刪除堆疊及其包含的所有資源。

## CloudFormation 範本詳細資訊
<a name="pipes-get-started-template-details"></a>

此範本會在您的帳戶中建立資源並授予許可。

### Resources
<a name="pipes-get-started-template-resources"></a>

本教學課程的 CloudFormation 範本會在您的帳戶中建立下列資源：

**重要**  
如果您從此範本建立堆疊，則會向您收取所使用的 Amazon 資源費用。
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html)：做為管道事件來源的 DynamoDB 資料表。
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sqs-queue.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sqs-queue.html)：Amazon SQS 佇列，做為流經管道之事件的目標。
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html)：IAM 執行角色授予您帳戶中 EventBridge Pipes 服務的許可。
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pipes-pipe.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pipes-pipe.html)：將 DynamoDB 資料表連接至 Amazon SQS 佇列的管道。

### 許可
<a name="pipes-get-started-template-perms"></a>

範本包含代表執行角色`AWS::IAM::Role`的資源。此角色會授予 EventBridge 管道服務 (`pipes.amazonaws.com`) 您帳戶中的下列許可。

下列許可範圍限定於 DynamoDB 資料表，並串流範本建立為管道的事件來源：
+ `dynamodb:DescribeStream`
+ `dynamodb:GetRecords`
+ `dynamodb:GetShardIterator`
+ `dynamodb:ListStreams`

下列許可的範圍是堆疊建立為管道目標的 Amazon SQS 佇列：
+ `sqs:SendMessage`

## CloudFormation 範本
<a name="pipes-get-started-template"></a>

將下列 JSON 或 YAML 程式碼儲存為個別檔案，以用作本教學課程的 CloudFormation 範本。

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

```
{
  "AWSTemplateFormatVersion": "2010-09-09",

 "Description" : "[AWSDocs] EventBridge: pipes-get-started",

  "Parameters" : {
    "SourceTableName" : {
      "Type" : "String",
      "Default" : "pipe-example-source",
      "Description" : "Specify the name of the table to provision as the pipe source, or accept the default."
    },
  "TargetQueueName" : {
    "Type" : "String",
    "Default" : "pipe-example-target",
    "Description" : "Specify the name of the queue to provision as the pipe target, or accept the default."
  },
    "PipeName" : {
      "Type" : "String",
      "Default" : "pipe-with-filtering-example",
      "Description" : "Specify the name of the table to provision as the pipe source, or accept the default."
    }
},
  "Resources": {
    "PipeSourceDynamoDBTable": {
      "Type": "AWS::DynamoDB::Table",
      "Properties": {
        "AttributeDefinitions": [{
            "AttributeName": "Album",
            "AttributeType": "S"
          },
          {
            "AttributeName": "Artist",
            "AttributeType": "S"
          }

        ],
        "KeySchema": [{
            "AttributeName": "Album",
            "KeyType": "HASH"

          },
          {
            "AttributeName": "Artist",
            "KeyType": "RANGE"
          }
        ],
        "ProvisionedThroughput": {
          "ReadCapacityUnits": 10,
          "WriteCapacityUnits": 10
        },
        "StreamSpecification": {
          "StreamViewType": "NEW_AND_OLD_IMAGES"
        },
        "TableName": { "Ref" : "SourceTableName" }
      }
    },
    "PipeTargetQueue": {
      "Type": "AWS::SQS::Queue",
      "Properties": {
        "QueueName": { "Ref" : "TargetQueueName" }
      }
    },
    "PipeTutorialPipeRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [{
            "Effect": "Allow",
            "Principal": {
              "Service": "pipes.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
              "StringLike": {
                "aws:SourceArn": {
                  "Fn::Join": [
                    "",
                    [
                      "arn:",
                      { "Ref": "AWS::Partition" },
                      ":pipes:",
                      { "Ref": "AWS::Region" },
                      ":",
                      { "Ref": "AWS::AccountId" },
                      ":pipe/",
                      { "Ref": "PipeName" }
                    ]
                  ]
                },
                "aws:SourceAccount": { "Ref" : "AWS::AccountId" }
              }
            }
          }]
        },
        "Description" : "EventBridge Pipe template example. Execution role that grants the pipe the permissions necessary to send events to the specified pipe.",
        "Path": "/",
        "Policies": [{
            "PolicyName": "SourcePermissions",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [{
                "Effect": "Allow",
                "Action": [
                  "dynamodb:DescribeStream",
                  "dynamodb:GetRecords",
                  "dynamodb:GetShardIterator",
                  "dynamodb:ListStreams"
                ],
                "Resource": [
                  { "Fn::GetAtt" : [ "PipeSourceDynamoDBTable", "StreamArn" ] }
                ]
              }]
            }
          },
          {
            "PolicyName": "TargetPermissions",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [{
                "Effect": "Allow",
                "Action": [
                  "sqs:SendMessage"
                ],
                "Resource": [
                  { "Fn::GetAtt" : [ "PipeTargetQueue", "Arn" ] }
                ]
              }]
            }
          }
        ]
      }
  },
    "PipeWithFiltering": {
      "Type": "AWS::Pipes::Pipe",
      "Properties": {
        "Description" : "EventBridge Pipe template example. Pipe that receives events from a DynamoDB stream, applies a filter, and sends matching events on to an SQS Queue.",
        "Name": { "Ref" : "PipeName" },
        "RoleArn": {"Fn::GetAtt" : ["PipeTutorialPipeRole", "Arn"] },
        "Source": { "Fn::GetAtt" : [ "PipeSourceDynamoDBTable", "StreamArn" ] },
        "SourceParameters": {
          "DynamoDBStreamParameters" : {
            "StartingPosition" : "LATEST"
         },
        "FilterCriteria" : {
          "Filters" : [ {
            "Pattern" : "{ \"eventName\": [\"INSERT\", \"MODIFY\"] }"
         }]
        }
        },
        "Target": { "Fn::GetAtt" : [ "PipeTargetQueue", "Arn" ] }
      }
    }
  }
}
```

------
#### [ YAML ]

```
AWSTemplateFormatVersion: '2010-09-09'
Description: '[AWSDocs] EventBridge: pipes-get-started'
Parameters:
  SourceTableName:
    Type: String
    Default: pipe-example-source
    Description: Specify the name of the table to provision as the pipe source, or accept the default.
  TargetQueueName:
    Type: String
    Default: pipe-example-target
    Description: Specify the name of the queue to provision as the pipe target, or accept the default.
  PipeName:
    Type: String
    Default: pipe-with-filtering-example
    Description: Specify the name of the table to provision as the pipe source, or accept the default.
Resources:
  PipeSourceDynamoDBTable:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        - AttributeName: Album
          AttributeType: S
        - AttributeName: Artist
          AttributeType: S
      KeySchema:
        - AttributeName: Album
          KeyType: HASH
        - AttributeName: Artist
          KeyType: RANGE
      ProvisionedThroughput:
        ReadCapacityUnits: 10
        WriteCapacityUnits: 10
      StreamSpecification:
        StreamViewType: NEW_AND_OLD_IMAGES
      TableName: !Ref SourceTableName
  PipeTargetQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Ref TargetQueueName
  PipeTutorialPipeRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: pipes.amazonaws.com
            Action: sts:AssumeRole
            Condition:
              StringLike:
                aws:SourceArn: !Join
                  - ''
                  - - 'arn:'
                    - !Ref AWS::Partition
                    - ':pipes:'
                    - !Ref AWS::Region
                    - ':'
                    - !Ref AWS::AccountId
                    - ':pipe/'
                    - !Ref PipeName
                aws:SourceAccount: !Ref AWS::AccountId
      Description: EventBridge Pipe template example. Execution role that grants the pipe the permissions necessary to send events to the specified pipe.
      Path: /
      Policies:
        - PolicyName: SourcePermissions
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - dynamodb:DescribeStream
                  - dynamodb:GetRecords
                  - dynamodb:GetShardIterator
                  - dynamodb:ListStreams
                Resource:
                  - !GetAtt PipeSourceDynamoDBTable.StreamArn
        - PolicyName: TargetPermissions
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - sqs:SendMessage
                Resource:
                  - !GetAtt PipeTargetQueue.Arn
  PipeWithFiltering:
    Type: AWS::Pipes::Pipe
    Properties:
      Description: EventBridge Pipe template example. Pipe that receives events from a DynamoDB stream, applies a filter, and sends matching events on to an SQS Queue.
      Name: !Ref PipeName
      RoleArn: !GetAtt PipeTutorialPipeRole.Arn
      Source: !GetAtt PipeSourceDynamoDBTable.StreamArn
      SourceParameters:
        DynamoDBStreamParameters:
          StartingPosition: LATEST
        FilterCriteria:
          Filters:
            - Pattern: '{ "eventName": ["INSERT", "MODIFY"] }'
      Target: !GetAtt PipeTargetQueue.Arn
```

------