

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

# 分析
<a name="analytics-pattern-list"></a>

**Topics**
+ [在 Microsoft SQL Server Analysis Services 中分析 Amazon Redshift 資料](analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services.md)
+ [使用 Amazon Athena 和 Amazon Quick Sight 分析並視覺化巢狀 JSON 資料](analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.md)
+ [自動化從 AWS Data Exchange 到 Amazon S3 的資料擷取](automate-data-ingestion-from-aws-data-exchange-into-amazon-s3.md)
+ [使用 AWS CloudFormation 範本自動化 AWS Glue 中的加密強制執行 AWS CloudFormation](automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template.md)
+ [建置資料管道，以使用 AWS DataOps 開發套件擷取、轉換和分析 Google Analytics 資料](build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit.md)
+ [使用 Amazon Kinesis Video Streams 和 AWS Fargate 建置影片處理管道](build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate.md)
+ [建置 ETL 服務管道，使用 AWS Glue 從 Amazon S3 遞增載入資料至 Amazon Redshift](build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue.md)
+ [使用 Amazon DataZone 建置企業資料網格 AWS CDK，以及 AWS CloudFormation](build-enterprise-data-mesh-amazon-data-zone.md)
+ [使用 AWS 服務計算風險值 (VaR)](calculate-value-at-risk-var-by-using-aws-services.md)
+ [使用 Amazon Athena 設定共用 AWS Glue Data Catalog 的跨帳戶存取權](configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena.md)
+ [將 Teradata NORMALIZE 暫時功能轉換為 Amazon Redshift SQL](convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql.md)
+ [將 Teradata RESET WHEN 功能轉換為 Amazon Redshift SQL](convert-the-teradata-reset-when-feature-to-amazon-redshift-sql.md)
+ [使用基礎設施做為程式碼，在 AWS 雲端上部署和管理無伺服器資料湖](deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code.md)
+ [在啟動時強制標記 Amazon EMR 叢集](enforce-tagging-of-amazon-emr-clusters-at-launch.md)
+ [確保在啟動時啟用對 Amazon S3 的 Amazon EMR 記錄](ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch.md)
+ [使用 AWS Glue 任務和 Python 產生測試資料](generate-test-data-using-an-aws-glue-job-and-python.md)
+ [使用 AWS IoT Greengrass，以經濟實惠的方式直接將 IoT 資料擷取至 Amazon S3 AWS IoT](cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.md)
+ [使用 Lambda 函數在暫時性 EMR 叢集中啟動 Spark 任務](launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function.md)
+ [使用 AWS Glue 將 Apache Cassandra 工作負載遷移至 Amazon Keyspaces](migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.md)
+ [從內部部署伺服器將 Oracle Business Intelligence 12c 遷移至 AWS 雲端](migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.md)
+ [將 ELK 堆疊遷移至 AWS 上的彈性雲端](migrate-an-elk-stack-to-elastic-cloud-on-aws.md)
+ [AWS 雲端 使用 Starburst 將資料遷移至](migrate-data-to-the-aws-cloud-by-using-starburst.md)
+ [在 AWS 上最佳化輸入檔案大小的 ETL 擷取](optimize-the-etl-ingestion-of-input-file-size-on-aws.md)
+ [使用 透過驗證、轉換和分割來協調 ETL 管道 AWS Step Functions](orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.md)
+ [使用 Amazon Redshift ML 執行進階分析](perform-advanced-analytics-using-amazon-redshift-ml.md)
+ [使用 Amazon Athena 查詢具有 SQL 的 Amazon DynamoDB 資料表](query-amazon-dynamodb-tables-sql-amazon-athena.md)
+ [使用 Athena 存取、查詢和聯結 Amazon DynamoDB 資料表](access-query-and-join-amazon-dynamodb-tables-using-athena.md)
+ [使用純量 Python UDF 設定 Amazon Redshift 查詢結果的語言特定排序](set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf.md)
+ [訂閱來自不同 AWS 區域中 S3 儲存貯體的事件通知的 Lambda 函數](subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions.md)
+ [將資料轉換為 Apache Parquet 的三種 AWS Glue ETL 任務類型](three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet.md)
+ [使用 Amazon Athena 和 Amazon QuickSight 視覺化 Amazon Redshift 稽核日誌](visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight.md)
+ [使用 Amazon Quick Sight 視覺化所有 AWS 帳戶的 IAM 登入資料報告](visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.md)
+ [更多模式](analytics-more-patterns-pattern-list.md)

# 在 Microsoft SQL Server Analysis Services 中分析 Amazon Redshift 資料
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services"></a>

*Sunil Vora，Amazon Web Services*

## 總結
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-summary"></a>

此模式說明如何使用 Intellisoft OLE 資料庫提供者或 CData ADO.NET 提供者進行資料庫存取，來連接和分析 Microsoft SQL Server Analysis Services 中的 Amazon Redshift 資料。

Amazon Redshift 是一種在雲端中完全受管的 PB 級資料倉儲服務。SQL Server Analysis Services 是一種線上分析處理 (OLAP) 工具，可用來分析來自 Amazon Redshift 等資料區塊和資料倉儲的資料。您可以使用 SQL Server Analysis Services 從資料建立 OLAP 立方體，以進行快速、進階的資料分析。 

## 先決條件和限制
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-prereqs"></a>

**假設**
+ 此模式說明如何在 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體上為 Amazon Redshift 設定 SQL Server Analysis Services 和 Intellisoft OLE 資料庫提供者或 CData ADO.NET 提供者。或者，您可以在公司資料中心的主機上安裝兩者。

**先決條件**
+ 作用中的 AWS 帳戶
+ 具有登入資料的 Amazon Redshift 叢集

## Architecture
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-architecture"></a>

**來源技術堆疊**
+ Amazon Redshift 叢集

**目標技術堆疊**
+ Microsoft SQL Server Analysis Services

**來源和目標架構**

![\[在 Microsoft SQL Server Analysis Services 中分析 Amazon Redshift 資料\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e444fec0-e00f-4cc6-acc6-4ffc61b654a0/images/6f29dab5-1ea7-452f-9b07-d1d23ae469a2.png)


## 工具
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-tools"></a>
+ [Microsoft Visual Studio 2019 （社群版本）](https://visualstudio.microsoft.com/vs/)
+ 適用於 [Amazon Redshift 的 Intellisoft OLE 資料庫提供者 （試用） ](https://www.pgoledb.com/index.php?option=com_filecabinet&view=files&id=1&Itemid=68)或[適用於 Amazon Redshift 的 CData ADO.NET 提供者 （試用）](https://www.cdata.com/kb/tech/redshift-ado-ssas.rst)

## 史詩
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-epics"></a>

### 分析資料表
<a name="analyze-tables"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 分析要匯入的資料表和資料。 | 識別要匯入的 Amazon Redshift 資料表及其大小。 | DBA | 

### 設定 EC2 執行個體並安裝工具
<a name="set-up-ec2-instance-and-install-tools"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 EC2 執行個體。 | 在您的 AWS 帳戶中，在私有或公有子網路中建立 EC2 執行個體。 | 系統管理員 | 
| 安裝用於資料庫存取的工具。 | 下載並安裝[適用於 Amazon Redshift 的 Intellisoft OLE 資料庫提供者 ](https://www.pgoledb.com/index.php?option=com_filecabinet&view=files&id=1&Itemid=68)（或適用於 [Amazon Redshift 的 CData ADO.NET 提供者](https://www.cdata.com/kb/tech/redshift-ado-ssas.rst))。  | 系統管理員 | 
| 安裝 Visual Studio。 | 下載並安裝 [Visual Studio 2019 (Community Edition)](https://visualstudio.microsoft.com/vs/)。  | 系統管理員 | 
| 安裝擴充功能。 | 在 Visual Studio 中安裝 **Microsoft Analysis Services Projects** 延伸模組。 | 系統管理員 | 
| 建立專案。 | 在 Visual Studio 中建立新的表格式模型專案，以存放 Amazon Redshift 資料。在 Visual Studio 中，選擇建立**專案時的 Analysis Services 表格式**專案選項。 | DBA | 

### 建立資料來源和匯入資料表
<a name="create-data-source-and-import-tables"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Amazon Redshift 資料來源。 | 使用適用於 Amazon Redshift 的 Intellisoft OLE 資料庫提供者 （或適用於 Amazon Redshift 的 CData ADO.NET 提供者） 和您的 Amazon Redshift 憑證來建立 Amazon Redshift 資料來源。 | Amazon Redshift、DBA | 
| 匯入資料表。 | 選取資料表和檢視，並將其從 Amazon Redshift 匯入 SQL Server Analysis Services 專案。 | Amazon Redshift、DBA | 

### 遷移後清除
<a name="clean-up-after-migration"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除 EC2 執行個體。 | 刪除您先前啟動的 EC2 執行個體。 | 系統管理員 | 

## 相關資源
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-resources"></a>
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/) (AWS 文件）
+ [安裝 SQL Server Analysis Services](https://docs.microsoft.com/en-us/analysis-services/instances/install-windows/install-analysis-services?view=asallproducts-allversions) (Microsoft 文件）
+ [表格式模型設計工具](https://docs.microsoft.com/en-us/analysis-services/tabular-models/tabular-model-designer-ssas?view=asallproducts-allversions) (Microsoft 文件）
+ [進階分析的 OLAP 立方體概觀](https://docs.microsoft.com/en-us/system-center/scsm/olap-cubes-overview?view=sc-sm-2019) (Microsoft 文件）
+ [Microsoft Visual Studio 2019 （社群版本）](https://visualstudio.microsoft.com/vs/)
+ [Amazon Redshift 的 Intellisoft OLE 資料庫提供者 （試驗）](https://www.pgoledb.com/index.php?option=com_filecabinet&view=files&id=1&Itemid=68) 
+ [Amazon Redshift 的 CData ADO.NET 提供者 （試用）](https://www.cdata.com/kb/tech/redshift-ado-ssas.rst)

# 使用 Amazon Athena 和 Amazon Quick Sight 分析並視覺化巢狀 JSON 資料
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight"></a>

*Anoop Singh，Amazon Web Services*

## 摘要
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-summary"></a>

此模式說明如何使用 Amazon Athena 將巢狀 JSON 格式的資料結構轉譯為表格式檢視，然後在 Amazon Quick Sight 中視覺化資料。

您可以將 JSON 格式的資料用於來自作業系統的 API 驅動資料饋送，以建立資料產品。此資料也可以協助您更了解客戶及其與產品的互動，因此您可以量身打造使用者體驗並預測結果。

## 先決條件和限制
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 代表巢狀資料結構的 JSON 檔案 （此模式提供範例檔案）

**限制：**
+ JSON 功能與 Athena 中現有的 SQL 導向函數完美整合。不過，它們與 ANSI SQL 不相容，而且 JSON 檔案預期會將每個記錄放在單獨的一行。您可能需要使用 Athena 中的 `ignore.malformed.json` 屬性來指出格式不正確的 JSON 記錄是否應該變成 null 字元或產生錯誤。 如需詳細資訊，請參閱 Athena 文件中的[讀取 JSON 資料的最佳實務](https://docs.aws.amazon.com/athena/latest/ug/parsing-JSON.html)。
+ 此模式只會考慮簡單和少量的 JSON 格式資料。如果您想要大規模使用這些概念，請考慮套用資料分割，並將您的資料合併成較大的檔案。

## Architecture
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-architecture"></a>

下圖顯示此模式的架構和工作流程。巢狀資料結構會以 JSON 格式存放在 Amazon Simple Storage Service (Amazon S3) 中。在 Athena 中，JSON 資料會映射至 Athena 資料結構。然後，您可以建立檢視來分析資料，並在 Quick Sight 中視覺化資料結構。

![\[分析和視覺化 AWS 上的巢狀 JSON 資料。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e9ad39a1-e0a4-4429-bdc0-594b68707761/images/474e8747-626f-468c-9c27-c007af79bf2d.png)


## 工具
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-tools"></a>

**AWS 服務**
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。此模式使用 Amazon S3 來存放 JSON 檔案。
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon S3 中分析資料。此模式使用 Athena 來查詢和轉換 JSON 資料。透過 中的幾個動作 AWS 管理主控台，您可以將 Athena 指向 Amazon S3 中的資料，並使用標準 SQL 執行一次性查詢。Athena 是無伺服器，因此無需設定或管理基礎設施，您只需為執行的查詢付費。Athena 會自動擴展並平行執行查詢，因此即使使用大型資料集和複雜的查詢，結果也會很快。    
+ [Amazon Quick Sight](https://docs.aws.amazon.com/quicksuite/latest/userguide/quick-bi.html) 是一種雲端規模的商業智慧 (BI) 服務，可協助您在單一儀表板上視覺化、分析和報告資料。Quick Sight 可讓您輕鬆建立和發佈互動式儀表板，其中包含機器學習 (ML) 洞見。您可以從任何裝置存取這些儀表板，並將其內嵌到您的應用程式、入口網站和網站。

**範例程式碼**

下列 JSON 檔案提供巢狀資料結構，您可以在此模式中使用。

```
{
  "symbol": "AAPL",
  "financials": [
    {
      "reportDate": "2017-03-31",
      "grossProfit": 20591000000,
      "costOfRevenue": 32305000000,
      "operatingRevenue": 52896000000,
      "totalRevenue": 52896000000,
      "operatingIncome": 14097000000,
      "netIncome": 11029000000,
      "researchAndDevelopment": 2776000000,
      "operatingExpense": 6494000000,
      "currentAssets": 101990000000,
      "totalAssets": 334532000000,
      "totalLiabilities": 200450000000,
      "currentCash": 15157000000,
      "currentDebt": 13991000000,
      "totalCash": 67101000000,
      "totalDebt": 98522000000,
      "shareholderEquity": 134082000000,
      "cashChange": -1214000000,
      "cashFlow": 12523000000,
      "operatingGainsLosses": null
    }
  ]
}
```

## 史詩
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-epics"></a>

### 設定 S3 儲存貯體
<a name="set-up-an-s3-bucket"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 S3 儲存貯體。 | 若要建立儲存貯體以存放 JSON 檔案，請登入 AWS 管理主控台，開啟 [Amazon S3 主控台](https://console.aws.amazon.com/s3/)，然後選擇**建立儲存貯**體。如需詳細資訊，請參閱 Amazon S3 文件中的[建立儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)體。  | 系統管理員 | 
| 新增巢狀 JSON 資料。 | 將您的 JSON 檔案上傳至 S3 儲存貯體。如需範例 JSON 檔案，請參閱上一節。如需說明，請參閱 [Amazon S3 文件中的上傳物件](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)。 Amazon S3  | 系統管理員 | 

### 分析 Athena 中的資料
<a name="analyze-data-in-ate"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立用於映射 JSON 資料的資料表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html)如需建立資料表的詳細資訊，請參閱 [Athena 文件](https://docs.aws.amazon.com/athena/latest/ug/creating-tables.html)。 | 開發人員 | 
| 建立用於資料分析的檢視。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html)如需建立檢視的詳細資訊，請參閱 [Athena 文件](https://docs.aws.amazon.com/athena/latest/ug/create-view.html)。 | 開發人員 | 
| 分析和驗證資料。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html) | 開發人員 | 

### 在 Quick Sight 中視覺化資料
<a name="visualize-data-in-qsight"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 Quick Sight 中將 Athena 設定為資料來源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html) | 系統管理員 | 
| 在 Quick Sight 中視覺化資料。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html) | 資料分析 | 

## 相關資源
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-resources"></a>
+ [Amazon Athena 文件](https://docs.aws.amazon.com/athena/latest/ug/getting-started.html)
+ [Amazon Quick Sight 教學課程](https://docs.aws.amazon.com/quicksuite/latest/userguide/example-analysis.html)
+ [使用巢狀 JSON ](https://aws.amazon.com/blogs/big-data/create-tables-in-amazon-athena-from-nested-json-and-mappings-using-jsonserde/)（部落格文章）

# 自動化從 AWS Data Exchange 到 Amazon S3 的資料擷取
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3"></a>

*Adnan Alvee 和 Manikanta Gona，Amazon Web Services*

## 總結
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-summary"></a>

此模式提供 CloudFormation 範本，可讓您在 Amazon Simple Storage Service (Amazon S3) 中自動將資料從 擷取 AWS Data Exchange 到資料湖。 

AWS Data Exchange 是一項服務，可讓您輕鬆地在 AWS Cloud 中安全地交換檔案型資料集。 AWS Data Exchange 資料集是以訂閱為基礎。身為訂閱者，您也可以在供應商發佈新資料時存取資料集修訂。 

 CloudFormation 範本會在 Amazon CloudWatch Events 和 AWS Lambda 函數中建立事件。事件會監控您已訂閱之資料集的任何更新。如果有更新，CloudWatch 會啟動 Lambda 函數，將資料複製到您指定的 S3 儲存貯體。成功複製資料後，Lambda 會傳送 Amazon Simple Notification Service (Amazon SNS) 通知給您。

## 先決條件和限制
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 在 中訂閱資料集 AWS Data Exchange

**限制**
+ 範本 CloudFormation 必須針對其中的每個訂閱資料集分別部署 AWS Data Exchange。

## Architecture
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-architecture"></a>

**目標技術堆疊**
+ AWS Lambda
+ Amazon S3
+ AWS Data Exchange
+ Amazon CloudWatch
+ Amazon SNS

**目標架構**

![\[CloudWatch 會啟動 Lambda 函數，將資料複製到 S3 儲存貯體，並傳送 Amazon SNS 通知。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/059816dc-5a71-4942-9c7f-ac977072eebc/images/ec021620-47c1-4fb5-95a9-3b8985accc56.png)


**自動化和擴展**

您可以針對要擷取至資料湖的資料集多次使用 CloudFormation 範本。

## 工具
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-tools"></a>
+ [AWS Data Exchange](https://docs.aws.amazon.com/data-exchange/latest/userguide/what-is.html) 可讓 AWS 客戶在 中安全地交換檔案型資料集 AWS 雲端。身為訂閱者，您可以從合格的資料提供者找到並訂閱數百種產品。然後，您可以快速下載資料集或將其複製到 Amazon S3，以用於各種 AWS 分析和機器學習服務。任何具有 的人 AWS 帳戶 都可以是 AWS Data Exchange 訂閱者。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 可讓您直接執行程式碼，無需佈建或管理伺服器。Lambda 只有在需要時才會執行程式碼，可自動從每天數項請求擴展成每秒數千項請求。您只需為使用的運算時間付費；程式碼未執行時無需付費。使用 Lambda，您可以為幾乎任何類型的應用程式或後端服務執行程式碼，無需管理。Lambda 會在高可用性運算基礎設施上執行您的程式碼，並管理所有運算資源，包括伺服器和作業系統維護、容量佈建和自動擴展、程式碼監控和記錄。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html) 為網際網路提供儲存空間。您可以使用 Amazon S3 隨時從 Web 任何地方存放和擷取任意資料量。
+ [Amazon CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) 提供近乎即時的系統事件串流，描述 AWS 資源的變更。使用您可以快速設定的簡單規則，您可以比對事件並將它們路由到一或多個目標函數或串流。CloudWatch Events 在操作變更時會查覺到。它會回應這些操作變更，並視需要採取修正動作，透過傳送訊息來回應環境、啟用 函數、進行變更，以及擷取狀態資訊。您也可以使用 CloudWatch Events 來排程使用 **Cron** 或 **Rate** 表達式在特定時間自行啟動的自動化動作。
+ [Amazon Simple Notification Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可讓應用程式、最終使用者和裝置立即從雲端傳送和接收通知。Amazon SNS 為高輸送量、以推送為基礎的many-to-many訊息提供主題 （通訊管道）。使用 Amazon SNS 主題，發佈者可以將訊息分發給大量訂閱者以進行平行處理，包括 Amazon Simple Queue Service (Amazon SQS) 佇列、Lambda 函數和 HTTP/S Webhook。您也可以使用 Amazon SNS，使用行動推播、簡訊和電子郵件傳送通知給最終使用者。

## 史詩
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-epics"></a>

### 訂閱資料集
<a name="subscribe-to-a-data-set"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 訂閱資料集。 | 在 AWS Data Exchange 主控台中，訂閱資料集。如需說明，請參閱 AWS 文件中的[在 上訂閱資料產品 AWS Data Exchange](https://docs.aws.amazon.com/data-exchange/latest/userguide/subscribe-to-data-sets.html)。 | 一般 AWS | 
| 請記下資料集屬性。 | 請記下資料集的 、 AWS 區域 ID 和修訂 ID。在下一個步驟中，範本將需要此 CloudFormation 值。 | 一般 AWS | 

### 部署 CloudFormation 範本
<a name="deploy-the-cfn-template"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 S3 儲存貯體和資料夾。 | 如果您在 Amazon S3 中已有資料湖，請建立資料夾來存放要擷取的資料 AWS Data Exchange。如果您要部署範本進行測試，請建立新的 S3 儲存貯體，並記下下一個步驟的儲存貯體名稱和資料夾字首。 | 一般 AWS | 
| 部署 CloudFormation 範本。 | 將做為附件提供的 CloudFormation 範本部署至此模式。如需說明，請參閱 [CloudFormation 文件](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。設定下列參數以對應至您的 AWS 帳戶、資料集和 S3 儲存貯體設定：**資料集 AWS 區域**、**資料集 ID**、**修訂 ID**、**S3 儲存貯體名稱** （例如 `DOC-EXAMPLE-BUCKET`)、**資料夾字首** （例如 `myfolder/`)，以及 **SNS 通知的電子郵件**。您可以將**資料集名稱**參數設定為任何名稱。當您部署範本時，它會執行 Lambda 函數，以自動擷取資料集中可用的第一組資料。接著，當新資料抵達資料集時，會自動執行後續擷取。 | 一般 AWS | 

## 相關資源
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-resources"></a>
+ [訂閱 上的資料產品 AWS Data Exchange](https://docs.aws.amazon.com/data-exchange/latest/userguide/subscribe-to-data-sets.html) (AWS Data Exchange 文件）

## 附件
<a name="attachments-059816dc-5a71-4942-9c7f-ac977072eebc"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/059816dc-5a71-4942-9c7f-ac977072eebc/attachments/attachment.zip)

# 使用 AWS CloudFormation 範本自動化 AWS Glue 中的加密強制執行 AWS CloudFormation
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template"></a>

*Diogo Guedes，Amazon Web Services*

## 總結
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-summary"></a>

此模式說明如何使用 AWS CloudFormation 範本在 AWS Glue 中設定和自動化加密強制執行。 AWS CloudFormation 範本會建立強制執行加密所需的所有必要組態和資源。這些資源包括初始組態、Amazon EventBridge 規則建立的預防性控制，以及 AWS Lambda 函數。

## 先決條件和限制
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 部署 CloudFormation 範本及其資源的許可

**限制**

此安全控制是區域性的。您必須在要在 AWS Glue 中設定加密強制執行的每個 AWS 區域中部署安全控制。

## Architecture
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-architecture"></a>

**目標技術堆疊**
+ Amazon CloudWatch Logs （來自 AWS Lambda)
+ Amazon EventBridge 規則
+ AWS CloudFormation 堆疊
+ AWS CloudTrail
+ AWS Identity and Access Management (IAM) 受管角色和政策
+ AWS Key Management Service (AWS KMS)
+ AWS KMS 別名
+ AWS Lambda 功能
+ AWS Systems Manager 參數存放區

**目標架構**

下圖顯示如何在 AWS Glue 中自動化加密強制執行。

![\[圖表顯示如何使用 CloudFormation 範本自動化 AWS Glue 中的加密強制執行。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/d50d0659-5592-44d0-8fcb-7a2983712640/images/272a7fb2-ecbc-41f7-a556-d555e4e39a59.png)


該圖顯示以下工作流程：

1. [CloudFormation 範本](https://github.com/aws-samples/aws-custom-guardrail-event-driven/blob/main/CloudFormation/aws-custom-guardrail-event-driven.yaml)會建立所有資源，包括 AWS Glue 中加密強制執行的初始組態和偵測控制。

1. EventBridge 規則會偵測加密組態中的狀態變更。

1. 透過 CloudWatch Logs 叫用 Lambda 函數進行評估和記錄。對於不合規偵測，參數存放區會使用 AWS KMS 金鑰的 Amazon Resource Name (ARN) 復原。服務會修復為啟用加密的合規狀態。

**自動化和擴展**

如果您使用的是 [AWS Organizations](https://aws.amazon.com/organizations/)，則可以使用 [AWS CloudFormation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) 在多個帳戶中部署此範本，其中您想要在 AWS Glue 中啟用加密強制執行。

## 工具
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-tools"></a>
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可協助您即時監控 AWS 資源的指標，以及您在 AWS 上執行的應用程式。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一種無伺服器事件匯流排服務，可協助您將應用程式與來自各種來源的即時資料連線。例如，Lambda 函數、使用 API 目的地的 HTTP 調用端點，或其他 AWS 帳戶中的事件匯流排。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速一致地佈建資源，以及在整個 AWS 帳戶和區域的生命週期進行管理。
+ [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) 可協助您啟用 AWS 帳戶的營運和風險稽核、控管和合規。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是全受管的擷取、轉換和載入 (ETL) 服務。它可協助您可靠地分類、清理、擴充和移動資料存放區和資料串流之間的資料。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可協助您建立和控制密碼編譯金鑰，以協助保護您的資料。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可協助您管理在 AWS 雲端中執行的應用程式和基礎設施。它可簡化應用程式和資源管理、縮短偵測和解決操作問題的時間，並協助您大規模安全地管理 AWS 資源。

**Code**

此模式的程式碼可在 GitHub [aws-custom-guardrail-event-driven](https://github.com/aws-samples/aws-custom-guardrail-event-driven/blob/main/CloudFormation/aws-custom-guardrail-event-driven.yaml) 儲存庫中使用。

## 最佳實務
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-best-practices"></a>

AWS Glue 支援靜態資料加密，以便在 [ AWS Glue 中編寫任務](https://docs.aws.amazon.com/glue/latest/dg/author-job-glue.html)[，並使用開發端點開發指令碼](https://docs.aws.amazon.com/glue/latest/dg/dev-endpoint.html)。

請考慮下列最佳實務：
+ 設定 ETL 任務和開發端點，以使用 AWS KMS 金鑰寫入靜態加密的資料。
+ 使用您透過 [AWS KMS 管理的金鑰，加密存放在 AWS Glue Data Catalog](https://docs.aws.amazon.com/glue/latest/dg/components-overview.html#data-catalog-intro) 中的中繼資料。
+ 使用 AWS KMS 金鑰來加密任務書籤，以及[爬蟲程式](https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html)和 ETL 任務所產生的日誌。

## 史詩
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-epics"></a>

### 啟動 CloudFormation 範本
<a name="launch-the-cloudformation-template"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 CloudFormation 範本。 | 從 GitHub [儲存庫](https://github.com/aws-samples/aws-custom-guardrail-event-driven/blob/main/CloudFormation/aws-custom-guardrail-event-driven.yaml)下載`aws-custom-guardrail-event-driven.yaml`範本，然後[部署](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/deploy/index.html)範本。`CREATE_COMPLETE` 狀態表示您的範本已成功部署。範本不需要輸入參數。 | 雲端架構師 | 

### 驗證 AWS Glue 中的加密設定
<a name="verify-the-encryption-settings-in-aws-glue"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢查 AWS KMS 金鑰組態。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template.html) | 雲端架構師 | 

### 測試加密強制執行
<a name="test-the-encryption-enforcement"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 識別 CloudFormation 中的加密設定。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template.html) | 雲端架構師 | 
| 將佈建的基礎設施切換為不合規狀態。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template.html)在您清除核取方塊後，護欄會偵測 AWS Glue 中的不合規狀態，然後透過自動修復加密設定錯誤來強制執行合規。因此，在您重新整理頁面之後，應該再次選取加密核取方塊。 | 雲端架構師 | 

## 相關資源
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-resources"></a>
+ [在 AWS CloudFormation 主控台上建立堆疊](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html) (AWS CloudFormation 文件）
+ [使用 AWS CloudTrail 建立在 AWS API 呼叫上觸發的 CloudWatch Events 規則 CloudTrail](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/Create-CloudWatch-Events-CloudTrail-Rule.html) (Amazon CloudWatch 文件）
+ [在 AWS Glue 中設定加密](https://docs.aws.amazon.com/glue/latest/dg/set-up-encryption.html) (AWS Glue 文件）

# 建置資料管道，以使用 AWS DataOps 開發套件擷取、轉換和分析 Google Analytics 資料
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit"></a>

*Anton Kukushkin 和 Rudy Puig，Amazon Web Services*

## 總結
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-summary"></a>

此模式說明如何使用 AWS DataOps 開發套件 (AWS DDK) 和其他 建置資料管道來擷取、轉換和分析 Google Analytics 資料 AWS 服務。 AWS DDK 是一種開放原始碼開發架構，可協助您建置資料工作流程和現代資料架構 AWS。DDK AWS 的主要目標之一是節省您通常投入大量人力的資料管道任務的時間和精力，例如協調管道、建置基礎設施，以及在該基礎設施背後建立 DevOps。您可以將這些人力密集型任務卸載至 AWS DDK，以便專注於編寫程式碼和其他高價值活動。

## 先決條件和限制
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 適用於 Google Analytics 的 Amazon AppFlow 連接器，已[設定](https://docs.aws.amazon.com/appflow/latest/userguide/google-analytics.html)
+ [Python](https://www.python.org/downloads/) 和 [pip](https://pip.pypa.io/en/stable/cli/pip_download/) (Python 的套件管理員）
+ Git，已安裝和[設定](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup)
+ AWS Command Line Interface (AWS CLI)，[已安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)
+ AWS Cloud Development Kit (AWS CDK)，[已安裝](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install)

**產品版本**
+ Python 3.7 或更高版本
+ pip 9.0.3 或更新版本

## Architecture
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-architecture"></a>

**技術堆疊**
+ Amazon AppFlow
+ Amazon Athena
+ Amazon CloudWatch
+ Amazon EventBridge
+ Amazon Simple Storage Service (Amazon S3)
+ Amazon Simple Queue Service (Amazon SQS)
+ AWS DataOps 開發套件 (AWS DDK)
+ AWS Lambda

**目標架構**

下圖顯示擷取、轉換和分析 Google Analytics 資料的事件驅動程序。

![\[使用 AWS 服務擷取、轉換和分析 Google Analytics 資料。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/edf40222-2867-4d4a-9153-ab29785b6662/images/8c38b472-153b-4497-982c-8efb97d2f7a5.png)


該圖顯示以下工作流程：

1. Amazon CloudWatch 排程事件規則會叫用 Amazon AppFlow。

1. Amazon AppFlow 會將 Google Analytics 資料擷取到 S3 儲存貯體。

1. 在 S3 儲存貯體擷取資料之後，EventBridge 中的事件通知就會產生、由 CloudWatch Events 規則擷取，然後放入 Amazon SQS 佇列。

1. Lambda 函數會使用來自 Amazon SQS 佇列的事件、讀取個別的 S3 物件、將物件轉換為 Apache Parquet 格式、將轉換的物件寫入 S3 儲存貯體，然後建立或更新 AWS Glue Data Catalog 資料表定義。

1. Athena 查詢會針對資料表執行。

## 工具
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-tools"></a>

**AWS 工具**
+ [Amazon AppFlow](https://docs.aws.amazon.com/appflow/latest/userguide/what-is-appflow.html) 是一種全受管整合服務，可讓您在軟體即服務 (SaaS) 應用程式之間安全地交換資料。
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon S3 中分析資料。
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可協助您 AWS 即時監控 AWS 資源的指標，以及您執行的應用程式。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一種無伺服器事件匯流排服務，可協助您將應用程式與來自各種來源的即時資料連線。例如， AWS Lambda 函數、使用 API 目的地的 HTTP 呼叫端點，或其他事件匯流排 AWS 帳戶。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供安全、耐用且可用的託管佇列，可協助您整合和分離分散式軟體系統和元件。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是在程式碼中定義雲端基礎設施並透過其佈建的架構 CloudFormation。
+ [AWS DataOps 開發套件 (AWS DDK)](https://github.com/awslabs/aws-ddk) 是一種開放原始碼開發架構，可協助您在其中建置資料工作流程和現代資料架構 AWS。

**Code**

此模式的程式碼可在 GitHub [AWS DataOps 開發套件 (AWS DDK)](https://github.com/awslabs/aws-ddk) [和使用 Amazon AppFlow、Amazon Athena 和 AWS DataOps 開發套件儲存庫分析 Google Analytics 資料](https://github.com/aws-samples/aws-ddk-examples/tree/main/google-analytics-data-using-appflow/python)中找到。

## 史詩
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-epics"></a>

### 準備環境
<a name="prepare-the-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製原始程式碼。 | 若要複製原始程式碼，請執行下列命令：<pre>git clone https://github.com/aws-samples/aws-ddk-examples.git</pre> | DevOps 工程師 | 
| 建立虛擬環境。 | 導覽至原始程式碼目錄，然後執行下列命令來建立虛擬環境：<pre>cd google-analytics-data-using-appflow/python && python3 -m venv .venv</pre> | DevOps 工程師 | 
| 安裝相依性。 | 若要啟用虛擬環境並安裝相依性，請執行下列命令：<pre>source .venv/bin/activate && pip install -r requirements.txt</pre> | DevOps 工程師 | 

### 部署使用資料管道的應用程式
<a name="deploy-the-application-that-uses-your-data-pipeline"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 引導環境。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit.html) | DevOps 工程師 | 
| 部署資料。 | 若要部署資料管道，請執行 `cdk deploy --profile [AWS_PROFILE]`命令。 | DevOps 工程師 | 

### 測試部署
<a name="test-the-deployment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證堆疊狀態。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit.html) | DevOps 工程師 | 

## 疑難排解
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 部署在建立 `AWS::AppFlow::Flow`來源期間失敗，您會收到下列錯誤： `Connector Profile with name ga-connection does not exist` | 確認您已建立適用於 Google Analytics 的 Amazon AppFlow 連接器，並將其命名為 `ga-connection`。如需說明，請參閱 Amazon AppFlow 文件中的 [Google Analytics](https://docs.aws.amazon.com/appflow/latest/userguide/google-analytics.html)。 | 

## 相關資源
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-resources"></a>
+ [AWS DataOps 開發套件 (AWS DDK)](https://github.com/awslabs/aws-ddk) (GitHub)
+ [AWS DDK 範例](https://github.com/aws-samples/aws-ddk-examples) (GitHub)

## 其他資訊
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-additional"></a>

AWS DDK 資料管道由一或多個階段組成。在下列程式碼範例中，您會使用 從 Google Analytics `AppFlowIngestionStage` 擷取資料、`SqsToLambdaStage`處理資料轉換，以及`AthenaSQLStage`執行 Athena 查詢。

首先，會建立資料轉換和擷取階段，如下列程式碼範例所示：

```
        appflow_stage = AppFlowIngestionStage(
            self,
            id="appflow-stage",
            flow_name=flow.flow_name,
        )
        sqs_lambda_stage = SqsToLambdaStage(
            self,
            id="lambda-stage",
            lambda_function_props={
                "code": Code.from_asset("./ddk_app/lambda_handlers"),
                "handler": "handler.lambda_handler",
                "layers": [
                    LayerVersion.from_layer_version_arn(
                        self,
                        id="layer",
                        layer_version_arn=f"arn:aws:lambda:{self.region}:336392948345:layer:AWSDataWrangler-Python39:1",
                    )
                ],
                "runtime": Runtime.PYTHON_3_9,
            },
        )
        # Grant lambda function S3 read & write permissions
        bucket.grant_read_write(sqs_lambda_stage.function)
        # Grant Glue database & table permissions
        sqs_lambda_stage.function.add_to_role_policy(
            self._get_glue_db_iam_policy(database_name=database.database_name)
        )
        athena_stage = AthenaSQLStage(
            self,
            id="athena-sql",
            query_string=[
                (
                    "SELECT year, month, day, device, count(user_count) as cnt "
                    f"FROM {database.database_name}.ga_sample "
                    "GROUP BY year, month, day, device "
                    "ORDER BY cnt DESC "
                    "LIMIT 10; "
                )
            ],
            output_location=Location(
                bucket_name=bucket.bucket_name, object_key="query-results/"
            ),
            additional_role_policy_statements=[
                self._get_glue_db_iam_policy(database_name=database.database_name)
            ],
        )
```

接下來，建構會使用 EventBridge `DataPipeline` 規則將階段 "wire" 在一起，如下列程式碼範例所示：

```
        (
            DataPipeline(self, id="ingestion-pipeline")
            .add_stage(
                stage=appflow_stage,
                override_rule=Rule(
                    self,
                    "schedule-rule",
                    schedule=Schedule.rate(Duration.hours(1)),
                    targets=appflow_stage.targets,
                ),
            )
            .add_stage(
                stage=sqs_lambda_stage,
                # By default, AppFlowIngestionStage stage emits an event after the flow run finishes successfully
                # Override rule below changes that behavior to call the the stage when data lands in the bucket instead
                override_rule=Rule(
                    self,
                    "s3-object-created-rule",
                    event_pattern=EventPattern(
                        source=["aws.s3"],
                        detail={
                            "bucket": {"name": [bucket.bucket_name]},
                            "object": {"key": [{"prefix": "ga-data"}]},
                        },
                        detail_type=["Object Created"],
                    ),
                    targets=sqs_lambda_stage.targets,
                ),
            )
            .add_stage(stage=athena_stage)
        )
```

如需更多程式碼範例，請參閱 GitHub [使用 Amazon AppFlow、Amazon Athena 和 AWS DataOps 開發套件儲存庫分析 Google Analytics 資料](https://github.com/aws-samples/aws-ddk-examples/tree/main/google-analytics-data-using-appflow/python)。

# 使用 Amazon Kinesis Video Streams 和 AWS Fargate 建置影片處理管道
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate"></a>

*Piotr Chotkowski 和 Pushparaju Thangavel，Amazon Web Services*

## 總結
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-summary"></a>

此模式示範如何使用 [Amazon Kinesis Video Streams](https://aws.amazon.com/kinesis/video-streams/) 和 [AWS Fargate](https://aws.amazon.com/fargate) 從影片串流擷取影格，並將其儲存為影像檔案，以便在 [Amazon Simple Storage Service (Amazon S3](https://aws.amazon.com/s3/)) 中進一步處理。 

模式以 Java Maven 專案的形式提供範例應用程式。此應用程式使用 AWS [雲端開發套件 ](https://aws.amazon.com/cdk/)(AWS CDK) 定義 AWS 基礎設施。影格處理邏輯和基礎設施定義都會以 Java 程式設計語言撰寫。您可以使用此範例應用程式做為開發自己的即時影片處理管道的基礎，或建置機器學習管道的影片預先處理步驟。 

## 先決條件和限制
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ Java SE 開發套件 (JDK) 11，已安裝
+ [Apache Maven](https://maven.apache.org/)，已安裝
+ [AWS 雲端開發套件 (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)，已安裝
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) 第 2 版，已安裝
+ [Docker](https://docs.docker.com/get-docker/) （建置要在 AWS Fargate 任務定義中使用的 Docker 映像時需要），已安裝

**限制**

此模式旨在做為概念驗證，或做為進一步開發的基礎。它不應在生產部署中以目前的形式使用。

**產品版本**
+ 此模式已使用 AWS CDK 1.77.0 版進行測試 （請參閱 [AWS CDK 版本](https://docs.aws.amazon.com/cdk/api/latest/versions.html))
+ JDK 11
+ AWS CLI 第 2 版

## Architecture
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-architecture"></a>

**目標技術堆疊**
+ Amazon Kinesis Video Streams
+ AWS Fargate 任務
+ Amazon Simple Queue Service (Amazon SQS) 佇列
+ Amazon S3 儲存貯體

**目標架構**

![\[使用 Kinesis Video Streams 和 Fargate 建置影片處理管道的架構。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/9d1442c2-f3ee-47fd-8cce-90d9206ce4d4/images/a60e585f-27be-4dd6-897b-c38adf1d283f.png)


使用者建立 Kinesis 影片串流、上傳影片，並將包含輸入 Kinesis 影片串流和輸出 S3 儲存貯體詳細資訊的 JSON 訊息傳送至 SQS 佇列。AWS Fargate 正在容器中執行主要應用程式，會從 SQS 佇列提取訊息並開始擷取影格。每個影格都會儲存在映像檔案中，並存放在目標 S3 儲存貯體中。

**自動化和擴展**

範例應用程式可以在單一 AWS 區域內水平和垂直擴展。水平擴展可以透過增加從 SQS 佇列讀取的已部署 AWS Fargate 任務數量來實現。垂直擴展可以透過增加應用程式中框架分割和影像發佈執行緒的數量來實現。這些設定會在 AWS CDK 的 [QueueProcessingFargateService](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs-patterns.QueueProcessingFargateService.html) 資源定義中做為環境變數傳遞至應用程式。由於 AWS CDK 堆疊部署的本質，您可以在多個 AWS 區域和帳戶中部署此應用程式，無需額外努力。

## 工具
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-tools"></a>

**工具**
+ [AWS CDK](https://aws.amazon.com/cdk/) 是一種軟體開發架構，可透過使用 TypeScript、JavaScript、Python、Java 和 C\$1/ 等程式設計語言來定義您的雲端基礎設施和資源。淨額。
+ [Amazon Kinesis Video Streams](https://aws.amazon.com/kinesis/video-streams/) 是一項全受管 AWS 服務，可用來將即時影片從裝置串流至 AWS 雲端，或建置應用程式以進行即時影片處理或批次導向影片分析。
+ [AWS Fargate](https://aws.amazon.com/fargate) 是容器的無伺服器運算引擎。Fargate 不需要佈建和管理伺服器，並可讓您專注於開發應用程式。
+ [Amazon S3](https://aws.amazon.com/s3/) 是一種物件儲存服務，可提供可擴展性、資料可用性、安全性和效能。
+ [Amazon SQS](https://aws.amazon.com/sqs/) 是一種全受管訊息佇列服務，可讓您解耦和擴展微服務、分散式系統和無伺服器應用程式。

**Code**
+ 已連接範例應用程式專案 (`frame-splitter-code.zip`) 的 .zip 檔案。

## 史詩
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-epics"></a>

### 部署基礎設施
<a name="deploy-the-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動 Docker 常駐程式。 | 在本機系統上啟動 Docker 協助程式。AWS CDK 使用 Docker 來建置 AWS Fargate 任務中使用的映像。您必須先執行 Docker，才能繼續下一個步驟。 | 開發人員、DevOps 工程師 | 
| 建置專案。 | 下載`frame-splitter-code`範例應用程式 （已連接），並將其內容解壓縮至本機電腦上的資料夾。您必須先建置 [Java Maven](https://maven.apache.org/) 專案，才能部署基礎設施。在命令提示字元中，導覽至專案的根目錄，然後執行 命令來建置專案： <pre>mvn clean install</pre> | 開發人員、DevOps 工程師 | 
| 引導 AWS CDK。 | （僅限第一次使用 AWS CDK 的使用者） 如果這是您第一次使用 AWS CDK，您可能需要執行 AWS CLI 命令來引導環境：<pre>cdk bootstrap --profile "$AWS_PROFILE_NAME" </pre>其中 `$AWS_PROFILE_NAME`會保留來自您 AWS 登入資料的 AWS 設定檔名稱。或者，您可以移除此參數以使用預設設定檔。如需詳細資訊，請參閱 [AWS CDK 文件](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)。 | 開發人員、DevOps 工程師 | 
| 部署 AWS CDK 堆疊。 | 在此步驟中，您會在 AWS 帳戶中建立所需的基礎設施資源 (SQS 佇列、S3 儲存貯體、AWS Fargate 任務定義）、建置 AWS Fargate 任務所需的 Docker 映像，並部署應用程式。在命令提示字元中，導覽至專案的根目錄，然後執行 命令：<pre>cdk deploy --profile "$AWS_PROFILE_NAME" --all </pre>其中 `$AWS_PROFILE_NAME`會保留來自您 AWS 登入資料的 AWS 設定檔名稱。或者，您可以移除此參數以使用預設設定檔。確認部署。請注意 CDK 部署輸出中的 **QueueUrl** 和**儲存貯體**值；後續步驟中會需要這些值。AWS CDK 會建立資產、將其上傳至您的 AWS 帳戶，以及建立所有基礎設施資源。您可以在 [AWS CloudFormation 主控台](https://console.aws.amazon.com/cloudformation/)中觀察資源建立程序。如需詳細資訊，請參閱 [AWS CloudFormation 文件](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)和 [AWS CDK 文件](https://docs.aws.amazon.com/cdk/latest/guide/hello_world.html#hello_world_tutorial_deploy)。 | 開發人員、DevOps 工程師 | 
| 建立影片串流。 | 在此步驟中，您會建立 Kinesis 影片串流，做為影片處理的輸入串流。請確定您已安裝並設定 AWS CLI。在 AWS CLI 中，執行：<pre>aws kinesisvideo --profile "$AWS_PROFILE_NAME" create-stream --stream-name "$STREAM_NAME" --data-retention-in-hours "24" </pre>其中 `$AWS_PROFILE_NAME`會從您的 AWS 登入資料保留 AWS 設定檔的名稱 （或移除此參數以使用預設設定檔），而且 `$STREAM_NAME` 是任何有效的串流名稱。 或者，您可以依照 Kinesis Video [Streams 文件中的步驟，使用 Kinesis 主控台建立影片串流](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/gs-createstream.html#gs-createstream-console)。請注意所建立串流的 AWS Resource Name (ARN)；稍後會需要它。 | 開發人員、DevOps 工程師 | 

### 執行範例
<a name="run-an-example"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將影片上傳至串流。 | 在範例`frame-splitter-code`應用程式的專案資料夾中，開啟 `src/test/java/amazon/awscdk/examples/splitter`資料夾中`ProcessingTaskTest.java`的檔案。將 `profileName`****和 `streamName`****變數取代為您在先前步驟中使用的值。若要將範例影片上傳至您在上一個步驟中建立的 Kinesis 影片串流，請執行： <pre>amazon.awscdk.examples.splitter.ProcessingTaskTest#testExample test</pre>或者，您可以使用 [Kinesis Video Streams 文件中所述的其中一種方法上傳影片](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk.html)。 | 開發人員、DevOps 工程師 | 
| 啟動影片處理。 | 現在您已將影片上傳至 Kinesis 影片串流，您可以開始處理影片。若要啟動處理邏輯，您必須將包含詳細資訊的訊息傳送至 AWS CDK 在部署期間建立的 SQS 佇列。若要使用 AWS CLI 傳送訊息，請執行：<pre>aws sqs --profile "$AWS_PROFILE_NAME" send-message --queue-url QUEUE_URL --message-body MESSAGE </pre>其中 `$AWS_PROFILE_NAME`保留來自您 AWS 登入資料的 AWS 設定檔名稱 （移除此參數以使用預設設定檔）、 `QUEUE_URL` 是來自 AWS CDK 輸出的 **QueueUrl** 值，以及下列格式`MESSAGE`的 JSON 字串： <pre>{ "streamARN": "STREAM_ARN", "bucket": "BUCKET_NAME", "s3Directory": "test-output" }</pre>其中 `STREAM_ARN`是您在先前步驟中建立之影片串流的 ARN，而 `BUCKET_NAME`是來自 AWS CDK 輸出的**儲存貯**體值。 傳送此訊息會啟動影片處理。或者，您可以使用 Amazon SQS 主控台傳送訊息，如 [Amazon SQS 文件](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-using-send-messages.html)所述。 | 開發人員、DevOps 工程師 | 
| 檢視影片影格的影像。 | 您可以在 S3 輸出儲存貯體中看到產生的映像，`s3://BUCKET_NAME/test-output`其中 `BUCKET_NAME`是來自 AWS CDK 輸出的**儲存貯**體值。 | 開發人員、DevOps 工程師 | 

## 相關資源
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-resources"></a>
+ [AWS CDK 文件](https://docs.aws.amazon.com/cdk/latest/guide/home.html)
+ [AWS CDK API 參考](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html)
+ [AWS CDK 簡介研討會](https://cdkworkshop.com/)
+ [Amazon Kinesis Video Streams 文件](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/what-is-kinesis-video.html)
+ [範例：使用 SageMaker 識別影片串流中的物件](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-sagemaker.html)
+ [範例：剖析和轉譯 Kinesis Video Streams 片段](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-renderer.html)
+ [使用 Amazon Kinesis Video Streams 和 Amazon SageMaker 即時大規模分析即時影片 ](https://aws.amazon.com/blogs/machine-learning/analyze-live-video-at-scale-in-real-time-using-amazon-kinesis-video-streams-and-amazon-sagemaker/)(AWS Machine Learning 部落格文章）
+ [AWS Fargate 入門](https://aws.amazon.com/fargate/getting-started/)

## 其他資訊
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-additional"></a>

**選擇 IDE**

我們建議您使用最愛的 Java IDE 來建置和探索此專案。 

**清除**

執行完此範例後，請移除所有部署的資源，以避免產生額外的 AWS 基礎設施成本。 

若要移除基礎設施和影片串流，請在 AWS CLI 中使用這兩個命令：

```
cdk destroy --profile "$AWS_PROFILE_NAME" --all
```

```
aws kinesisvideo --profile "$AWS_PROFILE_NAME" delete-stream --stream-arn "$STREAM_ARN"
```

或者，您可以使用 AWS CloudFormation 主控台來移除 AWS CloudFormation 堆疊，以及使用 Kinesis 主控台來移除 Kinesis 影片串流，以手動方式移除資源。請注意， `cdk destroy`不會移除輸出 S3 儲存貯體或 Amazon Elastic Container Registry (Amazon ECR) 儲存庫 () 中的映像`aws-cdk/assets`。您必須手動移除它們。

## 附件
<a name="attachments-9d1442c2-f3ee-47fd-8cce-90d9206ce4d4"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/9d1442c2-f3ee-47fd-8cce-90d9206ce4d4/attachments/attachment.zip)

# 建置 ETL 服務管道，使用 AWS Glue 從 Amazon S3 遞增載入資料至 Amazon Redshift
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue"></a>

*Rohan Jamadagni 和 Arunabha Datta，Amazon Web Services*

## 總結
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-summary"></a>

此模式提供如何設定 Amazon Simple Storage Service (Amazon S3) 以實現最佳資料湖效能的指引，然後使用 AWS Glue，將增量資料變更從 Amazon S3 載入 Amazon Redshift。 

Amazon S3 中的來源檔案可以有不同的格式，包括逗號分隔值 (CSV)、XML 和 JSON 檔案。此模式說明如何使用 AWS Glue 將來源檔案轉換為成本最佳化和效能最佳化格式，例如 Apache Parquet。您可以直接從 Amazon Athena 和 Amazon Redshift Spectrum 查詢 Parquet 檔案。您也可以將 Parquet 檔案載入 Amazon Redshift、彙總它們，以及與消費者共用彙總資料，或使用 Amazon Quick Sight 視覺化資料。

## 先決條件和限制
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 具有正確權限且包含 CSV、XML 或 JSON 檔案的 S3 來源儲存貯體。

**假設**
+ CSV、XML 或 JSON 來源檔案已載入 Amazon S3，可從設定 AWS Glue 和 Amazon Redshift 的帳戶存取。
+ 如 [Amazon Redshift 文件](https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-S3.html)所述，遵循載入檔案、分割檔案、壓縮和使用資訊清單的最佳實務。
+ 來源檔案結構未變更。
+ 來源系統能夠遵循 Amazon S3 中定義的資料夾結構，將資料擷取至 Amazon S3。
+ Amazon Redshift 叢集跨越單一可用區域。（此架構是適當的，因為 AWS Lambda、AWS Glue 和 Amazon Athena 是無伺服器。) 為了實現高可用性，叢集快照會定期拍攝。

**限制**
+ 檔案格式僅限於 [ AWS Glue 目前支援的](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-format.html)檔案格式。
+ 不支援即時下游報告。

## Architecture
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-architecture"></a>

**來源技術堆疊**
+ 具有 CSV、XML 或 JSON 檔案的 S3 儲存貯體

**目標技術堆疊**
+ S3 資料湖 （具有分割 Parquet 檔案儲存）
+ Amazon Redshift

**目標架構**

![\[使用 AWS Glue 將增量變更從 Amazon S3 載入 Amazon Redshift 的架構。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/105b58ec-56c1-464a-8e69-f625360caa14/images/626aa365-e6e6-4874-a873-1c71adbe5306.png)


 

**資料流程**

![\[使用 AWS Glue 將增量變更從 Amazon S3 載入 Amazon Redshift 的資料流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/105b58ec-56c1-464a-8e69-f625360caa14/images/29569e48-9f2d-4f48-bc59-1f33949d01ca.png)


## 工具
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-tools"></a>
+ [Amazon S3](https://aws.amazon.com/s3/) – Amazon Simple Storage Service (Amazon S3) 是一種高度可擴展的物件儲存服務。Amazon S3 可用於各種儲存解決方案，包括網站、行動應用程式、備份和資料湖。
+ [AWS Lambda](https://aws.amazon.com/lambda/) – AWS Lambda 可讓您執行程式碼，而無需佈建或管理伺服器。AWS Lambda 是一種事件驅動的服務；您可以設定程式碼，以從其他 AWS 服務自動啟動。
+ [Amazon Redshift](https://aws.amazon.com/redshift/) – Amazon Redshift 是全受管的 PB 級資料倉儲服務。使用 Amazon Redshift，您可以使用標準 SQL 查詢資料倉儲和資料湖中數 PB 的結構化和半結構化資料。
+ [AWS Glue](https://aws.amazon.com/glue/) – AWS Glue 是一種全受管 ETL 服務，可讓您更輕鬆地準備和載入資料以進行分析。AWS Glue 會探索您的資料，並將相關聯的中繼資料 （例如資料表定義和結構描述） 存放在 AWS Glue Data Catalog 中。您的目錄資料可立即搜尋、查詢，並可用於 ETL。
+ [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) – AWS Secrets Manager 有助於保護和集中管理應用程式或服務存取所需的秘密。服務會存放資料庫登入資料、API 金鑰和其他秘密，無需以純文字格式硬式編碼敏感資訊。Secrets Manager 也提供金鑰輪換，以滿足安全和合規需求。它具有 Amazon Redshift、Amazon Relational Database Service (Amazon RDS) 和 Amazon DocumentDB 的內建整合。您可以使用 Secrets Manager 主控台、命令列界面 (CLI) 或 Secrets Manager API 和 SDKs 來存放和集中管理秘密。
+ [Amazon Athena](https://aws.amazon.com/athena/) – Amazon Athena 是一種互動式查詢服務，可讓您輕鬆分析存放在 Amazon S3 中的資料。Athena 無伺服器並與 AWS Glue 整合，因此可以直接查詢使用 AWS Glue 編目的資料。Athena 會彈性擴展以提供互動式查詢效能。

## 史詩
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-epics"></a>

### 建立 S3 儲存貯體和資料夾結構
<a name="create-the-s3-buckets-and-folder-structure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 分析來源系統的資料結構和屬性。 | 針對有助於 Amazon S3 資料湖的每個資料來源執行此任務。 | 資料工程師 | 
| 定義分割區和存取策略。 | 此策略應以資料擷取的頻率、差異處理和耗用需求為基礎。請確定 S3 儲存貯體未向公眾開放，且存取權僅由特定服務角色型政策控制。如需詳細資訊，請參閱 [Amazon S3 說明文件](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/using-folders.html)。 | 資料工程師 | 
| 為每個資料來源類型建立單獨的 S3 儲存貯體，並為處理過的 (Parquet) 資料為每個來源建立單獨的 S3 儲存貯體。 | 為每個來源建立單獨的儲存貯體，然後根據來源系統的資料擷取頻率建立資料夾結構，例如 `s3://source-system-name/date/hour`。對於已處理 （轉換為 Parquet 格式） 檔案，請建立類似的結構，例如 `s3://source-processed-bucket/date/hour`。如需建立 S3 儲存貯體的詳細資訊，請參閱 [Amazon S3 文件](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/create-bucket.html)。 | 資料工程師 | 

### 在 Amazon Redshift 中建立資料倉儲
<a name="create-a-data-warehouse-in-amazon-redshift"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用適當的參數群組以及維護和備份策略啟動 Amazon Redshift 叢集。 | 建立 Amazon Redshift 叢集時，針對管理員使用者憑證使用 Secrets Manager 資料庫秘密。如需有關建立和調整 Amazon Redshift 叢集大小的資訊，請參閱 [Amazon Redshift 文件](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/event-publishing-redshift-cluster.html)和[調整雲端資料倉儲大小](https://d1.awsstatic.com/whitepapers/Size-Cloud-Data-Warehouse-on-AWS.pdf)白皮書。 | 資料工程師 | 
| 建立 IAM 服務角色並將其連接至 Amazon Redshift 叢集。 | AWS Identity and Access Management (IAM) 服務角色可確保存取 Secrets Manager 和來源 S3 儲存貯體。如需詳細資訊，請參閱[授權](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html)和[新增角色](https://docs.aws.amazon.com/redshift/latest/dg/c-getting-started-using-spectrum-add-role.html)的 AWS 文件。 | 資料工程師 | 
| 建立資料庫結構描述。 | 遵循資料表設計的 Amazon Redshift 最佳實務。根據使用案例，選擇適當的排序和分佈索引鍵，以及最佳的壓縮編碼。如需最佳實務，請參閱 [AWS 文件](https://docs.aws.amazon.com/redshift/latest/dg/c_designing-tables-best-practices.html)。 | 資料工程師 | 
| 設定工作負載管理。 | 根據您的需求設定工作負載管理 (WLM) 佇列、短查詢加速 (SQA) 或並行擴展。如需詳細資訊，請參閱《Amazon Redshift 文件》中的[實作工作負載管理](https://docs.aws.amazon.com/redshift/latest/dg/cm-c-implementing-workload-management.html)。 | 資料工程師 | 

### 在 Secrets Manager 中建立秘密
<a name="create-a-secret-in-secrets-manager"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立新的秘密，將 Amazon Redshift 登入憑證存放在 Secrets Manager 中。 | 此秘密會存放管理員使用者以及個別資料庫服務使用者的登入資料。如需說明，請參閱 [Secrets Manager 文件](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)。選擇 **Amazon Redshift 叢集**做為秘密類型。此外，在**秘密輪換**頁面上，開啟輪換。這將在 Amazon Redshift 叢集中建立適當的使用者，並以定義的間隔輪換金鑰秘密。 | 資料工程師 | 
| 建立 IAM 政策以限制 Secrets Manager 存取。 | 限制 Secrets Manager 只能存取 Amazon Redshift 管理員和 AWS Glue。 | 資料工程師 | 

### 設定 AWS Glue
<a name="configure-aws-glue"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 AWS Glue Data Catalog 中，新增 Amazon Redshift 的連線。 | 如需說明，請參閱 [AWS Glue 文件](https://docs.aws.amazon.com/glue/latest/dg/console-connections.html)。 | 資料工程師 | 
| 建立並連接 IAM 服務角色，讓 AWS Glue 存取 Secrets Manager、Amazon Redshift 和 S3 儲存貯體。 | 如需詳細資訊，請參閱 [AWS Glue 文件](https://docs.aws.amazon.com/glue/latest/dg/create-service-policy.html)。 | 資料工程師 | 
| 定義來源的 AWS Glue Data Catalog。 | 此步驟涉及在 AWS Glue Data Catalog 中建立資料庫和所需的資料表。您可以使用爬蟲程式來編目 AWS Glue 資料庫中的資料表，或將其定義為 Amazon Athena 外部資料表。您也可以透過 AWS Glue Data Catalog 存取 Athena 中定義的外部資料表。如需在 Athena 中[定義 Data Catalog ](https://docs.aws.amazon.com/glue/latest/dg/populate-data-catalog.html)和[建立外部資料表](https://docs.aws.amazon.com/athena/latest/ug/creating-tables.html)的詳細資訊，請參閱 AWS 文件。 | 資料工程師 | 
| 建立 AWS Glue 任務來處理來源資料。 | AWS Glue 任務可以是 Python shell 或 PySpark，以標準化、刪除重複和清除來源資料檔案。若要最佳化效能並避免必須查詢整個 S3 來源儲存貯體，請依日期分割 S3 儲存貯體，並依年、月、日和小時細分，做為 AWS Glue 任務的下推述詞。如需詳細資訊，請參閱 [AWS Glue 文件](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-partitions.html)。將已處理和轉換的資料載入 Parquet 格式的已處理 S3 儲存貯體分割區。您可以從 Athena 查詢 Parquet 檔案。 | 資料工程師 | 
| 建立 AWS Glue 任務以將資料載入 Amazon Redshift。 | AWS Glue 任務可以是 Python shell 或 PySpark，透過維護資料載入資料，然後進行完整重新整理。如需詳細資訊，請參閱 [AWS Glue 文件](https://docs.aws.amazon.com/glue/latest/dg/author-job.html)和*其他資訊*一節。 | 資料工程師 | 
| （選用） 視需要使用觸發條件來排程 AWS Glue 任務。 | 增量資料載入主要是由導致 AWS Lambda 函數呼叫 AWS Glue 任務的 Amazon S3 事件所驅動。針對需要時間型而非事件型排程的任何資料載入，使用 AWS Glue 觸發型排程。 | 資料工程師 | 

### 建立 Lambda 函數
<a name="create-a-lambda-function"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立並連接 AWS Lambda 的 IAM 服務連結角色，以存取 S3 儲存貯體和 AWS Glue 任務。 | 為 AWS Lambda 建立 IAM 服務連結角色，其中包含讀取 Amazon S3 物件和儲存貯體的政策，以及存取 AWS Glue API 以啟動 AWS Glue 任務的政策。如需詳細資訊，請參閱 [知識中心](https://aws.amazon.com/premiumsupport/knowledge-center/lambda-execution-role-s3-bucket/)。 | 資料工程師 | 
| 建立 Lambda 函數，根據定義的 Amazon S3 事件執行 AWS Glue 任務。 | Lambda 函數應該透過建立 Amazon S3 資訊清單檔案來啟動。Lambda 函數應將 Amazon S3 資料夾位置 （例如 source\$1bucket/year/month/date/hour) 做為參數傳遞至 AWS Glue 任務。AWS Glue 任務會使用此參數做為下推述詞，以最佳化檔案存取和任務處理效能。如需詳細資訊，請參閱 [AWS Glue 文件](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-calling.html)。 | 資料工程師 | 
| 建立 Amazon S3 PUT 物件事件以偵測物件建立，並呼叫個別的 Lambda 函數。 | Amazon S3 PUT 物件事件只能透過建立資訊清單檔案來啟動。資訊清單檔案控制 Lambda 函數和 AWS Glue 任務並行，並以批次方式處理負載，而不是處理抵達 S3 來源儲存貯體特定分割區的個別檔案。如需詳細資訊，請參閱 [Lambda 文件](https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html)。 | 資料工程師 | 

## 相關資源
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-resources"></a>
+ [Amazon S3 文件](https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html)
+ [AWS Glue 文件](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html)
+ [Amazon Redshift 文件](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html)
+ [AWS Lambda](https://aws.amazon.com/lambda/)
+ [Amazon Athena](https://aws.amazon.com/athena/)
+ [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/)

## 其他資訊
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-additional"></a>

**upsert 和完整重新整理的詳細方法**

**Upsert**：這適用於需要歷史彙總的資料集，取決於業務使用案例。根據您的業務需求，遵循[更新和插入新資料](https://docs.aws.amazon.com/redshift/latest/dg/t_updating-inserting-using-staging-tables-.html) (Amazon Redshift 文件） 中所述的方法之一。

**完整重新整理**：這適用於不需要歷史彙總的小型資料集。請遵循下列其中一種方法：

1. 截斷 Amazon Redshift 資料表。

1. 從預備區域載入目前的分割區

或：

1. 使用目前的分割區資料建立暫存資料表。

1. 捨棄目標 Amazon Redshift 資料表。

1. 將暫存資料表重新命名為目標資料表。

# 使用 Amazon DataZone 建置企業資料網格 AWS CDK，以及 AWS CloudFormation
<a name="build-enterprise-data-mesh-amazon-data-zone"></a>

*Dhrubajyoti Mukherjee、Ravi Kumar、WeiORDER Sun 和 Adjoa Taylor，Amazon Web Services*

## 摘要
<a name="build-enterprise-data-mesh-amazon-data-zone-summary"></a>

在 Amazon Web Services (AWS) 上，客戶了解資料是加速企業創新和推動商業價值的關鍵。若要管理此大量資料，您可以採用分散式架構，例如資料網格。資料網格架構可促進產品思維，這是一種將客戶、目標和市場納入考量的思維方式。資料網格也有助於建立聯合控管模型，以快速、安全地存取您的資料。

[在 上建置資料網格型企業解決方案的策略 AWS](https://docs.aws.amazon.com/prescriptive-guidance/latest/strategy-data-mesh/introduction.html)討論了如何使用資料網格策略架構來為您的組織制定和實作資料網格策略。透過使用資料網格策略架構，您可以最佳化團隊組織及其互動，以加速您的資料網格之旅。

本文件提供如何使用 [Amazon DataZone](https://docs.aws.amazon.com/datazone/latest/userguide/what-is-datazone.html) 建置企業資料網格的指引。Amazon DataZone 是一種資料管理服務，用於編目 AWS、探索、共用和管理跨內部部署和第三方來源存放的資料。模式包含程式碼成品，可協助您使用 AWS Cloud Development Kit (AWS CDK) 和 部署資料網格型資料解決方案基礎設施 AWS CloudFormation。此模式適用於雲端架構師和 DevOps 工程師。

如需此模式目標和解決方案範圍的相關資訊，請參閱[其他資訊](#build-enterprise-data-mesh-amazon-data-zone-additional)一節。

## 先決條件和限制
<a name="build-enterprise-data-mesh-amazon-data-zone-prereqs"></a>

**先決條件**
+ 至少兩個作用中 AWS 帳戶：一個用於中央控管帳戶，另一個用於成員帳戶
+ AWS 開發環境中中央控管帳戶的管理員登入資料
+ AWS Command Line Interface AWS 服務 安裝 [https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (AWS CLI) 從命令列管理
+ 安裝 Node.js 和 Node Package Manager (npm) [https://docs.npmjs.com/downloading-and-installing-node-js-and-npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)來管理 AWS CDK 應用程式
+ AWS CDK 使用 npm 在開發環境中全域[安裝](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install)的工具組，以合成和部署 AWS CDK 應用程式

  ```
  npm install -g aws-cdk
  ```
+ 安裝在開發環境中的 Python 3.12 版
+ 安裝在開發環境中或使用 npm 編譯器全域安裝的 TypeScript：

  ```
  npm install -g typescript
  ```
+ 安裝在開發環境中的 Docker
+ 版本控制系統，例如 Git，以維護解決方案的原始程式碼 （建議）
+ 支援 Python 和 TypeScript 的整合式開發環境 (IDE) 或文字編輯器 （強烈建議）

**限制**
+ 解決方案僅在執行 Linux 或 macOS 的機器上進行測試。
+ 在目前版本中，解決方案 AWS IAM Identity Center 預設不支援 Amazon DataZone 和 的整合。不過，您可以將其設定為支援此整合。

**產品版本**
+ Python 3.12 版

## Architecture
<a name="build-enterprise-data-mesh-amazon-data-zone-architecture"></a>

下圖顯示資料網格參考架構。架構是以 Amazon DataZone 為基礎，並使用 Amazon Simple Storage Service (Amazon S3) 和 AWS Glue Data Catalog 作為資料來源。根據組織的需求， AWS 服務 您在資料網格實作中與 Amazon DataZone 搭配使用的 可能會有所不同。

![\[成員帳戶和中央控管帳戶的五個步驟工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/79056dd9-e669-4302-afb8-21e3e0e8a136/images/eacbffca-4f25-405a-a7c8-f89d0fee5682.png)


1. 在生產者帳戶中，原始資料適合目前形式的取用，或使用 進行轉換以供取用 AWS Glue。資料的技術中繼資料存放在 Amazon S3 中，並使用 AWS Glue 資料爬蟲程式進行評估。使用 Data Quality 測量資料[AWS Glue 品質](https://docs.aws.amazon.com/glue/latest/dg/glue-data-quality.html)。Data Catalog 中的來源資料庫會註冊為 Amazon DataZone 目錄中的資產。Amazon DataZone 目錄使用 Amazon DataZone 資料來源任務託管在中央控管帳戶中。

1. 中央控管帳戶託管 Amazon DataZone 網域和 Amazon DataZone 資料入口網站。資料生產者和消費者 AWS 帳戶 的 與 Amazon DataZone 網域相關聯。資料生產者和消費者的 Amazon DataZone 專案是以對應的 Amazon DataZone 網域單位組織。

1. 資料資產的最終使用者使用其 AWS Identity and Access Management (IAM) 登入資料或單一登入 （透過 IAM Identity Center 整合） 登入 Amazon DataZone 資料入口網站。它們會在 Amazon DataZone 資料目錄中搜尋、篩選和檢視資產資訊 （例如，資料品質資訊或業務和技術中繼資料）。

1. 最終使用者找到所需的資料資產後，他們會使用 Amazon DataZone 訂閱功能來請求存取。生產者團隊的資料擁有者會收到通知，並在 Amazon DataZone 資料入口網站中評估訂閱請求。資料擁有者會根據訂閱請求的有效性來核准或拒絕訂閱請求。

1. 授予並履行訂閱請求後，會在消費者帳戶中存取資產以進行下列活動：
   + 使用 Amazon SageMaker AI 開發 AI/ML 模型
   + 使用 Amazon Athena 和 Amazon Quick 進行分析和報告

## 工具
<a name="build-enterprise-data-mesh-amazon-data-zone-tools"></a>

**AWS 服務**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon Simple Storage Service (Amazon S3) 中分析資料。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端 基礎設施。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。
+ [Amazon DataZone](https://docs.aws.amazon.com/datazone/latest/userguide/what-is-datazone.html) 是一項資料管理服務，可協助您編目、探索、共用和控管跨 AWS、內部部署和第三方來源存放的資料。
+ [Amazon Quick](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) 是一種雲端規模的商業智慧 (BI) 服務，可協助您在單一儀表板中視覺化、分析和報告您的資料。
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/?id=docs_gateway) 是一種受管機器學習 (ML) 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供安全、耐用且可用的託管佇列，可協助您整合和分離分散式軟體系統和元件。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**程式碼儲存庫**

解決方案可在 GitHub [data-mesh-datazone-cdk-cloudformation](https://github.com/aws-samples/data-mesh-datazone-cdk-cloudformation) 儲存庫中使用。

## 史詩
<a name="build-enterprise-data-mesh-amazon-data-zone-epics"></a>

### 設定環境
<a name="set-up-the-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要複製儲存庫，請在本機開發環境 (Linux 或 macOS) 中執行下列命令：<pre>git clone https://github.com/aws-samples/data-mesh-datazone-cdk-cloudformation</pre> | 雲端架構師、DevOps 工程師 | 
| 建立環境。 | 若要建立 Python 虛擬環境，請執行下列命令：<pre> python3 -m venv .venv<br /> source .venv/bin/activate<br /> pip install -r requirements.txt</pre> | 雲端架構師、DevOps 工程師 | 
| 引導帳戶。 | 若要使用 引導中央控管帳戶 AWS CDK，請執行下列命令：<pre>cdk bootstrap aws://<GOVERNANCE_ACCOUNT_ID>/<AWS_REGION></pre>登入 AWS 管理主控台，開啟中央控管帳戶主控台，並取得 AWS CDK 執行角色的 Amazon Resource Name (ARN)。 | 雲端架構師、DevOps 工程師 | 
| 建構 `DzDataMeshMemberStackSet.yaml` 檔案。 | 若要建構`DzDataMeshMemberStackSet.yaml`檔案，請從儲存庫的根目錄啟動下列 bash 指令碼：<pre>./lib/scripts/create_dz_data_mesh_member_stack_set.sh</pre> | 雲端架構師、DevOps 工程師 | 
| 確認範本建立。 | 確定 CloudFormation 範本檔案是在 `lib/cfn-templates/DzDataMeshMemberStackSet.yaml`位置建立的。 | 雲端架構師、DevOps 工程師 | 

### 在中央控管帳戶中部署資源
<a name="deploy-resources-in-the-central-governance-account"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 修改組態。 | 在 `config/Config.ts`檔案中，修改下列參數：<pre>DZ_APPLICATION_NAME - Name of the application.<br />DZ_STAGE_NAME - Name of the stage. <br />DZ_DOMAIN_NAME - Name of the Amazon DataZone domain<br />DZ_DOMAIN_DESCRIPTION - Description of the Amazon DataZone domain<br />DZ_DOMAIN_TAG - Tag of the Amazon DataZone domain<br />DZ_ADMIN_PROJECT_NAME - Name of the Amazon DataZone project for administrators<br />DZ_ADMIN_PROJECT_DESCRIPTION - Description of the Amazon DataZone project for administrators<br />CDK_EXEC_ROLE_ARN - ARN of the cdk execution role<br />DZ_ADMIN_ROLE_ARN - ARN of the administrator role</pre>將剩餘的參數保留空白。 | 雲端架構師、DevOps 工程師 | 
| 更新 Amazon DataZone 詞彙表組態。 | 若要更新 `lib/utils/glossary_config.json` 檔案中的 Amazon DataZone 詞彙表組態，請使用下列範例組態：<pre>{<br />    "GlossaryName": "PII Data",<br />    "GlossaryDescription": "If data source contains PII attributes",<br />    "GlossaryTerms": [{<br />            "Name": "Yes",<br />            "ShortDescription": "Yes",<br />            "LongDescription": "Yes Glossary Term"<br />        },<br />        {<br />            "Name": "No",<br />            "ShortDescription": "No",<br />            "LongDescription": "No Glossary Term"<br />        }<br />    ]<br />}</pre> | 雲端架構師、DevOps 工程師 | 
| 更新 Amazon DataZone 中繼資料表單組態。 | 若要更新 中的 Amazon DataZone 中繼資料表單組態`lib/utils/metadata_form_config.json file`，請使用下列範例組態：<pre>{<br />    "FormName": "ScheduleDataRefresh",<br />    "FormDescription": "Form for data refresh schedule",<br />    "FormSmithyModel": "@amazon.datazone#displayname(defaultName: \"Data Refresh Schedule\")\nstructure ScheduleDataRefresh {\n    @documentation(\"Schedule of Data Refresh\")\n    @required\n    @amazon.datazone#searchable\n    @amazon.datazone#displayname(defaultName: \"Data Refresh Schedule\")\n    data_refresh_schedule: String\n}"<br />}</pre> | 雲端架構師、DevOps 工程師 | 
| 匯出 AWS 登入資料。 | 若要使用管理許可將 AWS 登入資料匯出至 IAM 角色的開發環境，請使用下列格式：<pre>export AWS_ACCESS_KEY_ID=<br />export AWS_SECRET_ACCESS_KEY=<br />export AWS_SESSION_TOKEN=</pre> | 雲端架構師、DevOps 工程師 | 
| 合成範本。 | 若要合成 CloudFormation 範本，請執行下列命令：<pre>npx cdk synth</pre> | 雲端架構師、DevOps 工程師 | 
| 部署解決方案。 | 若要部署解決方案，請執行下列命令：<pre>npx cdk deploy --all</pre> | 雲端架構師、DevOps 工程師 | 

### 設定新的成員帳戶
<a name="configure-new-member-accounts"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 範本。 | 使用下列輸入參數部署位於成員帳戶中 `lib/cfn-templates/DzDataMeshCfnStackSetExecutionRole.yaml`的 CloudFormation 範本： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 雲端架構師、DevOps 工程師 | 
| 更新 ARNs。 | 若要更新成員帳戶的 CloudFormation StackSet 執行角色 ARNs清單，請使用下列程式碼：<pre>DZ_MEMBER_STACK_SET_EXEC_ROLE_LIST  - List of Stack set execution role arns for the member accounts.</pre> | 雲端架構師、DevOps 工程師 | 
| 合成和部署。 | 若要合成 CloudFormation 範本並部署解決方案，請執行下列命令：<pre>npx cdk synth<br />npx cdk deploy --all</pre> | 雲端架構師、DevOps 工程師 | 
| 關聯成員帳戶。 | 若要將成員帳戶與中央控管帳戶建立關聯，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 雲端架構師、DevOps 工程師 | 
| 更新參數。 | 若要更新 組態檔案中的成員帳戶特定參數`config/Config.ts`，請使用下列格式：<pre>export const DZ_MEMBER_ACCOUNT_CONFIG: memberAccountConfig = {<br />  '123456789012' : {<br />    PROJECT_NAME: 'TEST-PROJECT-123456789012',<br />    PROJECT_DESCRIPTION: 'TEST-PROJECT-123456789012',<br />    PROJECT_EMAIL: 'user@xyz.com'<br />  }<br />}</pre> | 雲端架構師、DevOps 工程師 | 
| 合成和部署範本。 | 若要合成 CloudFormation 範本並部署解決方案，請執行下列命令：<pre>npx cdk synth<br />npx cdk deploy --all</pre> | 雲端架構師、DevOps 工程師 | 
| 新增成員帳戶。 | 若要在資料解決方案中建立和設定其他成員帳戶，請為每個成員帳戶重複上述步驟。此解決方案不會區分資料生產者和消費者。 | 雲端架構師、DevOps 工程師 | 

### 清除
<a name="clean-up"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 取消成員帳戶的關聯。 | 若要取消帳戶關聯，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 雲端架構師、DevOps 工程師 | 
| 刪除堆疊執行個體。 | 若要刪除 CloudFormation 堆疊執行個體，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 雲端架構師、DevOps 工程師 | 
| 銷毀所有資源。 | 若要銷毀資源，請在本機開發環境 (Linux 或 macOS) 中實作下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 雲端架構師、DevOps 工程師 | 

## 相關資源
<a name="build-enterprise-data-mesh-amazon-data-zone-resources"></a>
+ [Amazon DataZone AWS Glue 資料快速入門](https://docs.aws.amazon.com/datazone/latest/userguide/quickstart-glue.html)
+ [教學課程：建立您的第一個 AWS CDK 應用程式](https://docs.aws.amazon.com/cdk/v2/guide/hello_world.html)
+ [入門 CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/GettingStarted.html)
+ [在 上建置資料網格型企業解決方案的策略 AWS](https://docs.aws.amazon.com/prescriptive-guidance/latest/strategy-data-mesh/introduction.html)

## 其他資訊
<a name="build-enterprise-data-mesh-amazon-data-zone-additional"></a>

**目標**

實作此模式可達成下列目標：
+ **分散式資料擁有權**：將資料擁有權從中央團隊轉移到代表組織來源系統、業務單位或使用案例的團隊。
+ **產品思維** ‒ 在考慮組織中的資料資產時，引進以產品為基礎的思維，其中包括客戶、市場和其他因素。
+ **聯合控管** ‒ 改善整個組織資料產品的安全防護機制、控制和合規性。
+ **多帳戶和多專案支援** ‒ 支援跨組織業務單位或專案的高效、安全的資料共用和協作。
+ **集中監控和通知** ‒ 使用 Amazon CloudWatch 監控資料網格的雲端資源，並在新成員帳戶相關聯時通知使用者。
+ **可擴展性和可擴展性** ‒ 隨著組織發展，將新的使用案例新增至資料網格。

**解決方案範圍**

當您使用此解決方案時，您可以啟動小型 並隨著資料網格旅程的進展進行擴展。通常，當成員帳戶採用資料解決方案時，它包含組織、專案或業務單位特定的帳戶組態。此解決方案支援下列功能，以容納這些不同的 AWS 帳戶 組態：
+ AWS Glue Data Catalog 作為 Amazon DataZone 的資料來源
+ Amazon DataZone 資料網域和相關資料入口網站的管理
+ 在資料網格型資料解決方案中新增成員帳戶的管理
+ Amazon DataZone 專案和環境的管理
+ Amazon DataZone 詞彙表和中繼資料表單的管理
+ 與資料網格型資料解決方案使用者對應的 IAM 角色管理
+ 資料網格型資料解決方案使用者的通知
+ 監控佈建的雲端基礎設施

  此解決方案使用 AWS CDK 和 CloudFormation 部署雲端基礎設施。它使用 CloudFormation 執行下列動作：
  + 在較低的抽象層級定義和部署雲端資源。
  + 從 部署雲端資源 AWS 管理主控台。透過使用此方法，您可以在沒有開發環境的情況下部署基礎設施。

  資料網格解決方案使用 在較高的抽象層級 AWS CDK 定義資源。因此，解決方案透過選擇部署雲端資源的相關工具，提供解耦、模組化和可擴展的方法。

**後續步驟**

您可以聯絡 AWS[專家](https://aws.amazon.com/professional-services)，以取得使用 Amazon DataZone 建置資料網格 的指引。

此解決方案的模組化性質支援使用不同的架構來建置資料管理解決方案，例如資料結構和資料湖。此外，根據您的組織需求，您可以將解決方案擴展到其他 Amazon DataZone 資料來源。

# 使用 AWS 服務計算風險值 (VaR)
<a name="calculate-value-at-risk-var-by-using-aws-services"></a>

*Sumon Samanta，Amazon Web Services*

## 總結
<a name="calculate-value-at-risk-var-by-using-aws-services-summary"></a>

此模式說明如何使用 AWS 服務實作風險值 (VaR) 計算系統。在內部部署環境中，大多數 VaR 系統使用大型的專用基礎設施，以及內部或商業網格排程軟體來執行批次程序。此模式提供簡單、可靠且可擴展的架構，以處理 AWS 雲端中的 VaR 處理。其建置的無伺服器架構使用 Amazon Kinesis Data Streams 做為串流服務、Amazon Simple Queue Service (Amazon SQS) 做為受管佇列服務、Amazon ElastiCache 做為快取服務，以及 AWS Lambda 來處理訂單和計算風險。

VaR 是交易者和風險經理用來估計其產品組合中潛在損失超出特定可信度水準的統計指標。大多數 VaR 系統涉及執行大量數學和統計計算並儲存結果。這些計算需要大量的運算資源，因此 VaR 批次程序必須分成較小的運算任務集。您可以將大型批次分割為較小的任務，因為這些任務大部分是獨立的 （也就是說，一個任務的計算不會依賴其他任務）。 

VaR 架構的另一個重要需求是運算可擴展性。此模式使用無伺服器架構，可根據運算負載自動縮減或縮減規模。由於批次或線上運算需求難以預測，因此需要動態擴展才能在服務層級協議 (SLA) 規定的時間內完成程序。此外，成本最佳化架構應該能夠在該資源上的任務完成後，立即縮減每個運算資源。 

AWS 服務非常適合 VaR 計算，因為它們提供可擴展的運算和儲存容量、以成本最佳化的方式處理的分析服務，以及執行風險管理工作流程的不同類型排程器。此外，您只需為在 AWS 上使用的運算和儲存資源付費。

## 先決條件和限制
<a name="calculate-value-at-risk-var-by-using-aws-services-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 輸入檔案，這取決於您的業務需求。典型的使用案例包含下列輸入檔案：
  + 市場資料檔案 （輸入至 VaR 計算引擎）
  + 交易資料檔案 （除非交易資料透過串流）。
  + 組態資料檔案 （模型和其他靜態組態資料）
  + 計算引擎模型檔案 （定量程式庫）
  + 時間序列資料檔案 （適用於歷史資料，例如過去五年的股票價格）
+ 如果市場資料或其他輸入透過串流傳入、Amazon Kinesis Data Streams 設定，以及設定為寫入串流的 Amazon Identity and Access Management (IAM) 許可。 

此模式會建置一種架構，其中交易資料會從交易系統寫入 Kinesis 資料串流。您可以不使用串流服務，將交易資料儲存在小型批次檔案中、將其存放在 Amazon Simple Storage Service (Amazon S3) 儲存貯體中，並叫用事件以開始處理資料。

**限制**
+ 每個碎片都保證 Kinesis 資料串流排序，因此寫入多個碎片的交易訂單不保證會以與寫入操作相同的順序交付。
+ AWS Lambda 執行時間限制目前為 15 分鐘。（如需詳細資訊，請參閱 [Lambda 常見問答集](https://aws.amazon.com/lambda/faqs/)。)

## Architecture
<a name="calculate-value-at-risk-var-by-using-aws-services-architecture"></a>

**目標架構**

下列架構圖顯示風險評估系統的 AWS 服務和工作流程。

![\[使用 AWS 服務的 VaR 計算系統\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/eb615fc5-3cc3-445a-af2c-8446ee7b5276/images/c60aec03-ff6c-410c-8ee8-f1f6efa22cf7.png)


此圖展示了以下要點：

1. 從訂單管理系統傳入交易串流。

1. *票證位置網路 Lambda* 函數會處理訂單，並將每個刻度的合併訊息寫入 Amazon SQS 中的風險佇列。

1. *風險計算引擎* Lambda 函數會處理來自 Amazon SQS 的訊息、執行風險計算，以及更新 Amazon ElastiCache 風險快取中的 VaR 損益 (PnL) 資訊。

1. *讀取 ElastiCache 資料* Lambda 函數會從 ElastiCache 擷取風險結果，並將其存放在資料庫和 S3 儲存貯體中。

如需這些服務和步驟的詳細資訊，請參閱 *Epics* 一節。

**自動化和擴展**

您可以使用 AWS Cloud Development Kit (AWS CDK) 或 AWS CloudFormation 範本來部署整個架構。架構可以同時支援批次處理和當日 （即時） 處理。

擴展內建於 架構中。隨著更多交易寫入 Kinesis 資料串流並等待處理，可以叫用其他 Lambda 函數來處理這些交易，然後在處理完成後縮減規模。透過多個 Amazon SQS 風險計算佇列進行處理也是一個選項。如果需要跨佇列嚴格排序或整合，則無法平行處理。不過，對於end-of-the-day批次或迷你當日批次，Lambda 函數可以平行處理並將最終結果存放在 ElastiCache 中。 

## 工具
<a name="calculate-value-at-risk-var-by-using-aws-services-tools"></a>

** AWS 服務**
+ [Amazon Aurora MySQL 相容版本](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraMySQL.html)是完全受管的 MySQL 相容關聯式資料庫引擎，可協助您設定、操作和擴展 MySQL 部署。此模式使用 MySQL 做為範例，但您可以使用任何 RDBMS 系統來存放資料。
+ [Amazon ElastiCache](https://docs.aws.amazon.com/elasticache/) 可協助您在 AWS 雲端中設定、管理和擴展分散式記憶體內快取環境。
+ [Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) 可協助您即時收集和處理大型資料記錄串流。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供安全、耐用且可用的託管佇列，可協助您整合和分離分散式軟體系統和元件。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**Code**

此模式為 AWS 雲端中的 VaR 系統提供範例架構，並說明如何使用 Lambda 函數進行 VaR 計算。若要建立 Lambda 函數，請參閱 [Lambda 文件](https://docs.aws.amazon.com/lambda/latest/dg/service_code_examples.html)中的程式碼範例。如需協助，請聯絡 [AWS Professional Services](https://pages.awscloud.com/AWS-Professional-Services.html)。

## 最佳實務
<a name="calculate-value-at-risk-var-by-using-aws-services-best-practices"></a>
+ 讓每個 VaR 運算任務盡可能小且輕量。在每個運算任務中實驗不同數量的交易，以查看哪個交易最適合運算時間和成本。
+ 在 Amazon ElastiCache 中存放可重複使用的物件。使用 Apache Arrow 等架構來減少序列化和還原序列化。
+ 考慮 Lambda 的時間限制。如果您認為運算任務可能超過 15 分鐘，請嘗試將其分解為較小的任務，以避免 Lambda 逾時。如果無法做到這一點，您可能會考慮使用 AWS Fargate、Amazon Elastic Container Service (Amazon ECS) 和 Amazon Elastic Kubernetes Service (Amazon EKS) 的容器協同運作解決方案。

## 史詩
<a name="calculate-value-at-risk-var-by-using-aws-services-epics"></a>

### 交易流程到風險系統
<a name="trade-flow-to-risk-system"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 開始撰寫交易。 | 新的、已結清或部分結清的交易會從訂單管理系統寫入風險串流。此模式使用 Amazon Kinesis 作為受管串流服務。交易訂單代號的雜湊用於跨多個碎片下達交易訂單。 | Amazon Kinesis | 

### 執行 Lambda 函數以進行訂單處理
<a name="run-lambda-functions-for-order-processing"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 Lambda 開始處理風險。 | 為新訂單執行 AWS Lambda 函數。根據待定交易訂單的數量，Lambda 會自動擴展。每個 Lambda 執行個體都有一或多個訂單，並從 Amazon ElastiCache 擷取每個代號的最新位置。（您可以使用其他金融衍生產品的 CUSIP ID、曲線名稱或索引名稱做為金鑰，以存放並從 ElasticCache.) 在 ElastiCache 中，每個刻度的總位置 （數量） 和鍵值對 <*ticker*， *net position*>，其中 *net position* 是擴展係數，都會更新一次。  | Amazon Kinesis、AWS Lambda、Amazon ElastiCache | 

### 將每個標記的訊息寫入佇列
<a name="write-messages-for-each-ticker-into-queue"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將合併的訊息寫入風險佇列。 | 將訊息寫入佇列。此模式使用 Amazon SQS 做為受管佇列服務。單一 Lambda 執行個體可能在任何指定時間取得一批迷你交易訂單，但只會將每個代號的單一訊息寫入 Amazon SQS。系統會計算擴展係數： (*舊的淨位置* \$1 *目前位置*) / *舊的淨位置*。 | Amazon SQS、AWS Lambda | 

### 叫用風險引擎
<a name="invoke-risk-engine"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 開始風險計算。 | 叫用風險引擎 Lambda 的 Lambda 函數。每個位置都由單一 Lambda 函數處理。不過，為了最佳化目的，每個 Lambda 函數都可以處理來自 Amazon SQS 的多個訊息。 | Amazon SQS、AWS Lambda | 

### 從快取擷取風險結果
<a name="retrieve-risk-results-from-cache"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 擷取和更新風險快取。 | Lambda 會從 ElastiCache 擷取每個刻度的目前網路位置。它也會從 ElastiCache 擷取每個刻度的 VaR 損益 (PnL) 陣列。 如果 PnL 陣列已存在，Lambda 函數會使用 比例更新陣列和 VaR，該比例來自網路 Lambda 函數寫入的 Amazon SQS 訊息。如果 PnL 陣列不在 ElasticCache 中，則會使用模擬股票代號價格序列資料來計算新的 PnL 和 VaR。 | Amazon SQS、AWS Lambda、Amazon ElastiCache | 

### 更新 Elastic Cache 中的資料並存放在資料庫中
<a name="update-data-in-elastic-cache-and-store-in-database"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 存放風險結果。 | 在 ElastiCache 中更新 VaR 和 PnL 號碼後，每五分鐘會叫用新的 Lambda 函數。此函數會從 ElastiCache 讀取所有儲存的資料，並將其存放在 Aurora MySQL 相容資料庫和 S3 儲存貯體中。 | AWS Lambda、Amazon ElastiCache | 

## 相關資源
<a name="calculate-value-at-risk-var-by-using-aws-services-resources"></a>
+ [Basel VaR 架構](https://www.bis.org/basel_framework/chapter/DIS/50.htm)

# 使用 Amazon Athena 設定共用 AWS Glue Data Catalog 的跨帳戶存取權
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena"></a>

*Denis Avdonin，Amazon Web Services*

## 總結
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-summary"></a>

此模式提供step-by-step指示，包括 AWS Identity and Access Management (IAM) 政策範例，以使用 AWS Glue Data Catalog 設定存放在 Amazon Simple Storage Service (Amazon S3) 儲存貯體中之資料集的跨帳戶共用。您可以將資料集存放在 S3 儲存貯體中。中繼資料是由 AWS Glue 爬蟲程式收集，並放入 AWS Glue Data Catalog。S3 儲存貯體和 AWS Glue Data Catalog 位於稱為*資料帳戶的 AWS 帳戶中*。您可以為另一個稱為*消費者*帳戶的 AWS 帳戶中的 IAM 主體提供存取權。使用者可以使用 Amazon Athena 無伺服器查詢引擎來查詢消費者帳戶中的資料。

## 先決條件和限制
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-prereqs"></a>

**先決條件**
+ 兩個作用中[的 AWS 帳戶](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html)
+ 其中一個 AWS 帳戶中的 [S3 儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)體
+ [Athena 引擎版本 2](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference.html#engine-versions-reference-0002)
+ 安裝[https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) AWS Command Line Interface (AWS CLI) （或執行 [AWS CLI 命令的 AWS CloudShell](https://aws.amazon.com/cloudshell/))

**產品版本**

此模式僅適用於 [Athena 引擎版本 2](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference-0002.html) 和 [Athena 引擎版本 3](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference-0003.html)。我們建議您升級至 Athena 引擎版本 3。如果您無法從 Athena 引擎版本 1 升級到 Athena 引擎版本 3，請遵循 [AWS 大數據部落格中跨帳戶 AWS Glue Data Catalog 存取 Amazon Athena](https://aws.amazon.com/blogs/big-data/cross-account-aws-glue-data-catalog-access-with-amazon-athena/) 中討論的方法。

## Architecture
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-architecture"></a>

**目標技術堆疊**
+ Amazon Athena
+ Amazon Simple Storage Service (Amazon S3)
+ AWS Glue
+ AWS Identity and Access Management (IAM)
+ AWS Key Management Service (AWS KMS)

下圖顯示透過 AWS Glue Data Catalog，使用 IAM 許可將某個 AWS 帳戶 （資料帳戶） 中 S3 儲存貯體中的資料與另一個 AWS 帳戶 （消費者帳戶） 共用的架構。 AWS Glue 

![\[使用 AWS Glue Data Catalog 在資料帳戶與消費者帳戶之間共用 S3 儲存貯體中的資料集。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/4ee1d6f5-f8e1-4acb-8a9c-7601c832a87d/images/e73a2b47-c0b1-49f1-be66-9c563c11c9f9.png)


該圖顯示以下工作流程：

1. 資料帳戶中的 S3 儲存貯體政策會將許可授予取用者帳戶中的 IAM 角色，以及授予資料帳戶中的 AWS Glue 爬蟲程式服務角色。

1. 資料帳戶中的 AWS KMS 金鑰政策會將許可授予取用者帳戶中的 IAM 角色，以及授予資料帳戶中的 AWS Glue 爬蟲程式服務角色。

1. 資料帳戶中的 AWS Glue 爬蟲程式會探索存放在 S3 儲存貯體中的資料結構描述。

1. 資料帳戶中 AWS Glue Data Catalog 的資源政策會授予取用者帳戶中 IAM 角色的存取權。

1. 使用者使用 AWS CLI 命令，在消費者帳戶中建立具名目錄參考。

1. IAM 政策會授予取用者帳戶中的 IAM 角色對資料帳戶中資源的存取權。IAM 角色的信任政策允許取用者帳戶中的使用者擔任 IAM 角色。

1. 取用者帳戶中的使用者會擔任 IAM 角色，並使用 SQL 查詢存取資料目錄中的物件。

1.  Athena 無伺服器引擎會執行 SQL 查詢。

**注意**  
[IAM 最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)建議您將許可授予 IAM 角色，並使用[聯合身分](https://aws.amazon.com/identity/federation/)。

## 工具
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-tools"></a>
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon S3 中分析資料。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是全受管的擷取、轉換和載入 (ETL) 服務。它可協助您可靠地分類、清理、擴充和移動資料存放區和資料串流之間的資料。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 可透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可協助您建立和控制密碼編譯金鑰，以保護資料。

## 史詩
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-epics"></a>

### 在資料帳戶中設定許可
<a name="set-up-permissions-in-the-data-account"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 授予對 S3 儲存貯體中資料的存取權。 | 根據下列範本[建立 anS3bucket 政策](https://docs.aws.amazon.com/AmazonS3/latest/userguide/add-bucket-policy.html)，並將政策指派給儲存資料的儲存貯體。<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Principal": {<br />                "AWS": [<br />                     "arn:aws:iam::<consumer account id>:role/<role name>",<br />                     "arn:aws:iam::<data account id>:role/service-role/AWSGlueServiceRole-data-bucket-crawler"<br />                ]<br />            },<br />            "Action": "s3:GetObject",<br />            "Resource": "arn:aws:s3:::data-bucket/*"<br />        },<br />        {<br />            "Effect": "Allow",<br />            "Principal": {<br />                "AWS": [<br />                      "arn:aws:iam::<consumer account id>:role/<role name>",<br />                      "arn:aws:iam::<data account id>:role/service-role/AWSGlueServiceRole-data-bucket-crawler"<br />                ]<br />            },<br />            "Action": "s3:ListBucket",<br />            "Resource": "arn:aws:s3:::data-bucket"<br />        }<br />    ]<br />}</pre>儲存貯體政策會授予許可給取用者帳戶中的 IAM 角色，以及資料帳戶中的 AWS Glue 爬蟲程式服務角色。 | 雲端管理員 | 
| （如果需要） 授予資料加密金鑰的存取權。 | 如果 S3 儲存貯體是由 AWS KMS 金鑰加密，請將金鑰的`kms:Decrypt`許可授予取用者帳戶中的 IAM 角色，以及授予資料帳戶中的 AWS Glue 爬蟲程式服務角色。使用下列陳述式更新[金鑰政策](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)：<pre>{<br />    "Effect": "Allow",<br />    "Principal": {<br />        "AWS": [<br />            "arn:aws:iam::<consumer account id>:role/<role name>",<br />            "arn:aws:iam::<data account id>:role/service-role/AWSGlueServiceRole-data-bucket-crawler"<br />        ]<br />    },<br />    "Action": "kms:Decrypt",<br />    "Resource": "arn:aws:kms:<region>:<data account id>:key/<key id>"<br />}</pre> | 雲端管理員 | 
| 授予爬蟲程式對資料的存取權。 | 將下列 IAM 政策連接至爬蟲程式的服務角色：<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Action": "s3:GetObject",<br />            "Resource": "arn:aws:s3:::data-bucket/*"<br />        },<br />        {<br />            "Effect": "Allow",<br />            "Action": "s3:ListBucket",<br />            "Resource": "arn:aws:s3:::data-bucket"<br />        }<br />    ]<br />} </pre> | 雲端管理員 | 
| （如果需要） 授予爬蟲程式對資料加密金鑰的存取權。 | 如果 S3 儲存貯體是由 AWS KMS 金鑰加密，請將下列政策連接至爬蟲程式的服務角色，以授予金鑰的`kms:Decrypt`許可：<pre>{<br />    "Effect": "Allow",<br />    "Action": "kms:Decrypt",<br />    "Resource": "arn:aws:kms:<region>:<data account id>:key/<key id>"<br />}</pre> | 雲端管理員 | 
| 授予取用者帳戶中的 IAM 角色和爬蟲程式對資料目錄的存取權。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena.html)<pre>{<br />    "Version" : "2012-10-17",<br />    "Statement" : [ <br />        {<br />            "Effect" : "Allow",<br />            "Principal" : {<br />                "AWS" : [<br />                     "arn:aws:iam::<consumer account id>:role/<role name>",<br />                    "arn:aws:iam::<data account id>:role/service-role/AWSGlueServiceRole-data-bucket-crawler"<br />                ]<br />            },<br />            "Action" : "glue:*",<br />            "Resource" : [ <br />                 "arn:aws:glue:<region>:<data account id>:catalog", <br />                 "arn:aws:glue:<region>:<data account id>:database/*", <br />                 "arn:aws:glue:<region>:<data account id>:table/*" <br />            ]<br />        } <br />    ]<br />}</pre>此政策允許資料帳戶中所有資料庫和資料表上的所有 AWS Glue 動作。您可以自訂政策，只將必要的許可授予消費者委託人。例如，您可以提供資料庫中特定資料表或檢視的唯讀存取權。 | 雲端管理員 | 

### 從消費者帳戶存取資料
<a name="access-data-from-the-consumer-account"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 為資料目錄建立具名參考。 | 若要建立具名資料目錄參考，請使用 [CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/getting-started.html) 或本機安裝的 AWS CLI 來執行下列命令：<pre>aws athena create-data-catalog --name <shared catalog name> --type GLUE --parameters catalog-id=<data account id></pre> | 雲端管理員 | 
| 授予取用者帳戶中的 IAM 角色對資料的存取權。 | 將下列政策連接至取用者帳戶中的 IAM 角色，以授予角色跨帳戶的資料存取權：<pre>{<br />     "Version": "2012-10-17",		 	 	 <br />     "Statement": [<br />        {<br />             "Effect": "Allow",<br />             "Action": "s3:GetObject",<br />             "Resource": "arn:aws:s3:::data-bucket/*"<br />        },<br />        {<br />             "Effect": "Allow",<br />             "Action": "s3:ListBucket",<br />             "Resource": "arn:aws:s3:::data-bucket"<br />        },<br />        {<br />            "Effect": "Allow",<br />            "Action": "glue:*",<br />            "Resource": [<br />                 "arn:aws:glue:<region>:<data account id>:catalog",<br />                 "arn:aws:glue:<region>:<data account id>:database/*",<br />                 "arn:aws:glue:<region>:<data account id>:table/*"<br />            ]<br />        }<br />    ]<br />}</pre>接著，使用下列範本指定哪些使用者可以在其信任政策中接受 IAM 角色：<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />       {<br />            "Effect": "Allow",<br />            "Principal": {<br />                "AWS": "arn:aws:iam::<consumer account id>:user/<IAM user>"<br />            },<br />            "Action": "sts:AssumeRole"<br />        }<br />    ]<br />}</pre>最後，將相同的政策連接至使用者所屬的使用者群組，授予使用者擔任 IAM 角色的許可。 | 雲端管理員 | 
| （如果需要） 授予取用者帳戶中的 IAM 角色對資料加密金鑰的存取權。 | 如果 S3 儲存貯體是由 AWS KMS 金鑰加密，請將下列政策連接至取用者帳戶中的 IAM 角色，以授予金鑰的`kms:Decrypt`許可：<pre>{<br />     "Effect": "Allow",<br />     "Action": "kms:Decrypt",<br />     "Resource": "arn:aws:kms:<region>:<data account id>:key/<key id>"<br />}</pre> | 雲端管理員 | 
| 切換到取用者帳戶中的 IAM 角色以存取資料。 | 身為資料取用者，請[切換到 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html)以存取資料帳戶中的資料。 | 資料取用者 | 
| 存取資料。 | 使用 Athena 查詢資料。例如，開啟 Athena 查詢編輯器並執行下列查詢：<pre>SELECT *<br />  FROM <shared catalog name>.<database name>.<table name></pre>您也可以依目錄的 Amazon Resource Name (ARN) 來參考目錄，而不是使用具名目錄參考。如果您在查詢或檢視中使用動態目錄參考，請使用逸出雙引號 (\$1") 括住參考。例如：<pre>SELECT * <br />  FROM \"glue:arn:aws:glue:<region>:<data account id>:catalog\".<database name>.<table name></pre>如需詳細資訊，請參閱《Amazon Athena [ Athena 使用者指南》中的 AWS Glue 資料目錄的跨帳戶存取權](https://docs.aws.amazon.com/athena/latest/ug/security-iam-cross-account-glue-catalog-access.html)。 | 資料取用者 | 

## 相關資源
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-resources"></a>
+ [跨帳戶存取 AWS Glue 資料目錄 ](https://docs.aws.amazon.com/athena/latest/ug/security-iam-cross-account-glue-catalog-access.html)(Athena 文件）
+ [(AWS CLI) create-data-catalog](https://docs.aws.amazon.com/cli/latest/reference/athena/create-data-catalog.html) (AWS CLI 命令參考）
+ [使用 Amazon Athena 進行跨帳戶 AWS Glue Data Catalog 存取 ](https://aws.amazon.com/blogs/big-data/cross-account-aws-glue-data-catalog-access-with-amazon-athena/)(AWS 大數據部落格）
+ [IAM 中的安全最佳實務 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)(IAM 文件）

## 其他資訊
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-additional"></a>

**使用 Lake Formation 做為跨帳戶共用的替代方案**

您也可以使用 AWS Lake Formation 跨帳戶共用對 AWS Glue 目錄物件的存取權。Lake Formation 在資料欄和資料列層級提供精細的存取控制、標籤型存取控制、ACID 交易的受管資料表，以及其他功能。雖然 Lake Formation 與 Athena 充分整合，但相較於此模式的僅限 IAM 方法，它確實需要額外的組態。我們建議您考慮在整體解決方案架構的更廣泛內容中使用 Lake Formation 或僅限 IAM 存取控制的決定。考量包括涉及哪些其他服務，以及它們如何與這兩種方法整合。

# 將 Teradata NORMALIZE 暫時功能轉換為 Amazon Redshift SQL
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql"></a>

*Po Hong，Amazon Web Services*

## 總結
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-summary"></a>

**NORMALIZE** 是 ANSI SQL 標準的 Teradata 擴充功能。當 SQL 資料表包含具有 **PERIOD** 資料類型的資料欄時，**NORMALIZE** 會結合在該資料欄中符合或重疊的值，以形成單一期間來合併多個個別期間值。若要使用 **NORMALIZE**，SQL **SELECT** 清單中至少有一個資料欄必須是 Teradata 的暫時 **PERIOD** 資料類型。如需 **NORMALIZE** 的詳細資訊，請參閱 [Teradata 文件](https://docs.teradata.com/reader/2_MC9vCtAJRlKle2Rpb0mA/MIGI5UMEwgERC3Un7tEZ6g)。 

Amazon Redshift 不支援 **NORMALIZE**，但您可以在 Amazon Redshift 中使用原生 SQL 語法和 **LAG** 視窗函數來實作此功能。此模式著重於搭配 **ON MEETS 或 OVERLAPS **條件使用 Teradata **NORMALIZE** 延伸模組，這是最受歡迎的格式。它說明此功能如何在 Teradata 中運作，以及如何將其轉換為 Amazon Redshift 原生 SQL 語法。

## 先決條件和限制
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-prereqs"></a>

**先決條件**
+ 基本 Teradata SQL 知識和經驗
+ Amazon Redshift 知識和經驗

## Architecture
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-architecture"></a>

**來源技術堆疊**
+ Teradata 資料倉儲

**目標技術堆疊**
+ Amazon Redshift

**目標架構**

如需將 Teradata 資料庫遷移至 Amazon Redshift 的高階架構，請參閱[使用 AWS SCT 資料擷取代理程式將 Teradata 資料庫遷移至 Amazon Redshift](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/migrate-a-teradata-database-to-amazon-redshift-using-aws-sct-data-extraction-agents.html) 的模式。遷移不會自動將 Teradata **NORMALIZE** 片語轉換為 Amazon Redshift SQL。您可以遵循此模式中的準則來轉換此 Teradata 延伸。

## 工具
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-tools"></a>

**Code**

若要說明 **NORMALIZE** 的概念和功能，請考慮 Teradata 中的下列資料表定義：

```
CREATE TABLE systest.project
     (    emp_id        INTEGER,
          project_name  VARCHAR(20),
          dept_id       INTEGER,
          duration      PERIOD(DATE)
     );
```

執行下列 SQL 程式碼，將範例資料插入資料表：

```
BEGIN TRANSACTION;

INSERT INTO systest.project VALUES (10, 'First Phase', 1000,  PERIOD(DATE '2010-01-10', DATE '2010-03-20') );
INSERT INTO systest.project VALUES (10, 'First Phase', 2000,  PERIOD(DATE '2010-03-20', DATE '2010-07-15') );

INSERT INTO systest.project VALUES (10, 'Second Phase', 2000,  PERIOD(DATE '2010-06-15', DATE '2010-08-18') );
INSERT INTO systest.project VALUES (20, 'First Phase', 2000,  PERIOD(DATE '2010-03-10', DATE '2010-07-20') );

INSERT INTO systest.project VALUES (20, 'Second Phase', 1000,  PERIOD(DATE '2020-05-10', DATE '2020-09-20') );

END TRANSACTION;
```

結果：

```
select * from systest.project order by 1,2,3;
 
 *** Query completed. 4 rows found. 4 columns returned.
 *** Total elapsed time was 1 second.
 
     emp_id  project_name              dept_id  duration
-----------  --------------------  -----------  ------------------------
         10  First Phase                  1000  ('10/01/10', '10/03/20')        
         10  First Phase                  2000  ('10/03/20', '10/07/15')
         10  Second Phase                 2000  ('10/06/15', '10/08/18')
         20  First Phase                  2000  ('10/03/10', '10/07/20')
         20  Second Phase                 1000  ('20/05/10', '20/09/20')
```

*Teradata NORMALIZE 使用案例*

現在將 Teradata **NORMALIZE** SQL 子句新增至 **SELECT** 陳述式：

```
SELECT NORMALIZE ON MEETS OR OVERLAPS emp_id, duration 
FROM systest.project 
ORDER BY 1,2;
```

此 **NORMALIZE** 操作會在單一資料欄 () 上執行`emp_id`。對於 `emp_id=10`，持續時間中的三個重疊期間值會合併為單一期間值，如下所示： 

```
     emp_id  duration
-----------  ------------------------
         10  ('10/01/10', '10/08/18')
         20  ('10/03/10', '10/07/20')
         20  ('20/05/10', '20/09/20')
```

下列 **SELECT** 陳述式會在 `project_name`和 上執行 **NORMALIZE** 操作`dept_id`。請注意，**SELECT** 清單只包含一個 **PERIOD** 資料欄 `duration`。

```
SELECT NORMALIZE project_name, dept_id, duration 
FROM systest.project;
```

輸出：

```
project_name              dept_id  duration
--------------------  -----------  ------------------------
First Phase                  1000  ('10/01/10', '10/03/20')
Second Phase                 1000  ('20/05/10', '20/09/20')
First Phase                  2000  ('10/03/10', '10/07/20')
Second Phase                 2000  ('10/06/15', '10/08/18')
```

*Amazon Redshift 對等 SQL*

Amazon Redshift 目前不支援資料表中的 **PERIOD** 資料類型。相反地，您需要將 Teradata **PERIOD** 資料欄位分成兩個部分：`start_date, end_date`，如下所示： 

```
CREATE TABLE systest.project
     (    emp_id        INTEGER,
          project_name  VARCHAR(20),
          dept_id       INTEGER,
          start_date  DATE,
          end_date    DATE
     );
```

將範例資料插入資料表：

```
BEGIN TRANSACTION;
 
INSERT INTO systest.project VALUES (10, 'First Phase', 1000,  DATE '2010-01-10', DATE '2010-03-20' );
INSERT INTO systest.project VALUES (10, 'First Phase', 2000,  DATE '2010-03-20', DATE '2010-07-15');
 
INSERT INTO systest.project VALUES (10, 'Second Phase', 2000,  DATE '2010-06-15', DATE '2010-08-18' );
INSERT INTO systest.project VALUES (20, 'First Phase', 2000,  DATE '2010-03-10', DATE '2010-07-20' );
 
INSERT INTO systest.project VALUES (20, 'Second Phase', 1000,  DATE '2020-05-10', DATE '2020-09-20' );
 
END TRANSACTION;
```

輸出：

```
 emp_id | project_name | dept_id | start_date |  end_date
--------+--------------+---------+------------+------------
     10 | First Phase  |    1000 | 2010-01-10 | 2010-03-20
     10 | First Phase  |    2000 | 2010-03-20 | 2010-07-15
     10 | Second Phase |    2000 | 2010-06-15 | 2010-08-18
     20 | First Phase  |    2000 | 2010-03-10 | 2010-07-20
     20 | Second Phase |    1000 | 2020-05-10 | 2020-09-20
(5 rows)
```

若要重寫 Teradata 的 **NORMALIZE** 子句，您可以在 Amazon Redshift 中使用 [LAG 視窗函數](https://docs.aws.amazon.com/redshift/latest/dg/r_WF_LAG.html)。此函數會傳回分割區中目前資料列上方 （之前） 指定位移的資料列值。

您可以使用 **LAG** 函數來識別開始新期間的每個資料列，方法是判斷期間是否符合或與前一個期間重疊 (0 表示是，1 表示否）。當此旗標累積加總時，會提供群組識別符，可用於外部 **Group By** 子句，以到達 Amazon Redshift 中所需的結果。 

以下是使用 **LAG()** 的 Amazon Redshift SQL 陳述式範例：

```
SELECT emp_id, start_date, end_date, 
            (CASE WHEN start_date <= LAG(end_date) OVER (PARTITION BY emp_id ORDER BY start_date, end_date) THEN 0 ELSE 1 END) AS GroupStartFlag
FROM systest.project 
ORDER BY 1,2;
```

輸出：

```
 emp_id | start_date |  end_date  | groupstartflag
--------+------------+------------+----------------
     10 | 2010-01-10 | 2010-03-20 |              1
     10 | 2010-03-20 | 2010-07-15 |              0
     10 | 2010-06-15 | 2010-08-18 |              0
     20 | 2010-03-10 | 2010-07-20 |              1
     20 | 2020-05-10 | 2020-09-20 |              1
(5 rows)
```

下列 Amazon Redshift SQL 陳述式只會在 `emp_id` 欄上標準化：

```
SELECT T2.emp_id, MIN(T2.start_date) as new_start_date, MAX(T2.end_date) as new_end_date
FROM 
( SELECT T1.*, SUM(GroupStartFlag) OVER (PARTITION BY emp_id ORDER BY start_date ROWS UNBOUNDED PRECEDING) As GroupID
FROM ( SELECT emp_id, start_date, end_date, 
            (CASE WHEN start_date <= LAG(end_date) OVER (PARTITION BY emp_id ORDER BY start_date, end_date) THEN 0 ELSE 1 END) AS GroupStartFlag
FROM systest.project ) T1
) T2
GROUP BY T2.emp_id, T2.GroupID
ORDER BY 1,2;
```

輸出： 

```
 emp_id | new_start_date | new_end_date
--------+----------------+------------------------------------
     10 | 2010-01-10     | 2010-08-18
     20 | 2010-03-10     | 2010-07-20
     20 | 2020-05-10     | 2020-09-20
(3 rows)
```

** **

下列 Amazon Redshift SQL 陳述式會在 `project_name`和 `dept_id`資料欄上標準化：

```
SELECT T2.project_name, T2.dept_id, MIN(T2.start_date) as new_start_date, MAX(T2.end_date) as new_end_date
FROM 
( SELECT T1.*, SUM(GroupStartFlag) OVER (PARTITION BY project_name, dept_id ORDER BY start_date ROWS UNBOUNDED PRECEDING) As GroupID
FROM ( SELECT project_name, dept_id, start_date, end_date, 
            (CASE WHEN start_date <= LAG(end_date) OVER (PARTITION BY project_name, dept_id ORDER BY start_date, end_date) THEN 0 ELSE 1 END) AS GroupStartFlag
FROM systest.project ) T1
) T2
GROUP BY T2.project_name, T2.dept_id, T2.GroupID
ORDER BY 1,2,3;
```

輸出：

```
 project_name | dept_id | new_start_date | new_end_date
--------------+---------+----------------+--------------
 First Phase  |    1000 | 2010-01-10     | 2010-03-20
 First Phase  |    2000 | 2010-03-10     | 2010-07-20
 Second Phase |    1000 | 2020-05-10     | 2020-09-20
 Second Phase |    2000 | 2010-06-15     | 2010-08-18
(4 rows)
```

## 史詩
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-epics"></a>

### 將 NORMALIZE 轉換為 Amazon Redshift SQL
<a name="convert-normalize-to-amazon-redshift-sql"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Teradata SQL 程式碼。 | 根據您的需求使用 NORMALIZE 片語。 | SQL Developer | 
| 將程式碼轉換為 Amazon Redshift SQL。 | 若要轉換您的程式碼，請遵循此模式的「工具」區段中的準則。 | SQL Developer | 
| 在 Amazon Redshift 中執行程式碼。 | 建立資料表、將資料載入資料表，並在 Amazon Redshift 中執行程式碼。 | SQL Developer | 

## 相關資源
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-resources"></a>

**參考**
+ [Teradata NORMALIZE 暫時功能](https://docs.teradata.com/reader/2_MC9vCtAJRlKle2Rpb0mA/MIGI5UMEwgERC3Un7tEZ6g) (Teradata 文件）
+ [LAG 視窗函數](https://docs.aws.amazon.com/redshift/latest/dg/r_WF_LAG.html) (Amazon Redshift 文件）
+ [遷移至 Amazon Redshift](https://aws.amazon.com/redshift/data-warehouse-migration/) (AWS 網站）
+ [使用 AWS SCT 資料擷取代理程式將 Teradata 資料庫遷移至 Amazon Redshift](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/migrate-a-teradata-database-to-amazon-redshift-using-aws-sct-data-extraction-agents.html) (AWS 方案指引）
+ [將 Teradata RESET WHEN 功能轉換為 Amazon Redshift SQL](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/convert-the-teradata-reset-when-feature-to-amazon-redshift-sql.html) (AWS 方案指引）

**工具**
+ [AWS Schema Conversion Tool (AWS SCT)](https://aws.amazon.com/dms/schema-conversion-tool/)

**合作夥伴**
+ [AWS 遷移能力合作夥伴](https://aws.amazon.com/migration/partner-solutions/#delivery)

# 將 Teradata RESET WHEN 功能轉換為 Amazon Redshift SQL
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql"></a>

*Po Hong，Amazon Web Services*

## 總結
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-summary"></a>

**RESET WHEN** 是 SQL 分析視窗函數中使用的 Teradata 功能。它是 ANSI SQL 標準的延伸。**RESET WHEN** 會根據某些指定的條件，決定 SQL 視窗函數運作所在的分割區。如果條件評估為 **TRUE**，則會在現有視窗分割區內建立新的動態子分割區。如需 **RESET WHEN** 的詳細資訊，請參閱 [Teradata 文件](https://docs.teradata.com/reader/1DcoER_KpnGTfgPinRAFUw/b7wL86OoMTPno6hrSPNdDg)。

Amazon Redshift 在 SQL 視窗函數中不支援 **RESET WHEN**。若要實作此功能，您必須將 **RESET WHEN** 轉換為 Amazon Redshift 中的原生 SQL 語法，並使用多個巢狀函數。此模式示範如何使用 Teradata **RESET WHEN** 功能，以及如何將其轉換為 Amazon Redshift SQL 語法。 

## 先決條件和限制
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-prereqs"></a>

**先決條件**
+ Teradata 資料倉儲及其 SQL 語法的基本知識
+ 充分了解 Amazon Redshift 及其 SQL 語法

## Architecture
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-architecture"></a>

**來源技術堆疊**
+ Teradata 資料倉儲

**目標技術堆疊**
+ Amazon Redshift

**架構**

如需將 Teradata 資料庫遷移至 Amazon Redshift 的高階架構，請參閱[使用 AWS SCT 資料擷取代理程式將 Teradata 資料庫遷移至 Amazon Redshift](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/migrate-a-teradata-database-to-amazon-redshift-using-aws-sct-data-extraction-agents.html) 的模式。遷移不會自動將 Teradata **RESET WHEN** 片語轉換為 Amazon Redshift SQL。您可以遵循下一節中的準則來轉換此 Teradata 擴充功能。

## 工具
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-tools"></a>

**Code**

若要說明 **RESET WHEN** 的概念，請考慮 Teradata 中的下列資料表定義：

```
create table systest.f_account_balance                                
( account_id integer NOT NULL,
  month_id integer,
  balance integer )
unique primary index (account_id, month_id);
```

執行下列 SQL 程式碼，將範例資料插入資料表：

```
BEGIN TRANSACTION;
Insert Into systest.f_account_balance values (1,1,60);
Insert Into systest.f_account_balance values (1,2,99);
Insert Into systest.f_account_balance values (1,3,94);
Insert Into systest.f_account_balance values (1,4,90);
Insert Into systest.f_account_balance values (1,5,80);
Insert Into systest.f_account_balance values (1,6,88);
Insert Into systest.f_account_balance values (1,7,90);
Insert Into systest.f_account_balance values (1,8,92);
Insert Into systest.f_account_balance values (1,9,10);
Insert Into systest.f_account_balance values (1,10,60);
Insert Into systest.f_account_balance values (1,11,80);
Insert Into systest.f_account_balance values (1,12,10);
END TRANSACTION;
```

範例資料表具有下列資料：


| 
| 
| account\$1id | month\$1id | balance | 
| --- |--- |--- |
| 1 | 1 | 60 | 
| 1 | 2 | 99 | 
| 1 | 3 | 94 | 
| 1 | 4 | 90 | 
| 1 | 5 | 80 | 
| 1 | 6 | 88 | 
| 1 | 7 | 90 | 
| 1 | 8 | 92 | 
| 1 | 9 | 10 | 
| 1 | 10 | 60 | 
| 1 | 11 | 80 | 
| 1 | 12 | 10 | 

對於每個帳戶，假設您想要分析連續的每月餘額增加序列。當一個月的餘額小於或等於上個月的餘額時，需要將計數器重設為零並重新啟動。

*Teradata RESET 當使用案例*

為了分析此資料，Teradata SQL 使用具有巢狀彙總和 **RESET WHEN** 片語的視窗函數，如下所示：

```
SELECT account_id, month_id, balance,
 ( ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY month_id
RESET WHEN balance <= SUM(balance) over (PARTITION BY account_id ORDER BY month_id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) ) -1 ) as balance_increase
FROM systest.f_account_balance
ORDER BY 1,2;
```

輸出：


| 
| 
|  account\$1id | month\$1id | balance | balance\$1increase | 
| --- |--- |--- |--- |
| 1 | 1 | 60 | 0 | 
| 1 | 2 | 99 | 1 | 
| 1 | 3 | 94 | 0 | 
| 1 | 4 | 90 | 0 | 
| 1 | 5 | 80 | 0 | 
| 1 | 6 | 88 | 1 | 
| 1 | 7 | 90 | 2 | 
| 1 | 8 | 92 | 3 | 
| 1 | 9 | 10 | 0 | 
| 1 | 10 | 60 | 1 | 
| 1 | 11 | 80 | 2 | 
| 1 | 12 | 10 | 0 | 

查詢在 Teradata 中的處理方式如下：

1. **SUM（平衡）** 彙總函數會計算指定月份中指定帳戶的所有餘額總和。

1. 我們會檢查指定月份的餘額 （針對指定帳戶） 是否大於上個月的餘額。

1. 如果餘額增加，我們會追蹤累積計數值。如果 **RESET WHEN** 條件評估為 **false**，表示餘額已連續幾個月增加，我們會繼續增加計數。

1. **ROW\$1NUMBER()** 排序的分析函數會計算計數值。當我們達到餘額小於或等於上個月餘額的月份時，**RESET WHEN** 條件會評估為 **true**。若是如此，我們會啟動新的分割區，**ROW\$1NUMBER()** 會從 1 重新啟動計數。我們使用**介於 1 PRECEDING 和 1 PRECEDING 之間的 ROWS** 來存取上一列的值。

1. 我們減去 1，以確保計數值以 0 開頭。

*Amazon Redshift 對等 SQL*

Amazon Redshift 不支援 SQL 分析視窗函數中的 **RESET WHEN** 片語。 若要產生相同的結果，您必須使用 Amazon Redshift 原生 SQL 語法和巢狀子查詢重寫 Teradata SQL，如下所示： 

```
SELECT account_id, month_id, balance,
   (ROW_NUMBER() OVER(PARTITION BY account_id, new_dynamic_part ORDER BY month_id) -1) as balance_increase
FROM
( SELECT account_id, month_id, balance, prev_balance,
SUM(dynamic_part) OVER (PARTITION BY account_id ORDER BY month_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) As new_dynamic_part
FROM ( SELECT account_id, month_id, balance,
SUM(balance) over (PARTITION BY account_id ORDER BY month_id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) as prev_balance,
(CASE When balance <= prev_balance Then 1 Else 0 END) as dynamic_part
FROM systest.f_account_balance ) A
) B
ORDER BY 1,2;
```

由於 Amazon Redshift 在單一 SQL 陳述式的 **SELECT** 子句中不支援巢狀視窗函數，您必須使用兩個巢狀子查詢。
+ 在內部子查詢 （別名 A) 中，會建立並填入動態分割區指標 (**dynamic\$1part**)。如果一個月的餘額小於或等於上個月的餘額，則會將 **dynamic\$1part** 設定為 1；否則，會將 設定為 0。 
+ 在下一層 （別名 B) 中，會產生**新的\$1dynamic\$1part** 屬性作為 **SUM** 視窗函數的結果。 
+ 最後，將 **new\$1dynamic\$1part** 作為新的分割區屬性 (**動態分割區**) 新增至現有的分割區屬性 (**account\$1id**)，並套用與 Teradata （和減一） 相同的 **ROW\$1NUMBER()** 視窗函數。 

在這些變更之後，Amazon Redshift SQL 會產生與 Teradata 相同的輸出。

## 史詩
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-epics"></a>

### 將 RESET WHEN 轉換為 Amazon Redshift SQL
<a name="convert-reset-when-to-amazon-redshift-sql"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Teradata 視窗函數。 | 根據您的需求使用巢狀彙總和 RESET WHEN 片語。 | SQL Developer | 
| 將程式碼轉換為 Amazon Redshift SQL。 | 若要轉換您的程式碼，請遵循此模式的「工具」區段中的準則。 | SQL Developer | 
| 在 Amazon Redshift 中執行程式碼。 | 建立資料表、將資料載入資料表，以及在 Amazon Redshift 中執行程式碼。 | SQL Developer | 

## 相關資源
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-resources"></a>

**參考**
+ [片語時重設](https://docs.teradata.com/reader/1DcoER_KpnGTfgPinRAFUw/b7wL86OoMTPno6hrSPNdDg) (Teradata 文件）
+ [RESET WHEN 說明](https://stackoverflow.com/questions/53344536/teradata-reset-when-partition-by-order-by) （堆疊溢位）
+ [遷移至 Amazon Redshift](https://aws.amazon.com/redshift/data-warehouse-migration/) (AWS 網站）
+ [使用 AWS SCT 資料擷取代理程式將 Teradata 資料庫遷移至 Amazon Redshift](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/migrate-a-teradata-database-to-amazon-redshift-using-aws-sct-data-extraction-agents.html) (AWS 方案指引）
+ [將 Teradata NORMALIZE 暫時功能轉換為 Amazon Redshift SQL](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql.html) (AWS 方案指引）

**工具**
+ [AWS Schema Conversion Tool (AWS SCT)](https://aws.amazon.com/dms/schema-conversion-tool/)

**合作夥伴**
+ [AWS 遷移能力合作夥伴](https://aws.amazon.com/migration/partner-solutions/#delivery)

# 使用基礎設施做為程式碼，在 AWS 雲端上部署和管理無伺服器資料湖
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code"></a>

*Kirankumar Chandrashekar 和 Abdel Jaidi，Amazon Web Services*

## 總結
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-summary"></a>

此模式說明如何使用[無伺服器運算](https://aws.amazon.com/serverless/)和[基礎設施做為程式碼](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html) (IaC)，在 Amazon Web Services (AWS) 雲端上實作和管理資料湖。此模式是以 AWS 開發的[無伺服器資料湖架構 (SDLF)](https://sdlf.workshop.aws/) 研討會為基礎。

SDLF 是可重複使用的資源集合，可加速在 AWS 雲端上交付企業資料湖，並有助於更快速地部署至生產環境。它用於遵循最佳實務來實作資料湖的基礎結構。

SDLF 使用 AWS CodePipeline、AWS CodeBuild 和 AWS CodeCommit 等 AWS 服務，在整個程式碼和基礎設施部署中實作持續整合/持續部署 (CI/CD) 程序。

此模式使用多個 AWS 無伺服器服務來簡化資料湖管理。其中包括用於儲存的 Amazon Simple Storage Service (Amazon S3) 和 Amazon DynamoDB、用於運算的 AWS Lambda 和 AWS Glue，以及用於協同運作的 Amazon CloudWatch Events、Amazon Simple Queue Service (Amazon SQS) 和 AWS Step Functions。

AWS CloudFormation 和 AWS 程式碼服務可充當 IaC 層，以輕鬆操作和管理的方式提供可重複且快速的部署。

## 先決條件和限制
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)，已安裝並設定。 
+ 安裝和設定的 Git 用戶端。
+ [SDLF 研討會](https://sdlf.workshop.aws/)，在 Web 瀏覽器視窗中開啟並準備使用。 

## Architecture
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-architecture"></a>

![\[在 AWS 雲端上實作和管理資料湖。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/f4fc3ad2-1c4f-45ea-bc86-2db13105a173/images/e0cfff30-f0f8-4fc1-8e84-a152ef615c58.png)


 架構圖說明事件驅動的程序，步驟如下。 

1. 將檔案新增至原始資料 S3 儲存貯體後，Amazon S3 事件通知會放置在 SQS 佇列中。每個通知會以 JSON 檔案形式傳送，其中包含中繼資料，例如 S3 儲存貯體名稱、物件金鑰或時間戳記。

1. Lambda 函數會使用此通知，此函數會根據中繼資料將事件路由至正確的擷取、轉換和載入 (ETL) 程序。Lambda 函數也可以使用存放在 Amazon DynamoDB 資料表中的內容式組態。此步驟可對資料湖中的多個應用程式進行解耦和擴展。

1. 事件會路由至 ETL 程序中的第一個 Lambda 函數，該函數會將資料從原始資料區域轉換和移動到資料湖的暫存區域。第一步是更新全面型錄。這是包含資料湖所有檔案中繼資料的 DynamoDB 資料表。此資料表中的每一列都會保留儲存在 Amazon S3 中單一物件的操作中繼資料。在 S3 物件上，同步呼叫執行輕度轉換的 Lambda 函數，這是運算上便宜的操作 （例如將檔案從一種格式轉換為另一種格式）。由於已將新物件新增至預備 S3 儲存貯體，因此會更新完整目錄，並傳送訊息至等待 ETL 中下一個階段的 SQS 佇列。

1. CloudWatch Events 規則每 5 分鐘觸發一次 Lambda 函數。此函數會檢查訊息是否已從上一個 ETL 階段傳遞至 SQS 佇列。如果訊息已傳遞，Lambda 函數會從 ETL 程序的 [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/sample-start-workflow.html) 開始第二個函數。

1. 然後，大量轉換會套用至一批檔案。這種繁重的轉換是一種運算昂貴的操作，例如同步呼叫 AWS Glue 任務、AWS Fargate 任務、Amazon EMR 步驟或 Amazon SageMaker 筆記本。資料表中繼資料會使用更新 AWS Glue 目錄的 AWS Glue 爬蟲程式，從輸出檔案擷取。檔案中繼資料也會新增至 DynamoDB 中完整的目錄資料表。最後，也會執行利用 [Deequ](https://github.com/awslabs/deequ) 的資料品質步驟。

**技術堆疊**
+ Amazon CloudWatch Events
+ AWS CloudFormation
+ AWS CodePipeline
+ AWS CodeBuild
+ AWS CodeCommit
+ Amazon DynamoDB
+ AWS Glue
+ AWS Lambda
+ Amazon S3
+ Amazon SQS
+ AWS Step Functions

## 工具
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-tools"></a>
+ [Amazon CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) – CloudWatch Events 提供近乎即時的系統事件串流，說明 AWS 資源的變更。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) – CloudFormation 有助於以可預測且重複的方式建立和佈建 AWS 基礎設施部署。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) – CodeBuild 是一種全受管的建置服務，可編譯您的原始程式碼、執行單元測試，並產生準備好部署的成品。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) – CodeCommit 是由 AWS 託管的版本控制服務，可用來私下存放和管理資產 （例如原始碼和二進位檔案）。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) – CodePipeline 是一種持續交付服務，可用來建立模型、視覺化和自動化持續發佈軟體變更所需的步驟。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) – DynamoDB 是全受管的 NoSQL 資料庫服務，可提供快速且可預測的效能與可擴展性。 
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) – AWS Glue 是一種全受管 ETL 服務，可讓您更輕鬆地準備和載入資料以供分析。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – Lambda 支援執行程式碼，無需佈建或管理伺服器。Lambda 只有在需要時才會執行程式碼，可自動從每天數項請求擴展成每秒數千項請求。 
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html) – Amazon Simple Storage Service (Amazon S3) 是一種高度可擴展的物件儲存服務。Amazon S3 可用於各種儲存解決方案，包括網站、行動應用程式、備份和資料湖。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) - AWS Step Functions 是一種無伺服器函數協調器，可讓您輕鬆地將 AWS Lambda 函數和多個 AWS 服務排序為業務關鍵應用程式。
+ [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) – Amazon Simple Queue Service (Amazon SQS) 是一種全受管訊息佇列服務，可協助您解耦和擴展微服務、分散式系統和無伺服器應用程式。
+ [Deequ](https://github.com/awslabs/deequ) – Deequ 是一種工具，可協助您運算大型資料集的資料品質指標、定義和驗證資料品質限制，並隨時掌握資料分佈的變更。

**程式碼儲存庫**

SDLF 的原始碼和資源可在 [AWS Labs GitHub 儲存庫](https://github.com/awslabs/aws-serverless-data-lake-framework/)中使用。

## 史詩
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-epics"></a>

### 設定 CI/CD 管道來佈建 IaC
<a name="set-up-the-ci-cd-pipeline-to-provision-iac"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 CI/CD 管道來管理資料湖的 IaC。 | 登入 AWS 管理主控台，並遵循 SDLF 研討會[初始設定](https://sdlf.workshop.aws/en/10-deployment/100-setup.html)一節中的步驟。這會建立初始 CI/CD 資源，例如 CodeCommit 儲存庫、CodeBuild 環境，以及為資料湖佈建和管理 IaC 的 CodePipeline 管道。 | DevOps 工程師 | 

### 版本控制 IaC
<a name="version-control-the-iac"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在本機電腦上複製 CodeCommit 儲存庫。 | 請遵循 SDLF [研討會部署基礎](https://sdlf.workshop.aws/en/10-deployment/200-foundations.html)一節中的步驟。這可協助您將託管 IaC 的 Git 儲存庫複製到本機環境。 如需詳細資訊，請參閱從 [ CodeCommit 文件連線至 CodeCommit 儲存庫](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)。 CodeCommit  | DevOps 工程師 | 
| 修改 CloudFormation 範本。 | 使用您的本機工作站和程式碼編輯器，根據您的使用案例或需求修改 CloudFormation 範本。將它們遞交至本機複製的 Git 儲存庫。 如需詳細資訊，請參閱 [ AWS CloudFormation 文件中的使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html) AWS CloudFormation 範本。 | DevOps 工程師 | 
| 將變更推送至 CodeCommit 儲存庫。 | 您的基礎設施程式碼現在受到版本控制，並且會追蹤對程式碼基礎的修改。當您將變更推送至 CodeCommit 儲存庫時，CodePipeline 會自動將其套用至您的基礎設施，並將其交付至 CodeBuild。 如果您在 CodeBuild 中使用 AWS SAM CLI，請執行 `sam package`和 `sam deploy`命令。如果您使用 AWS CLI，請執行 `aws cloudformation package`和 `aws cloudformation deploy`命令。 | DevOps 工程師 | 

## 相關資源
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-resources"></a>

**設定 CI/CD 管道以佈建 IaC**
+ [SDLF 研討會 – 初始設定](https://sdlf.workshop.aws/en/10-deployment/100-setup.html)

**版本控制 IaC**
+ [SDLF 研討會 – 部署基礎](https://sdlf.workshop.aws/en/10-deployment/200-foundations.html)
+ [連線至 CodeCommit 儲存庫](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)
+ [使用 AWS CloudFormation 範本](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)

**其他資源**
+ [AWS 無伺服器資料分析管道參考架構](https://aws.amazon.com/blogs/big-data/aws-serverless-data-analytics-pipeline-reference-architecture/)
+ [SDLF 文件](https://sdlf.readthedocs.io/en/latest/)

# 在啟動時強制標記 Amazon EMR 叢集
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch"></a>

*Priyanka Chaudhary，Amazon Web Services*

## 總結
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-summary"></a>

此模式提供安全控制，可確保在建立 Amazon EMR 叢集時對其進行標記。 

Amazon EMR 是一種 Amazon Web Services (AWS) 服務，用於處理和分析大量資料。Amazon EMR 提供可擴展的低組態服務，是執行內部叢集運算的更簡單替代方案。您可以使用標記以不同方式分類 AWS 資源，例如依用途、擁有者或環境 。例如，您可以透過將自訂中繼資料指派給每個叢集來標記 Amazon EMR 叢集。標籤包含您定義的索引鍵和值。我們建議您建立一組一致的標籤，以符合組織的需求。當您將標籤新增至 Amazon EMR 叢集時，該標籤也會傳播到與叢集相關聯的每個作用中 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。同樣地，當您從 Amazon EMR 叢集移除標籤時，也會從每個相關聯的作用中 EC2 執行個體中移除該標籤。

偵測性控制項會監控 API 呼叫，並啟動 [RunJobFlow](https://docs.aws.amazon.com/emr/latest/APIReference/API_RunJobFlow.html)、[AddTags](https://docs.aws.amazon.com/emr/latest/APIReference/API_AddTags.html)、[RemoveTags](https://docs.aws.amazon.com/emr/latest/APIReference/API_RemoveTags.html) 和 [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) APIs Amazon CloudWatch Events 事件。事件會呼叫執行 Python 指令碼的 AWS Lambda。Python 函數會從事件的 JSON 輸入取得 Amazon EMR 叢集 ID，並執行下列檢查：
+ 檢查 Amazon EMR 叢集是否已使用您指定的標籤名稱設定。
+ 如果沒有，請傳送 Amazon Simple Notification Service (Amazon SNS) 通知給使用者，並提供相關資訊：Amazon EMR 叢集名稱、違規詳細資訊、AWS 區域、AWS 帳戶和 Lambda 的 Amazon Resource Name (ARN)，此通知來源為 。

## 先決條件和限制
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 用來上傳所提供 Lambda 程式碼的 Amazon Simple Storage Service (Amazon S3) 儲存貯體。或者，您可以為此目的建立 S3 儲存貯體，如 *Epics* 章節所述。
+ 您想要接收違規通知的作用中電子郵件地址。
+ 您要檢查的必要標籤清單。

**限制**
+ 此安全控制是區域性的。您必須將其部署到您要監控的每個 AWS 區域。

**產品版本**
+ Amazon EMR 4.8.0 版及更新版本。

## Architecture
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-architecture"></a>

**工作流程架構**

![\[叢集啟動、使用 APIs監控、事件產生、Lambda 函數呼叫、傳送的通知。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/1a4fc0f8-b0c9-4391-9c79-9eb3898d6ecb/images/0d95c414-69d1-4f29-a9e7-09f202e27014.png)


**自動化和擴展**
+ 如果您使用的是 [AWS Organizations](https://aws.amazon.com/organizations/)，則可以使用 [AWS Cloudformation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html)to，將此範本部署到您要監控的多個帳戶中。

## 工具
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-tools"></a>

**AWS 服務**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) –AWS CloudFormation 可協助您建立模型並設定 AWS 資源、快速一致地佈建資源，以及在整個生命週期中管理資源。您可以使用範本來描述資源及其相依性，並將它們一起啟動和設定為堆疊，而不是個別管理資源。您可以管理和佈建跨多個 AWS 帳戶和 AWS 區域的堆疊。
+ [Amazon CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) - Amazon CloudWatch Events 提供近乎即時的系統事件串流，說明 AWS 資源的變更。
+ [Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) - Amazon EMR 是 Web 服務，可簡化大數據架構的執行，並有效率地處理大量資料。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – AWS Lambda 是一種運算服務，支援執行程式碼，無需佈建或管理伺服器。Lambda 只有在需要時才會執行程式碼，可自動從每天數項請求擴展成每秒數千項請求。 
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一種物件儲存服務。您可以使用 Amazon S3 隨時從 Web 任何地方存放和擷取任意資料量。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) – Amazon Simple Notification Service (Amazon SNS) 會協調和管理發佈者和用戶端之間的訊息傳遞或傳送，包括 Web 伺服器和電子郵件地址。訂閱者會收到發佈到所訂閱主題的所有訊息，且某一主題的所有訂閱者均會收到相同訊息。

**Code**

此模式包含下列附件：
+ `EMRTagValidation.zip` – 用於安全控制的 Lambda 程式碼。
+ `EMRTagValidation.yml` – 設定事件和 Lambda 函數的 CloudFormation 範本。

## 史詩
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-epics"></a>

### 設定 S3 儲存貯體
<a name="set-up-the-s3-bucket"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 定義 S3 儲存貯體。 | 在 [Amazon S3 主控台](https://console.aws.amazon.com/s3/)上，選擇或建立 S3 儲存貯體以託管 Lambda 程式碼 .zip 檔案。此 S3 儲存貯體必須與您要監控的 Amazon EMR 叢集位於相同的 AWS 區域。Amazon S3 儲存貯體的名稱必須是全域唯一，且命名空間會由所有 AWS 帳戶共享。S3 儲存貯體名稱不能包含正斜線。 | 雲端架構師 | 
| 上傳 Lambda 程式碼。 | 將*附件*區段中提供的 Lambda 程式碼 .zip 檔案上傳至 S3 儲存貯體。                                              | 雲端架構師 | 

### 部署 AWS CloudFormation 範本
<a name="deploy-the-aws-cloudformation-template"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動 AWS CloudFormation 範本。 | 在與 S3 儲存貯體相同的 AWS 區域中開啟 [AWS CloudFormation 主控台](https://console.aws.amazon.com/cloudformation/.)，並部署範本。如需部署 AWS CloudFormation 範本的詳細資訊，請參閱 [ CloudFormation 文件中的在 AWS CloudFormation 主控台上建立堆疊](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。 CloudFormation  | 雲端架構師 | 
| 完成範本中的參數。 | 當您啟動範本時，系統會提示您輸入下列資訊：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/enforce-tagging-of-amazon-emr-clusters-at-launch.html) | 雲端架構師 | 

### 確認訂閱
<a name="confirm-the-subscription"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 確認訂閱。 | 當 CloudFormation 範本成功部署時，它會傳送訂閱電子郵件到您提供的電子郵件地址。您必須確認此電子郵件訂閱，才能開始接收違規通知。 | 雲端架構師 | 

## 相關資源
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-resources"></a>
+ [AWS Lambda 開發人員指南](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
+ [在 Amazon EMR 中標記叢集](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-tags.html)

## 附件
<a name="attachments-1a4fc0f8-b0c9-4391-9c79-9eb3898d6ecb"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/1a4fc0f8-b0c9-4391-9c79-9eb3898d6ecb/attachments/attachment.zip)

# 確保在啟動時啟用對 Amazon S3 的 Amazon EMR 記錄
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch"></a>

*Priyanka Chaudhary，Amazon Web Services*

## 總結
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-summary"></a>

此模式提供安全控制，可監控在 Amazon Web Services (AWS) 上執行之 Amazon EMR 叢集的記錄組態。

Amazon EMR 是一種用於大數據處理和分析的 AWS 工具。Amazon EMR 提供可擴展的低組態服務，作為執行內部叢集運算的替代方案。Amazon EMR 提供兩種類型的 EMR 叢集。
+ **暫時性 Amazon EMR 叢集**：暫時性 Amazon EMR 叢集會在處理完成時自動關閉並停止產生成本。
+ **持久性 Amazon EMR 叢集**：持久性 Amazon EMR 叢集會在資料處理任務完成後繼續執行。

Amazon EMR 和 Hadoop 都會產生報告叢集狀態的日誌檔案。根據預設，這些會寫入 **/mnt/var/log/** 目錄中的主節點。根據您在啟動叢集時設定叢集的方式，您也可以將這些日誌儲存至 Amazon Simple Storage Service (Amazon S3)，並透過圖形偵錯工具檢視它們。請注意，只有在叢集啟動時，才能指定 Amazon S3 記錄。使用此組態，日誌會每 5 分鐘從主節點傳送至 Amazon S3 位置。對於暫時性叢集，Amazon S3 記錄很重要，因為叢集會在處理完成時消失，而且這些日誌檔案可用來偵錯任何失敗的任務。

模式使用 AWS CloudFormation 範本來部署安全控制，以監控 API 呼叫，並在 "RunJobFlow" 上啟動 Amazon CloudWatch Events。RunJobFlow." 觸發程序會叫用執行 Python 指令碼的 AWS Lambda。Lambda 函數會從事件 JSON 輸入擷取 EMR 叢集 ID，並檢查 Amazon S3 日誌 URI。如果找不到 Amazon S3 URI，Lambda 函數會傳送 Amazon Simple Notification Service (Amazon SNS) 通知，詳細說明來自該通知的 EMR 叢集名稱、違規詳細資訊、AWS 區域、AWS 帳戶和 Lambda Amazon Resource Name (ARN)。

## 先決條件和限制
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ Lambda 程式碼 .zip 檔案的 S3 儲存貯體
+ 您想要接收違規通知的電子郵件地址

**限制**
+ 此偵測性控制是區域性控制，必須部署在您打算監控的 AWS 區域中。

**產品版本**
+ Amazon EMR 4.8.0 版及更新版本

## Architecture
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-architecture"></a>

**目標技術堆疊**
+ Amazon CloudWatch Events 事件
+ Amazon EMR
+ Lambda 函式
+ S3 bucket (S3 儲存貯體)
+ Amazon SNS

**目標架構**

![\[確保在啟動時啟用 Amazon EMR 記錄到 Amazon S3 的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/079af32e-0418-4bb2-bc20-c67ea5ac3b6e/images/3ba125cb-018a-4ace-838f-8c20992ecc20.png)


**自動化和擴展**
+ 如果您使用的是 AWS Organizations，則可以使用 [AWS CloudFormation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html)，將此範本部署到您要監控的多個帳戶中。

## 工具
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-tools"></a>

**工具**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) – AWS CloudFormation 可協助您使用基礎設施做為程式碼來建立模型和設定 AWS 資源。
+ [AWS Cloudwatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) – AWS CloudWatch Events 提供近乎即時的系統事件串流，說明 AWS 資源的變更。
+ [Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) – Amazon EMR 是一種受管叢集平台，可簡化大數據架構的執行。
+ [AWS Lambda](https://aws.amazon.com/lambda/) – AWS Lambda 支援執行程式碼，無需佈建或管理伺服器。Lambda 只有在需要時才會執行程式碼，可自動從每天數項請求擴展成每秒數千項請求。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/Welcome.html) – Amazon S3 是一種 Web 服務介面，可用來從 Web 上的任何位置存放和擷取任意數量的資料。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) – Amazon SNS 是一種 Web 服務，可協調和管理發佈者和用戶端之間的訊息傳遞或傳送，包括 Web 伺服器和電子郵件地址。

**Code**
+ 專案的 .zip 檔案可作為附件使用。

## 史詩
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-epics"></a>

### 定義 S3 儲存貯體
<a name="define-the-s3-bucket"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 定義 S3 儲存貯體。 | 若要託管 Lambda 程式碼 .zip 檔案，請選擇或建立具有不包含正斜線之唯一名稱的 S3 儲存貯體。S3 儲存貯體名稱全域唯一，且命名空間由所有 AWS 帳戶共用。您的 S3 儲存貯體必須與正在評估的 Amazon EMR 叢集位於相同的 AWS 區域。 | 雲端架構師 | 

### 將 Lambda 程式碼上傳至 S3 儲存貯體
<a name="upload-the-lambda-code-to-the-s3-bucket"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將 Lambda 程式碼上傳至 S3 儲存貯體。 | 將「附件」區段中提供的 Lambda 程式碼 .zip 檔案上傳至 S3 儲存貯體。S3 儲存貯體必須與正在評估的 Amazon EMR 叢集位於相同的區域。 | 雲端架構師 | 

### 部署 AWS CloudFormation 範本
<a name="deploy-the-aws-cloudformation-template"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 AWS CloudFormation 範本。 | 在 AWS CloudFormation 主控台上，在與 S3 儲存貯體相同的區域中，部署做為此模式附件提供的 AWS CloudFormation 範本。在下一個史詩中，提供參數的值。如需部署 AWS CloudFormation 範本的詳細資訊，請參閱「相關資源」一節。 | 雲端架構師 | 

### 完成 AWS CloudFormation 範本中的參數
<a name="complete-the-parameters-in-the-aws-cloudformation-template"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 命名 S3 儲存貯體。 | 輸入您在第一個 epic 中建立的 S3 儲存貯體名稱。 | 雲端架構師 | 
| 提供 Amazon S3 金鑰。 | 在您的 S3 儲存貯體中提供 Lambda 程式碼 .zip 檔案的位置，不帶正斜線 （例如，<directory>/<file-name>.zip)。 | 雲端架構師 | 
| 提供電子郵件地址。 | 提供作用中的電子郵件地址以接收 Amazon SNS 通知。 | 雲端架構師 | 
| 定義記錄層級。 | 定義 Lambda 函數的記錄層級和頻率。"Info" 會指定應用程式進度的詳細資訊訊息。「錯誤」會指定仍然可以允許應用程式繼續執行的錯誤事件。「警告」會指定潛在的有害情況。 | 雲端架構師 | 

### 確認訂閱
<a name="confirm-the-subscription"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 確認訂閱。 | 當範本成功部署時，它會傳送訂閱電子郵件訊息到提供的電子郵件地址。您必須確認此電子郵件訂閱，才能接收違規通知。 | 雲端架構師 | 

## 相關資源
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-resources"></a>
+ [AWS Lambda](https://aws.amazon.com/lambda/)
+ [Amazon EMR 記錄](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-debugging.html)
+ [部署 AWS CloudFormation 範本](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)

## 附件
<a name="attachments-079af32e-0418-4bb2-bc20-c67ea5ac3b6e"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/079af32e-0418-4bb2-bc20-c67ea5ac3b6e/attachments/attachment.zip)

# 使用 AWS Glue 任務和 Python 產生測試資料
<a name="generate-test-data-using-an-aws-glue-job-and-python"></a>

*Moinul Al-Mamun，Amazon Web Services*

## 總結
<a name="generate-test-data-using-an-aws-glue-job-and-python-summary"></a>

此模式說明如何建立以 Python 撰寫的 AWS Glue 任務，以快速且輕鬆地同時產生數百萬個範例檔案。範例檔案存放在 Amazon Simple Storage Service (Amazon S3) 儲存貯體中。快速產生大量範例檔案的功能對於測試或評估 AWS 雲端中的服務至關重要。例如，您可以對 Amazon S3 字首中的數百萬個小型檔案執行資料分析，以測試 AWS Glue Studio 或 AWS Glue DataBrew 任務的效能。

雖然您可以使用其他 AWS 服務來產生範例資料集，但我們建議您使用 AWS Glue。您不需要管理任何基礎設施，因為 AWS Glue 是無伺服器資料處理服務。您可以攜帶程式碼，並在 AWS Glue 叢集中執行。此外，AWS Glue 會佈建、設定和擴展執行任務所需的資源。您只需為您的任務在執行時使用的資源付費。

## 先決條件和限制
<a name="generate-test-data-using-an-aws-glue-job-and-python-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ AWS Command Line Interface (AWS CLI)[，已安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)並[設定為](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)使用 AWS 帳戶

**產品版本**
+ Python 3.9
+ AWS CLI 第 2 版

**限制**

每次觸發的 AWS Glue 任務數目上限為 50。如需詳細資訊，請參閱 [AWS Glue 端點和配額](https://docs.aws.amazon.com/general/latest/gr/glue.html)。

## Architecture
<a name="generate-test-data-using-an-aws-glue-job-and-python-architecture"></a>

下圖說明以 AWS Glue 任務為中心的架構範例，該任務會將其輸出 （即範例檔案） 寫入 S3 儲存貯體。

![\[工作流程顯示 AWS CLI 啟動 AWS Glue 任務，將輸出寫入 S3 儲存貯體。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/f35943e8-3b2b-410e-a3f0-05e1ebd357d0/images/452ccbda-71f2-42b8-976d-bcc968bb1dab.png)


圖表包含下列工作流程：

1. 您可以使用 AWS CLI、AWS 管理主控台或 API 來啟動 AWS Glue 任務。AWS CLI 或 API 可讓您自動化調用任務的平行化，並減少產生範例檔案的執行時間。

1. AWS Glue 任務會隨機產生檔案內容，將內容轉換為 CSV 格式，然後將內容儲存為通用字首下的 Amazon S3 物件。每個檔案小於 KB。AWS Glue 任務接受兩個使用者定義的任務參數： `START_RANGE`和 `END_RANGE`。您可以使用這些參數來設定檔案名稱，以及每個任務執行在 Amazon S3 中產生的檔案數目。您可以平行執行此任務的多個執行個體 （例如 100 個執行個體）。

## 工具
<a name="generate-test-data-using-an-aws-glue-job-and-python-tools"></a>
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您透過命令列 shell 中的命令與 AWS 服務互動。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是全受管的擷取、轉換和載入 (ETL) 服務。它可協助您可靠地分類、清理、擴充和移動資料存放區和資料串流之間的資料。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 可透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。

## 最佳實務
<a name="generate-test-data-using-an-aws-glue-job-and-python-best-practices"></a>

實作此模式時，請考慮下列 AWS Glue 最佳實務：
+ **使用正確的 AWS Glue 工作者類型來降低成本。**我們建議您了解工作者類型的不同屬性，然後根據 CPU 和記憶體需求，為您的工作負載選擇正確的工作者類型。對於此模式，我們建議您使用 Python shell 任務作為任務類型，以將 DPU 降至最低並降低成本。如需詳細資訊，請參閱《[AWS Glue 開發人員指南》中的在 AWS Glue 中新增任務](https://docs.aws.amazon.com/glue/latest/dg/add-job.html)。 AWS Glue 
+ **使用正確的並行限制來擴展您的任務。**我們建議您根據時間需求和所需的檔案數量來建立 AWS Glue 任務的最大並行數量。
+ **首先開始產生少量檔案。**若要在建置 AWS Glue 任務時降低成本並節省時間，請從少量檔案 （例如 1，000) 開始。這可讓您更輕鬆地進行故障診斷。如果產生少量檔案成功，則可以擴展到更多檔案。
+ **請先在本機執行 。**若要在建置 AWS Glue 任務時降低成本並節省時間，請在本機開始開發並測試程式碼。如需設定 Docker 容器的說明，以協助您在 shell 和整合開發環境 (IDE) 中撰寫 AWS Glue 擷取、轉換和載入 (ETL) 任務，請參閱 [ AWS 大數據部落格上的使用容器文章在本機開發 AWS Glue ETL 任務](https://aws.amazon.com/blogs/big-data/developing-aws-glue-etl-jobs-locally-using-a-container/)。

如需更多 AWS Glue 最佳實務，請參閱 AWS Glue 文件中的[最佳實務](https://docs.aws.amazon.com/prescriptive-guidance/latest/serverless-etl-aws-glue/best-practices.html)。

## 史詩
<a name="generate-test-data-using-an-aws-glue-job-and-python-epics"></a>

### 建立目的地 S3 儲存貯體和 IAM 角色
<a name="create-a-destination-s3-bucket-and-iam-role"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 S3 儲存貯體以存放檔案。 | 建立 [S3 儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)體和其中的[字首](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html)。此模式會將 `s3://{your-s3-bucket-name}/small-files/`位置用於示範用途。 | 應用程式開發人員 | 
| 建立和設定 IAM 角色。 | 您必須建立 AWS Glue 任務可用來寫入 S3 儲存貯體的 IAM 角色。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 應用程式開發人員 | 

### 建立和設定 AWS Glue 任務以處理並行執行
<a name="create-and-configure-an-aws-glue-job-to-handle-concurrent-runs"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 AWS Glue 任務。 | 您必須建立產生內容的 AWS Glue 任務，並將其存放在 S3 儲存貯體中。建立 [AWS Glue 任務](https://docs.aws.amazon.com/glue/latest/dg/console-jobs.html)，然後完成下列步驟來設定您的任務：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 應用程式開發人員 | 
| 更新任務代碼。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 應用程式開發人員 | 

### 從命令列或主控台執行 AWS Glue 任務
<a name="run-the-aws-glue-job-from-the-command-line-or-console"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 從命令列執行 AWS Glue 任務。 | 若要從 AWS CLI 執行您的 AWS Glue 任務，請使用您的值執行下列命令：<pre>cmd:~$ aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"0","--END_RANGE":"1000000"}'<br />cmd:~$ aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1000000","--END_RANGE":"2000000"}'</pre>如需從 AWS 管理主控台執行 AWS Glue 任務的指示，請參閱此模式中 * AWS 管理主控台案例的執行 AWS Glue 任務*。如果您想要使用不同的參數一次執行多個執行，建議您使用 AWS CLI 來執行 AWS Glue 任務，如上述範例所示。若要產生使用特定平行化因素產生定義數量的檔案所需的所有 AWS CLI 命令，請執行下列堡壘程式碼 （使用您的值）：<pre># define parameters<br />NUMBER_OF_FILES=10000000;<br />PARALLELIZATION=50; <br /> <br /># initialize<br />_SB=0;<br />      <br /># generate commands<br />for i in $(seq 1 $PARALLELIZATION); <br />do <br />      echo aws glue start-job-run --job-name create_small_files --arguments "'"'{"--START_RANGE":"'$(((NUMBER_OF_FILES/PARALLELIZATION) * (i-1) + _SB))'","--END_RANGE":"'$(((NUMBER_OF_FILES/PARALLELIZATION) * (i)))'"}'"'";<br />      _SB=1; <br />done</pre>如果您使用上述指令碼，請考慮下列事項：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) 若要查看上述指令碼的輸出範例，請參閱此模式*的額外資訊*區段中的 *Shell 指令碼輸出*。 | 應用程式開發人員 | 
| 在 AWS 管理主控台中執行 AWS Glue 任務。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 應用程式開發人員 | 
| 檢查 AWS Glue 任務的狀態。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 應用程式開發人員 | 

## 相關資源
<a name="generate-test-data-using-an-aws-glue-job-and-python-resources"></a>

**參考**
+ [AWS 上開放資料的登錄檔](https://registry.opendata.aws/)
+ [用於分析的資料集](https://aws.amazon.com/marketplace/solutions/data-analytics/data-sets)
+ [在 AWS 上開啟資料](https://aws.amazon.com/opendata/)
+ [在 AWS Glue 中新增任務](https://docs.aws.amazon.com/glue/latest/dg/add-job.html)
+ [AWS Glue 入門](https://aws.amazon.com/glue/getting-started/)

**指南和模式**
+ [AWS Glue 最佳實務](https://docs.aws.amazon.com/prescriptive-guidance/latest/serverless-etl-aws-glue/best-practices.html)
+ [負載測試應用程式](https://docs.aws.amazon.com/prescriptive-guidance/latest/load-testing/welcome.html)

## 其他資訊
<a name="generate-test-data-using-an-aws-glue-job-and-python-additional"></a>

**基準測試**

此模式用於產生 1，000 萬個檔案，使用不同的平行化參數做為基準測試的一部分。下表顯示測試的輸出：


| 
| 
| 平行化 | 任務執行產生的檔案數目 | 任務持續時間 | 速度 | 
| --- |--- |--- |--- |
| 10 | 1,000,000 | 6 小時 40 分鐘 | 非常慢 | 
| 50 | 200,000 | 80 分鐘 | 適中 | 
| 100 | 100,000 | 40 分鐘 | 快速 | 

如果您想要讓程序更快，您可以在任務組態中設定更多並行執行。您可以根據您的需求輕鬆調整任務組態，但請記住，有 AWS Glue 服務配額限制。如需詳細資訊，請參閱 [AWS Glue 端點和配額](https://docs.aws.amazon.com/general/latest/gr/glue.html)。

**Shell 指令碼輸出**

下列範例顯示此模式中從*命令列故事執行 AWS Glue 任務*的 shell 指令碼輸出。

```
user@MUC-1234567890 MINGW64 ~
  $ # define parameters
  NUMBER_OF_FILES=10000000;
  PARALLELIZATION=50;
  # initialize
  _SB=0;
   
  # generate commands
  for i in $(seq 1 $PARALLELIZATION);
   do
         echo aws glue start-job-run --job-name create_small_files --arguments "'"'{"--START_RANGE":"'$(((NUMBER_OF_FILES/PARALLELIZATION)  (i-1) + SB))'","--ENDRANGE":"'$(((NUMBER_OF_FILES/PARALLELIZATION)  (i)))'"}'"'";
         _SB=1;
   done
   
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"0","--END_RANGE":"200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"200001","--END_RANGE":"400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"400001","--END_RANGE":"600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"600001","--END_RANGE":"800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"800001","--END_RANGE":"1000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1000001","--END_RANGE":"1200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1200001","--END_RANGE":"1400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1400001","--END_RANGE":"1600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1600001","--END_RANGE":"1800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1800001","--END_RANGE":"2000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2000001","--END_RANGE":"2200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2200001","--END_RANGE":"2400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2400001","--END_RANGE":"2600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2600001","--END_RANGE":"2800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2800001","--END_RANGE":"3000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3000001","--END_RANGE":"3200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3200001","--END_RANGE":"3400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3400001","--END_RANGE":"3600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3600001","--END_RANGE":"3800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3800001","--END_RANGE":"4000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4000001","--END_RANGE":"4200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4200001","--END_RANGE":"4400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4400001","--END_RANGE":"4600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4600001","--END_RANGE":"4800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4800001","--END_RANGE":"5000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5000001","--END_RANGE":"5200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5200001","--END_RANGE":"5400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5400001","--END_RANGE":"5600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5600001","--END_RANGE":"5800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5800001","--END_RANGE":"6000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6000001","--END_RANGE":"6200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6200001","--END_RANGE":"6400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6400001","--END_RANGE":"6600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6600001","--END_RANGE":"6800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6800001","--END_RANGE":"7000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7000001","--END_RANGE":"7200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7200001","--END_RANGE":"7400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7400001","--END_RANGE":"7600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7600001","--END_RANGE":"7800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7800001","--END_RANGE":"8000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8000001","--END_RANGE":"8200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8200001","--END_RANGE":"8400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8400001","--END_RANGE":"8600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8600001","--END_RANGE":"8800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8800001","--END_RANGE":"9000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9000001","--END_RANGE":"9200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9200001","--END_RANGE":"9400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9400001","--END_RANGE":"9600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9600001","--END_RANGE":"9800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9800001","--END_RANGE":"10000000"}'
  
  user@MUC-1234567890 MINGW64 ~
```

**常見問答集**

*我應該使用多少個並行執行或平行任務？*

並行執行和平行任務的數量取決於您的時間需求和所需的測試檔案數量。建議您檢查正在建立的檔案大小。首先，檢查 AWS Glue 任務產生所需檔案數量所需的時間。然後，使用正確數量的並行執行來滿足您的目標。例如，如果您假設 100，000 個檔案需要 40 分鐘才能完成執行，但目標時間為 30 分鐘，則必須增加 AWS Glue 任務的並行設定。

*我可以使用此模式建立哪種類型的內容？*

您可以建立任何類型的內容，例如具有不同分隔符號的文字檔案 （例如 PIPE、JSON 或 CSV)。此模式使用 Boto3 寫入檔案，然後將檔案儲存在 S3 儲存貯體中。

*在 S3 儲存貯體中，我需要什麼層級的 IAM 許可？*

您必須擁有允許`Write`存取 S3 儲存貯體中物件的身分型政策。如需詳細資訊，請參閱 [Amazon S3 文件中的 Amazon S3：允許對 S3 儲存貯體中的物件進行讀取和寫入存取](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_s3_rw-bucket.html)。 Amazon S3 

# 使用 AWS IoT Greengrass，以經濟實惠的方式直接將 IoT 資料擷取至 Amazon S3 AWS IoT
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass"></a>

*Sebastian Viviani 和 Rizwan Syed，Amazon Web Services*

## 總結
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-summary"></a>

此模式說明如何使用 AWS IoT Greengrass 第 2 版裝置，以經濟實惠的方式將物聯網 (IoT) 資料直接擷取至 Amazon Simple Storage Service (Amazon S3) 儲存貯體。裝置會執行自訂元件來讀取 IoT 資料，並將資料儲存在持久性儲存體 （即本機磁碟區） 中。然後，裝置會將 IoT 資料壓縮為 Apache Parquet 檔案，並定期將資料上傳至 S3 儲存貯體。

您擷取的 IoT 資料數量和速度受限於您的邊緣硬體功能和網路頻寬。您可以使用 Amazon Athena 以經濟實惠的方式分析擷取的資料。Athena 使用 [Amazon Managed Grafana ](https://docs.aws.amazon.com/grafana/latest/userguide/what-is-Amazon-Managed-Service-Grafana.html)支援壓縮的 Apache Parquet 檔案和資料視覺化。

## 先決條件和限制
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 在 [AWS IoT Greengrass 第 2 版](https://docs.aws.amazon.com/greengrass/v2/developerguide/greengrass-v2-whats-new.html)上執行並從感應器收集資料的[邊緣閘道](https://docs.aws.amazon.com/greengrass/v1/developerguide/quick-start.html) （資料來源和資料收集程序超出此模式的範圍，但您可以使用幾乎任何類型的感應器資料。 此模式使用本機 [MQTT](https://mqtt.org/) 代理程式搭配可在本機發佈資料的感應器或閘道。)
+ AWS IoT Greengrass [元件](https://docs.aws.amazon.com/greengrass/v2/developerguide/develop-greengrass-components.html)、[角色](https://docs.aws.amazon.com/greengrass/v1/developerguide/service-role.html)和 [SDK 相依性](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#installation)
+ 將資料上傳至 S3 儲存貯體的[串流管理員元件](https://docs.aws.amazon.com/greengrass/v2/developerguide/stream-manager-component.html) 
+ [適用於 Java 的 AWS 開發套件](https://aws.amazon.com/sdk-for-java/)、[適用於 JavaScript 的 AWS 開發套件](https://aws.amazon.com/sdk-for-javascript/)或[適用於 Python 的 AWS 開發套件 (Boto3)](https://docs.aws.amazon.com/pythonsdk/) APIs

**限制**
+ 此模式中的資料不會即時上傳至 S3 儲存貯體。有延遲期間，您可以設定延遲期間。資料會在邊緣裝置中暫時緩衝，然後在期間過期後上傳。
+ 開發套件僅適用於 Java、Node.js 和 Python。

## Architecture
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-architecture"></a>

**目標技術堆疊**
+ Amazon S3
+ AWS IoT Greengrass
+ MQTT 代理程式
+ 串流管理員元件

**目標架構**

下圖顯示設計用來擷取 IoT 感應器資料的架構，並將該資料存放在 S3 儲存貯體中。

![\[架構圖\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/b9032ae2-fffb-4750-b161-09810e19d878/images/8c28e639-5dcf-4950-b4a6-8015ec1a2894.png)


該圖顯示以下工作流程：

1. 多個感應器 （例如，溫度和閥） 更新會發佈至本機 MQTT 代理程式。

1. 訂閱這些感應器的 Parquet 檔案壓縮器會更新主題並接收這些更新。

1. Parquet 檔案壓縮器會在本機存放更新。

1. 期間經過之後，儲存的檔案會壓縮為 Parquet 檔案，並傳遞給串流管理員，以上傳到指定的 S3 儲存貯體。

1. 串流管理員會將 Parquet 檔案上傳至 S3 儲存貯體。

**注意**  
串流管理員 (`StreamManager`) 是受管元件。如需如何將資料匯出至 Amazon S3 的範例，請參閱 AWS IoT Greengrass 文件中的[串流管理員](https://docs.aws.amazon.com/greengrass/v2/developerguide/stream-manager-component.html)。您可以使用本機 MQTT 代理程式做為元件或其他代理程式，例如 [Eclipse Mosquitto](https://mosquitto.org/)。

## 工具
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-tools"></a>

**AWS 工具**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon S3 中分析資料。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [AWS IoT Greengrass](https://docs.aws.amazon.com/greengrass/v2/developerguide/what-is-iot-greengrass.html) 是一種開放原始碼 IoT 邊緣執行期和雲端服務，可協助您在裝置上建置、部署和管理 IoT 應用程式。

**其他工具**
+ [Apache Parquet](https://parquet.apache.org/) 是一種開放原始碼資料欄導向的資料檔案格式，專為儲存和擷取而設計。
+ [MQTT](https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.html) （訊息佇列遙測傳輸） 是一種輕量型傳訊通訊協定，專為受限裝置而設計。

## 最佳實務
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-best-practices"></a>

**針對上傳的資料使用正確的分割區格式**

S3 儲存貯體 （例如 `"myAwesomeDataSet/"`或 `"dataFromSource"`) 中沒有根字首名稱的特定要求，但我們建議您使用有意義的分割區和字首，以便輕鬆了解資料集的目的。

我們也建議您在 Amazon S3 中使用正確的分割，以便在資料集上以最佳方式執行查詢。在下列範例中，資料會以 HIVE 格式分割，以便最佳化每個 Athena 查詢掃描的資料量。這可改善效能並降低成本。

`s3://<ingestionBucket>/<rootPrefix>/year=YY/month=MM/day=DD/HHMM_<suffix>.parquet`

## 史詩
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-epics"></a>

### 設定您的環境
<a name="set-up-your-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 S3 儲存貯體。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 應用程式開發人員 | 
| 將 IAM 許可新增至 S3 儲存貯體。 | 若要授予使用者對您先前建立的 S3 儲存貯體和字首的寫入存取權，請將下列 IAM 政策新增至您的 AWS IoT Greengrass 角色：<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Sid": "S3DataUpload",<br />            "Effect": "Allow",<br />            "Action": [<br />                "s3:List*",<br />                "s3:Put*"<br />            ],<br />            "Resource": [<br />                "arn:aws:s3:::<ingestionBucket>",<br />                "arn:aws:s3:::<ingestionBucket>/<prefix>/*"<br />            ]<br />        }<br />    ]<br />}</pre>如需詳細資訊，請參閱 Aurora 文件中的[建立 IAM 政策以存取 Amazon S3 資源](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.Authorizing.IAM.S3CreatePolicy.html)。接著，更新 S3 儲存貯體的資源政策 （如有需要），以允許使用正確的 AWS [主體](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-bucket-user-policy-specifying-principal-intro.html)進行寫入存取。 | 應用程式開發人員 | 

### 建置和部署 AWS IoT Greengrass 元件
<a name="build-and-deploy-the-aws-iot-greengrass-component"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新 元件的配方。 | 根據下列範例[，在建立部署](https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html)時[更新元件組態](https://docs.aws.amazon.com/greengrass/v2/developerguide/update-component-configurations.html)：<pre>{<br />  "region": "<region>",<br />  "parquet_period": <period>,<br />  "s3_bucket": "<s3Bucket>",<br />  "s3_key_prefix": "<s3prefix>"<br />}</pre>將 取代`<region>`為您的 AWS 區域、`<period>`將 取代為您的週期性間隔、`<s3Bucket>`將 取代為您的 S3 儲存貯體，並將 `<s3prefix>`取代為您的字首。 | 應用程式開發人員 | 
| 建立 元件。 | 執行以下任意一項：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 應用程式開發人員 | 
| 更新 MQTT 用戶端。 | 範例程式碼不使用身分驗證，因為元件會在本機連線至代理程式。如果您的案例不同，請視需要更新 MQTT 用戶端區段。此外，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 應用程式開發人員 | 

### 將元件新增至 AWS IoT Greengrass 第 2 版核心裝置
<a name="add-the-component-to-the-aws-iot-greengrass-version-2-core-device"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新核心裝置的部署。 | 如果 AWS IoT Greengrass 第 2 版核心裝置的部署已存在，[請修改部署](https://docs.aws.amazon.com/greengrass/v2/developerguide/revise-deployments.html)。如果部署不存在，[請建立新的部署](https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html)。若要為元件提供正確的名稱，請根據下列項目更新新元件的[日誌管理員組態](https://docs.aws.amazon.com/greengrass/v2/developerguide/log-manager-component.html) （如果需要）：<pre>{<br />  "logsUploaderConfiguration": {<br />    "systemLogsConfiguration": {<br />    ...<br />    },<br />    "componentLogsConfigurationMap": {<br />      "<com.iot.ingest.parquet>": {<br />        "minimumLogLevel": "INFO",<br />        "diskSpaceLimit": "20",<br />        "diskSpaceLimitUnit": "MB",<br />        "deleteLogFileAfterCloudUpload": "false"<br />      }<br />      ...<br />    }<br />  },<br />  "periodicUploadIntervalSec": "300"<br />}</pre>最後，完成 AWS IoT Greengrass 核心裝置的部署修訂。 | 應用程式開發人員 | 

### 驗證資料擷取至 S3 儲存貯體
<a name="verify-data-ingestion-into-the-s3-bucket"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢查 AWS IoT Greengrass 磁碟區的日誌。 | 檢查以下各項：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 應用程式開發人員 | 
| 檢查 S3 儲存貯體。 | 驗證資料是否正在上傳到 S3 儲存貯體。您可以在每個期間看到正在上傳的檔案。您也可以在下一節中查詢資料，確認資料是否已上傳至 S3 儲存貯體。 | 應用程式開發人員 | 

### 從 Athena 設定查詢
<a name="set-up-querying-from-athena"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立資料庫和資料表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 應用程式開發人員 | 
| 授予 Athena 對資料的存取權。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 應用程式開發人員 | 

## 疑難排解
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| MQTT 用戶端無法連線 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 
| MQTT 用戶端無法訂閱 | 驗證 MQTT 代理程式上的許可。如果您有來自 AWS 的 MQTT 代理程式，請參閱 [MQTT 3.1.1 代理程式 (Moquette)](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-moquette-component.html) 和 [MQTT 5 代理程式 (EMQX)](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-emqx-component.html)。 | 
| 不會建立 Parquet 檔案 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 
| 物件不會上傳到 S3 儲存貯體 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 

## 相關資源
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-resources"></a>
+ [DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) (Pandas 文件）
+ [Apache Parquet 文件](https://parquet.apache.org/docs/) (Parquet 文件）
+ [開發 AWS IoT Greengrass 元件](https://docs.aws.amazon.com/greengrass/v2/developerguide/develop-greengrass-components.html) (AWS IoT Greengrass 開發人員指南，第 2 版）
+ 將[ AWS IoT Greengrass 元件部署至裝置](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-deployments.html) (AWS IoT Greengrass 開發人員指南，第 2 版）
+ [與本機 IoT 裝置互動 ](https://docs.aws.amazon.com/greengrass/v2/developerguide/interact-with-local-iot-devices.html)(AWS IoT Greengrass 開發人員指南，第 2 版）
+ [MQTT 3.1.1 代理程式 (Moquette)](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-moquette-component.html) (AWS IoT Greengrass 開發人員指南，第 2 版）
+ [MQTT 5 代理程式 (EMQX)](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-emqx-component.html) (AWS IoT Greengrass 開發人員指南，第 2 版）

## 其他資訊
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-additional"></a>

**成本分析**

下列成本分析案例示範此模式中涵蓋的資料擷取方法如何影響 AWS 雲端中的資料擷取成本。此案例中的定價範例是以發佈時的價格為基礎。價格可能變動。此外，您的成本可能會根據您的 AWS 區域、AWS 服務配額以及與雲端環境相關的其他因素而有所不同。

*輸入訊號集*

此分析使用下列一組輸入訊號，做為比較 IoT 擷取成本與其他可用替代方案的基礎。


| 
| 
| 訊號數量 | Frequency (頻率) | 每個訊號的資料 | 
| --- |--- |--- |
| 125 | 25 Hz | 8 位元組 | 

在此案例中，系統會接收 125 個訊號。每個訊號都是 8 個位元組，每 40 毫秒 (25 Hz) 就會發生。這些訊號可以個別出現，或在常見的承載中分組。您可以選擇根據您的需求分割和封裝這些訊號。您也可以判斷延遲。延遲包含接收、累積和擷取資料的期間。

為了比較，此案例的擷取操作是以 `us-east-1` AWS 區域為基礎。成本比較僅適用於 AWS 服務。硬體或連線能力等其他成本不會納入分析。

*成本比較*

下表顯示每個擷取方法的每月成本，以美元 (USD) 為單位。


| 
| 
| Method | 每月成本 | 
| --- |--- |
| AWS IoT SiteWise*\$1* | 331.77 USD | 
| AWS IoT SiteWise Edge 搭配資料處理套件 （將所有資料保留在邊緣） | 200 USD | 
| 用於存取原始資料的 AWS IoT Core 和 Amazon S3 規則 | 84.54 USD | 
| Parquet 檔案在邊緣壓縮並上傳至 Amazon S3 | 0.5 USD | 

\$1資料必須進行縮減取樣，以符合服務配額。這表示此方法有一些資料遺失。

*替代方法*

本節顯示下列替代方法的同等成本：
+ **AWS IoT SiteWise** – 每個訊號都必須以個別訊息上傳。因此，每月的訊息總數為 125 × 25 × 3600 × 24 × 30，或每月 81 億則訊息。不過，AWS IoT SiteWise 每個屬性每秒只能處理 10 個資料點。假設資料縮減取樣至 10 Hz，則每月訊息數量會減少至 125 × 10 × 3600 × 24 × 30，或 32.4 億。如果您使用 發佈者元件，以 10 個 （每百萬則訊息 1 USD) 的群組來封裝衡量值，則每月 324 USD 的費用。假設每則訊息為 8 個位元組 (1 Kb/125)，即 25.92 Gb 的資料儲存體。這會增加每月 7.77 USD 的成本。第一個月的總成本為 331.77 USD，每月增加 7.77 USD。
+ **AWS IoT SiteWise Edge 搭配資料處理套件，包括在邊緣完全處理的所有模型和訊號 （即沒有雲端擷取）** – 您可以使用資料處理套件做為替代方案，以降低成本並設定在邊緣計算的所有模型。即使未執行實際計算，這仍僅適用於儲存體和視覺化。在此情況下，邊緣閘道必須使用功能強大的硬體。每月固定費用為 200 USD。
+ **MQTT 直接擷取至 AWS IoT Core 和 IoT 規則，以將原始資料儲存在 Amazon S3 中** – 假設所有訊號都發佈在通用承載中，發佈至 AWS IoT Core 的訊息總數為每月 25×3600×24×30 或 6480 萬。每百萬則訊息 1 USD，即每月 64.8 USD 的成本。每百萬規則啟用 0.15 USD，每則訊息一個規則，每月增加 19.44 USD。在 Amazon S3 中，每 Gb 儲存的成本為 0.023 USD，每月增加 1.5 USD （每月增加以反映新資料）。第一個月的總成本為 84.54 USD，每月增加 1.5 USD。
+ **在 Parquet 檔案中的邊緣壓縮資料並上傳至 Amazon S3 （建議的方法**) – 壓縮率取決於資料類型。使用針對 MQTT 測試的相同工業資料，整個月的總輸出資料為 1.2 Gb。此費用為每月 0.03 USD。其他基準測試中描述的壓縮率 （使用隨機資料） 的順序為 66% （較接近最壞情況）。總資料為 21 Gb，每月費用為 0.5 USD。

**Parquet 檔案產生器**

下列程式碼範例顯示以 Python 撰寫的 Parquet 檔案產生器結構。程式碼範例僅供說明之用，如果貼入您的環境，則無法運作。

```
import queue
import paho.mqtt.client as mqtt
import pandas as pd

#queue for decoupling the MQTT thread
messageQueue = queue.Queue()
client = mqtt.Client()
streammanager = StreamManagerClient()

def feederListener(topic, message):
    payload = {
        "topic" : topic,
        "payload" : message,
    }
    messageQueue.put_nowait(payload)

def on_connect(client_instance, userdata, flags, rc):
    client.subscribe("#",qos=0)

def on_message(client, userdata, message):
    feederListener(topic=str(message.topic), message=str(message.payload.decode("utf-8")))


filename = "tempfile.parquet"
streamname = "mystream"
destination_bucket= "amzn-s3-demo-bucket"
keyname="mykey"
period= 60

client.on_connect = on_connect
client.on_message = on_message
streammanager.create_message_stream(
            MessageStreamDefinition(name=streamname, strategy_on_full=StrategyOnFull.OverwriteOldestData)
        )


while True:
   try:
       message = messageQueue.get(timeout=myArgs.mqtt_timeout)
   except (queue.Empty):
       logger.warning("MQTT message reception timed out")

   currentTimestamp = getCurrentTime()
   if currentTimestamp >= nextUploadTimestamp:
       df = pd.DataFrame.from_dict(accumulator)
       df.to_parquet(filename)
       s3_export_task_definition = S3ExportTaskDefinition(input_url=filename, bucket=destination_bucket, key=key_name)
       streammanager.append_message(streamname, Util.validate_and_serialize_to_json_bytes(s3_export_task_definition))
       accumulator = {}
       nextUploadTimestamp += period
   else:
        accumulator.append(message)
```

# 使用 Lambda 函數在暫時性 EMR 叢集中啟動 Spark 任務
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function"></a>

*Dhrubajyoti Mukherjee，Amazon Web Services*

## 總結
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-summary"></a>

此模式使用 Amazon EMR RunJobFlow API 動作啟動暫時性叢集，從 Lambda 函數執行 Spark 任務。暫時性 EMR 叢集的設計會在任務完成或發生任何錯誤時立即終止。暫時性叢集可節省成本，因為它只會在運算時間執行，並在雲端環境中提供可擴展性和彈性。

在 Lambda 函數中使用 Boto3 API 和 Python 程式設計語言啟動暫時性 EMR 叢集。Lambda 函數以 Python 撰寫，提供在需要時啟動叢集的額外彈性。

為了示範範例批次運算和輸出，此模式會從 Lambda 函數在 EMR 叢集中啟動 Spark 任務，並根據虛構公司的範例銷售資料執行批次運算。Spark 任務的輸出將是 Amazon Simple Storage Service (Amazon S3) 中的逗號分隔值 (CSV) 檔案。用於執行運算的虛擬私有雲端 (VPC) 和 AWS Identity and Access Management (IAM) 角色的輸入資料檔案、Spark .jar 檔案、程式碼片段和 AWS CloudFormation 範本會以附件的形式提供。 AWS Identity and Access Management 

## 先決條件和限制
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶

**限制**
+ 一次只能從程式碼啟動一個 Spark 任務。 

**產品版本**
+ 在 Amazon EMR 6.0.0 上測試

## Architecture
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-architecture"></a>

**目標技術堆疊**
+ Amazon EMR 
+ AWS Lambda
+ Amazon S3
+ Apache Spark

**目標架構**

![\[Lambda 到 Amazon EMR 和 Spark 到 Amazon S3\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/6c999fa7-9550-4929-a5c1-60394142175d/images/eb4fbb3f-2114-44d2-b9da-3fdcb9ca456e.png)


**自動化和擴展**

若要自動化 Spark-EMR 批次運算，您可以使用下列其中一個選項。
+ 實作可在 Cron 排程中啟動 Lambda 函數的 Amazon EventBridge 規則。如需詳細資訊，請參閱[教學課程：使用 EventBridge 排程 AWS Lambda 函數](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-run-lambda-schedule.html)。
+ 設定 [Amazon S3 事件通知](https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html)，以在檔案到達時啟動 Lambda 函數。
+ 透過事件內文和 Lambda 環境變數，將輸入參數傳遞至 AWS Lambda 函數。

## 工具
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-tools"></a>

**AWS 服務**
+ [Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) 是一種受管叢集平台，可簡化在 AWS 上執行大數據架構，以處理和分析大量資料。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而不需要佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**其他工具**
+ [Apache Spark](https://spark.apache.org/docs/latest/) 是用於大規模資料處理的多語言分析引擎。

## 史詩
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-epics"></a>

### 建立 Amazon EMR 和 Lambda IAM 角色和 VPC
<a name="create-the-amazon-emr-and-lambda-iam-roles-and-the-vpc"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 IAM 角色和 VPC。 | 如果您已有 AWS Lambda 和 Amazon EMR IAM 角色和 VPC，您可以略過此步驟。若要執行程式碼，EMR 叢集和 Lambda 函數都需要 IAM 角色。EMR 叢集還需要具有公有子網路的 VPC，或具有 NAT 閘道的私有子網路。若要自動建立所有 IAM 角色和 VPC，請依原樣部署連接的 AWS CloudFormation 範本，或者您可以依照*其他資訊*區段中的指定手動建立角色和 VPC。 | 雲端架構師 | 
| 請注意 AWS CloudFormation 範本輸出金鑰。 | 在 CloudFormation 範本成功部署後，導覽至 AWS CloudFormation 主控台中的**輸出**索引標籤。請注意五個輸出金鑰：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function.html)建立 Lambda 函數時，您會使用這些索引鍵中的值。 | 雲端架構師 | 

### 上傳 Spark .jar 檔案
<a name="upload-the-spark-jar-file"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 上傳 Spark .jar 檔案。 | 將 Spark .jar 檔案上傳至 AWS CloudFormation 堆疊建立的 S3 儲存貯體。儲存貯體名稱與輸出金鑰 相同`S3Bucket`。 | 一般 AWS | 

### 建立 Lambda 函數以啟動 EMR 叢集
<a name="create-the-lambda-function-to-launch-the-emr-cluster"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Lambda 函式。 | 在 Lambda 主控台上，使用 執行角色建立 Python 3.9\$1 Lambda 函數。執行角色政策必須允許 Lambda 啟動 EMR 叢集。（請參閱連接的 AWS CloudFormation 範本。) | 資料工程師、雲端工程師 | 
| 複製並貼上程式碼。 | 將 `lambda_function.py` 檔案中的程式碼取代為此模式*其他資訊*區段中的程式碼。 | 資料工程師、雲端工程師 | 
| 變更程式碼中的參數。 | 請遵循程式碼中的註解，變更參數值以符合您的 AWS 帳戶。 | 資料工程師、雲端工程師 | 
| 啟動 函數以啟動叢集。 | 啟動 函數，以使用提供的 Spark .jar 檔案開始建立暫時性 EMR 叢集。它會執行 Spark 任務，並在任務完成時自動終止。 | 資料工程師、雲端工程師 | 
| 檢查 EMR 叢集狀態。 | EMR 叢集啟動後，會顯示在**叢集**索引標籤下的 Amazon EMR 主控台中。您可以相應地檢查啟動叢集或執行任務時的任何錯誤。 | 資料工程師、雲端工程師 | 

### 設定並執行示範範例
<a name="set-up-and-run-the-sample-demo"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 上傳 Spark .jar 檔案。 | 從*附件*區段下載 Spark .jar 檔案，並將其上傳至 S3 儲存貯體。 | 資料工程師、雲端工程師 | 
| 上傳輸入資料集。 | 將連接`fake_sales_data.csv`的檔案上傳至 S3 儲存貯體。 | 資料工程師、雲端工程師 | 
| 貼上 Lambda 程式碼並變更參數。 | 從**工具**區段複製程式碼，並將程式碼貼到 Lambda 函數中，取代程式碼`lambda_function.py`檔案。變更參數值以符合您的帳戶。 | 資料工程師、雲端工程師 | 
| 啟動 函數並驗證輸出。 | Lambda 函數使用提供的 Spark 任務啟動叢集後，會在 S3 儲存貯體中產生 .csv 檔案。 | 資料工程師、雲端工程師 | 

## 相關資源
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-resources"></a>
+ [建置 Spark](https://spark.apache.org/docs/latest/building-spark.html)
+ [Apache Spark 和 Amazon EMR](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark.html)
+ [Boto3 文件 run\$1job\$1flow 文件](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/emr.html#EMR.Client.run_job_flow)
+ [Apache Spark 資訊和文件](https://spark.apache.org/)

## 其他資訊
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-additional"></a>

**Code**

```
"""
Copy paste the following code in your Lambda function. Make sure to change the following key parameters for the API as per your account

-Name (Name of Spark cluster)
-LogUri (S3 bucket to store EMR logs)
-Ec2SubnetId (The subnet to launch the cluster into)
-JobFlowRole (Service role for EC2)
-ServiceRole (Service role for Amazon EMR)

The following parameters are additional parameters for the Spark job itself. Change the bucket name and prefix for the Spark job (located at the bottom).

-s3://your-bucket-name/prefix/lambda-emr/SparkProfitCalc.jar (Spark jar file)
-s3://your-bucket-name/prefix/fake_sales_data.csv (Input data file in S3)
-s3://your-bucket-name/prefix/outputs/report_1/ (Output location in S3)
"""
import boto3

client = boto3.client('emr')


def lambda_handler(event, context):
    response = client.run_job_flow(
        Name='spark_job_cluster',
        LogUri='s3://your-bucket-name/prefix/logs',
        ReleaseLabel='emr-6.0.0',
        Instances={
            'MasterInstanceType': 'm5.xlarge',
            'SlaveInstanceType': 'm5.large',
            'InstanceCount': 1,
            'KeepJobFlowAliveWhenNoSteps': False,
            'TerminationProtected': False,
            'Ec2SubnetId': 'subnet-XXXXXXXXXXXXXX'
        },
        Applications=[{'Name': 'Spark'}],
        Configurations=[
            {'Classification': 'spark-hive-site',
             'Properties': {
                 'hive.metastore.client.factory.class': 'com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory'}
             }
        ],
        VisibleToAllUsers=True,
        JobFlowRole='EMRLambda-EMREC2InstanceProfile-XXXXXXXXX',
        ServiceRole='EMRLambda-EMRRole-XXXXXXXXX',
        Steps=[
            {
                'Name': 'flow-log-analysis',
                'ActionOnFailure': 'TERMINATE_CLUSTER',
                'HadoopJarStep': {
                    'Jar': 'command-runner.jar',
                    'Args': [
                        'spark-submit',
                        '--deploy-mode', 'cluster',
                        '--executor-memory', '6G',
                        '--num-executors', '1',
                        '--executor-cores', '2',
                        '--class', 'com.aws.emr.ProfitCalc',
                        's3://your-bucket-name/prefix/lambda-emr/SparkProfitCalc.jar',
                        's3://your-bucket-name/prefix/fake_sales_data.csv',
                        's3://your-bucket-name/prefix/outputs/report_1/'
                    ]
                }
            }
        ]
    )
```

**IAM 角色和 VPC 建立**

若要在 Lambda 函數中啟動 EMR 叢集，需要 VPC 和 IAM 角色。您可以使用此模式附件區段中的 AWS CloudFormation 範本來設定 VPC 和 IAM 角色，也可以使用以下連結手動建立角色。 

執行 Lambda 和 Amazon EMR 需要下列 IAM 角色。 

*Lambda 執行角色*

Lambda 函數的[執行角色](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)會授予其存取 AWS 服務和資源的許可。

*Amazon EMR 的服務角色*

[Amazon EMR 角色](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role.html)會在佈建資源和執行未在叢集內執行的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體內容中執行的服務層級任務時，定義 Amazon EMR 的允許動作。例如，服務角色用於在叢集啟動時佈建 EC2 執行個體。

*EC2 執行個體的服務角色*

[叢集 EC2 執行個體的服務角色](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role-for-ec2.html) （也稱為 Amazon EMR 的 EC2 執行個體描述檔） 是一種特殊類型的服務角色，會在執行個體啟動時指派給 Amazon EMR 叢集中的每個 EC2 執行個體。在 Apache Hadoop 上執行的應用程式程序會擔任此角色，以取得與其他 AWS 服務互動的許可。

*VPC 和子網路建立*

您可以從 [VPC 主控台建立](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#create-vpc-and-other-resources) VPC。 

## 附件
<a name="attachments-6c999fa7-9550-4929-a5c1-60394142175d"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/6c999fa7-9550-4929-a5c1-60394142175d/attachments/attachment.zip)

# 使用 AWS Glue 將 Apache Cassandra 工作負載遷移至 Amazon Keyspaces
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue"></a>

*Nikolai Kolesnikov、Karthiga Priya Chandran 和 Samir Patel，Amazon Web Services*

## 總結
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-summary"></a>

此模式說明如何在 AWS Glue 上使用 CQLReplicator，將現有的 Apache Cassandra 工作負載遷移至 Amazon Keyspaces （適用於 Apache Cassandra)。您可以使用 AWS Glue 上的 CQLReplicator，將遷移工作負載的複寫延遲降到最低到幾分鐘。您也會了解如何使用 Amazon Simple Storage Service (Amazon S3) 儲存貯體來存放遷移所需的資料，包括 [Apache Parquet](https://parquet.apache.org/) 檔案、組態檔案和指令碼。此模式假設您的 Cassandra 工作負載託管在虛擬私有雲端 (VPC) 中的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體上。

## 先決條件和限制
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-prereqs"></a>

**先決條件**
+ 具有來源資料表的 Cassandra 叢集
+ Amazon Keyspaces 中複寫工作負載的目標資料表
+ S3 儲存貯體可存放包含增量資料變更的中繼 Parquet 檔案
+ 存放任務組態檔案和指令碼的 S3 儲存貯體

**限制**
+ AWS Glue 上的 CQLReplicator 需要一些時間來佈建 Cassandra 工作負載的資料處理單位 (DPUs)。 AWS Glue Cassandra 叢集與 Amazon Keyspaces 中的目標金鑰空間和資料表之間的複寫延遲可能只會持續幾分鐘。

## Architecture
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-architecture"></a>

**來源技術堆疊**
+ Apache Cassandra
+ DataStax 伺服器
+ ScyllaDB

**目標技術堆疊**
+ Amazon Keyspaces

**遷移架構**

下圖顯示範例架構，其中 Cassandra 叢集託管在 EC2 執行個體上，並分散在三個可用區域。Cassandra 節點託管在私有子網路中。

![\[自訂服務角色、Amazon Keyspaces 和 Amazon S3，搭配連接到節點 VPC 的 AWS Glue。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e08048da-8996-4f2c-b8ed-da49fe9e693b/images/76256ab3-a1e6-4c9e-9c40-dc78f51edf0f.png)


該圖顯示以下工作流程：

1. 自訂服務角色可讓您存取 Amazon Keyspaces 和 S3 儲存貯體。

1. AWS Glue 任務會讀取 S3 儲存貯體中的任務組態和指令碼。

1. AWS Glue 任務會透過連接埠 9042 連接，以從 Cassandra 叢集讀取資料。

1. AWS Glue 任務透過連接埠 9142 連接，將資料寫入 Amazon Keyspaces。

## 工具
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-tools"></a>

**AWS 服務和工具**
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您透過命令列 shell 中的命令與 AWS 服務互動。
+ [AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/welcome.html) 是一種瀏覽器型 shell，您可以使用 AWS Command Line Interface (AWS CLI) 和一系列預先安裝的開發工具來管理 AWS 服務。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一項全受管 ETL 服務，可協助您可靠地分類、清理、擴充和移動資料存放區和資料串流之間的資料。
+ [Amazon Keyspaces （適用於 Apache Cassandra)](https://docs.aws.amazon.com/keyspaces/latest/devguide/what-is-keyspaces.html) 是一種受管資料庫服務，可協助您在 AWS 雲端中遷移、執行和擴展 Cassandra 工作負載。

**Code**

此模式的程式碼可在 GitHub [CQLReplicator](https://github.com/aws-samples/cql-replicator/tree/main/glue) 儲存庫中使用。

## 最佳實務
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-best-practices"></a>
+ 若要判斷遷移所需的 AWS Glue 資源，請估計來源 Cassandra 資料表中的資料列數。例如，每 0.25 個 DPU 250 K 資料列 (2 個 vCPUs，4 GB 記憶體） 與 84 GB 磁碟。
+ 在執行 CQLReplicator 之前預熱 Amazon Keyspaces 資料表。例如，八個 CQLReplicator 圖磚 (AWS Glue 任務） 每秒最多可寫入 22 K WCUs，因此目標應預先暖機至每秒最多 25-30 K WCUs。
+ 若要啟用 AWS Glue 元件之間的通訊，請針對安全群組中的所有 TCP 連接埠使用自我參考傳入規則。
+ 使用增量流量策略，隨時間分配遷移工作負載。

## 史詩
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-epics"></a>

### 部署 CQLReplicator
<a name="deploy-cqlreplicator"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立目標金鑰空間和資料表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.html) | 應用程式擁有者、AWS 管理員、DBA、應用程式開發人員 | 
| 設定 Cassandra 驅動程式以連線至 Cassandra。 | 使用下列組態指令碼：<pre>Datastax-java-driver {<br />  basic.request.consistency = "LOCAL_QUORUM"<br />  basic.contact-points = ["127.0.0.1:9042"]<br />   advanced.reconnect-on-init = true<br />   basic.load-balancing-policy {<br />        local-datacenter = "datacenter1"<br />}<br />advanced.auth-provider = {<br />       class = PlainTextAuthProvider<br />       username = "user-at-sample"<br />       password = "S@MPLE=PASSWORD="<br />}<br />}</pre>上述指令碼使用 Spark Cassandra 連接器。如需詳細資訊，請參閱[ Cassandra](https://docs.datastax.com/en/developer/java-driver/4.17/manual/core/configuration/reference/) 的參考組態。 | DBA | 
| 設定 Cassandra 驅動程式以連線至 Amazon Keyspaces。 | 使用下列組態指令碼：<pre>datastax-java-driver {<br />basic {<br />  load-balancing-policy {<br />    local-datacenter = us-west-2<br />        }<br />  contact-points = [<br />            "cassandra.us-west-2.amazonaws.com:9142"<br />        ]<br />  request {<br />  page-size = 2500<br />  timeout = 360 seconds<br />  consistency = LOCAL_QUORUM<br />        }<br />    }<br />advanced {<br /> control-connection {<br />  timeout = 360 seconds<br />        }<br /> session-leak.threshold = 6<br /> connection {<br /> connect-timeout = 360 seconds<br /> init-query-timeout = 360 seconds<br /> warn-on-init-error = false<br />        }<br /> auth-provider = {<br />  class = software.aws.mcs.auth.SigV4AuthProvider<br />  aws-region = us-west-2<br /> }<br /><br /> ssl-engine-factory {<br />  class = DefaultSslEngineFactory<br />        }<br />    }<br />}</pre>上述指令碼使用 Spark Cassandra 連接器。如需詳細資訊，請參閱[ Cassandra](https://docs.datastax.com/en/developer/java-driver/4.17/manual/core/configuration/reference/) 的參考組態。 | DBA | 
| 為 AWS Glue 任務建立 IAM 角色。 | 建立名為 的新 AWS 服務角色`glue-cassandra-migration`，以 AWS Glue 做為信任的實體。`glue-cassandra-migration` 應該提供對 S3 儲存貯體和 Amazon Keyspaces 的讀取和寫入存取權。S3 儲存貯體包含 .jar 檔案、Amazon Keyspaces 和 Cassandra 的組態檔案，以及中繼 Parquet 檔案。例如，它包含 `AWSGlueServiceRole`、 `AmazonS3FullAccess`和 `AmazonKeyspacesFullAccess`受管政策。 | AWS DevOps | 
| 在 AWS CloudShell 中下載 CQLReplicator。 | 執行下列命令，將專案下載到您的主資料夾：<pre>git clone https://github.com/aws-samples/cql-replicator.git<br />cd cql-replicator/glue<br /># Only for AWS CloudShell, the bc package includes bc and dc. Bc is an arbitrary precision numeric processing arithmetic language<br />sudo yum install bc -y</pre> |  | 
| 修改參考組態檔案。 | 將 `KeyspacesConnector.conf` `CassandraConnector.conf`和 複製到專案資料夾中的 `../glue/conf`目錄。 | AWS DevOps | 
| 啟動遷移程序。 | 下列命令會初始化 CQLReplicator 環境。初始涉及複製 .jar 成品，以及建立 AWS Glue 連接器、S3 儲存貯體、AWS Glue 任務、 `migration` 金鑰空間和 `ledger`資料表：<pre>cd cql-replicator/glue/bin<br />./cqlreplicator --state init --sg '"sg-1","sg-2"' \ <br />                --subnet "subnet-XXXXXXXXXXXX" \ <br />                --az us-west-2a --region us-west-2 \ <br />                --glue-iam-role glue-cassandra-migration \ <br />                --landing-zone s3://cql-replicator-1234567890-us-west-2<br /></pre>該指令碼包括下列參數：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.html) | AWS DevOps | 
| 驗證部署。 | 在您執行先前的命令後，AWS 帳戶應包含下列項目：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.html) | AWS DevOps | 

### 執行 CQLReplicator
<a name="run-cqlreplicator"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動遷移程序。 | 若要在 AWS Glue 上操作 CQLReplicator，您需要使用 `--state run`命令，後面接著一系列參數。這些參數的精確組態主要取決於您唯一的遷移需求。例如，如果您選擇複寫存留時間 (TTL) 值和更新，或將超過 1 MB 的物件卸載至 Amazon S3，這些設定可能會有所不同。若要將工作負載從 Cassandra 叢集複寫到 Amazon Keyspaces，請執行下列命令：<pre>./cqlreplicator --state run --tiles 8  \<br />                --landing-zone s3://cql-replicator-1234567890-us-west-2 \ <br />                --region us-west-2 \                              <br />                --src-keyspace source_keyspace \ <br />                --src-table source_table \  <br />                --trg-keyspace taget_keyspace \<br />                --writetime-column column_name \<br />                --trg-table target_table --inc-traffic</pre>您的來源金鑰空間和資料表位於 Cassandra 叢集`source_keyspace.source_table`中。您的目標金鑰空間和資料表位於 Amazon Keyspaces `target_keyspace.target_table`中。參數`--inc-traffic`有助於防止增量流量因大量請求而使 Cassandra 叢集和 Amazon Keyspaces 超載。若要複寫更新，請將 `--writetime-column regular_column_name`新增至命令列。一般資料欄將用作寫入時間戳記的來源。 | AWS DevOps | 

### 監控遷移程序
<a name="monitor-the-migration-process"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在歷史遷移階段驗證已遷移的 Cassandra 資料列。 | 若要取得回填階段期間複寫的資料列數，請執行下列命令：<pre>./cqlreplicator --state stats \<br />                --landing-zone s3://cql-replicator-1234567890-us-west-2 \  <br />                --src-keyspace source_keyspace --src-table source_table --region us-west-2</pre> | AWS DevOps | 

### 停止遷移程序
<a name="stop-the-migration-process"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 `cqlreplicator`命令或 AWS Glue 主控台。 | 若要正常停止遷移程序，請執行下列命令：<pre>./cqlreplicator --state request-stop --tiles 8 \                         <br />                --landing-zone s3://cql-replicator-1234567890-us-west-2 \     <br />                --region us-west-2 \                     <br />                --src-keyspace source_keyspace --src-table source_table</pre>若要立即停止遷移程序，請使用 AWS Glue 主控台。 | AWS DevOps | 

### 清除
<a name="clean-up"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除已部署的資源。 | 下列命令會刪除 AWS Glue 任務、連接器、S3 儲存貯體和 Keyspaces 資料表 `ledger`：<pre>./cqlreplicator --state cleanup --landing-zone s3://cql-replicator-1234567890-us-west-2</pre> | AWS DevOps | 

## 疑難排解
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| AWS Glue 任務失敗，並傳回記憶體不足 (OOM) 錯誤。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.html) | 

## 相關資源
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-resources"></a>
+ [CQLReplicator 搭配 AWS Glue https：//README.MD](https://github.com/aws-samples/cql-replicator/blob/main/glue/README.MD)
+ [AWS Glue 文件](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html)
+ [Amazon Keyspaces 文件](https://docs.aws.amazon.com/keyspaces/latest/devguide/what-is-keyspaces.html)
+ [Apache Cassandra](https://cassandra.apache.org/_/index.html)

## 其他資訊
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-additional"></a>

**遷移考量**

您可以使用 AWS Glue 將 Cassandra 工作負載遷移至 Amazon Keyspaces，同時在遷移過程中保持 Cassandra 來源資料庫完全正常運作。複寫完成後，您可以選擇在 Cassandra 叢集和 Amazon Keyspaces 之間，以最小的複寫延遲 （不到 分鐘） 將應用程式切換到 Amazon Keyspaces。若要維持資料一致性，您也可以使用類似的管道，將資料從 Amazon Keyspaces 複寫回 Cassandra 叢集。

**寫入單位計算**

例如，假設您打算在一小時內寫入 500，000，000 且資料列大小為 1 KiB。您需要的 Amazon Keyspaces 寫入單位 WCUs) 總數是根據此計算：

`(number of rows/60 mins 60s) 1 WCU per row = (500,000,000/(60*60s) * 1 WCU) = 69,444 WCUs required`

每秒 69，444 WCUs 是 1 小時的速率，但您可以為額外負荷新增一些緩衝。 例如， `69,444 * 1.10 = 76,388 WCUs`有 10% 的額外負荷。

**使用 CQL 建立金鑰空間**

若要使用 CQL 建立金鑰空間，請執行下列命令：

```
CREATE KEYSPACE target_keyspace WITH replication = {'class': 'SingleRegionStrategy'}
CREATE TABLE target_keyspace.target_table ( userid uuid, level text, gameid int, description text, nickname text, zip text, email text, updatetime text, PRIMARY KEY (userid, level, gameid) ) WITH default_time_to_live = 0 AND CUSTOM_PROPERTIES = {'capacity_mode':{ 'throughput_mode':'PROVISIONED', 'write_capacity_units':76388, 'read_capacity_units':3612 }} AND CLUSTERING ORDER BY (level ASC, gameid ASC)
```

# 從內部部署伺服器將 Oracle Business Intelligence 12c 遷移至 AWS 雲端
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers"></a>

*Lanre (Lan-Ray) showunmi 和 Patrick Yellow，Amazon Web Services*

## 總結
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-summary"></a>

此模式說明如何使用 AWS CloudFormation，將 [Oracle Business Intelligence Enterprise Edition 12c](https://www.oracle.com/business-analytics/business-intelligence/technologies/bi-enterprise-edition.html) 從內部部署伺服器遷移至 AWS 雲端。 AWS CloudFormation 它也說明如何使用其他 AWS 服務來實作 Oracle BI 12c 元件，以提供高可用性、安全性、彈性和動態擴展的能力。

如需將 Oracle BI 12c 遷移至 AWS 雲端的相關最佳實務清單，請參閱此模式**的其他資訊**一節。

**注意**  
最佳實務是先執行多個測試遷移，再將現有的 Oracle BI 12c 資料傳輸至雲端。這些測試可協助您微調遷移方法、識別和修正潛在問題，以及更準確地預估停機時間需求。

## 先決條件和限制
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 透過 AWS [Virtual Private Network (AWS VPN) ](https://aws.amazon.com/vpn/)服務或 AWS [Direct Connect，保護內部部署伺服器與 AWS](https://docs.aws.amazon.com/directconnect/latest/UserGuide/Welcome.html) 之間的網路連線
+ Oracle 作業系統、Oracle BI 12c、Oracle Database、Oracle WebLogic Server 和 Oracle HTTP Server 的軟體授權

**限制**

如需儲存大小限制的資訊，請參閱適用於 [Oracledocumentation 的Amazon Relational Database Service (Amazon RDS)](https://aws.amazon.com/rds/oracle/features/)。

**產品版本**
+ Oracle Business Intelligence Enterprise Edition 12c
+ Oracle WebLogic Server 12c
+ Oracle HTTP 伺服器 12c
+ Oracle 資料庫 12c （或更新版本）
+ Oracle Java SE 8

## Architecture
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-architecture"></a>

下圖顯示在 AWS 雲端中執行 Oracle BI 12c 元件的範例架構：

![\[在 AWS 雲端中執行 Oracle BI 12c 元件的範例架構。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/8bb72df1-7546-4208-bc70-5789767e3600/images/aae8f8f3-8125-4868-a8e5-eac1cc42812f.png)


 

此圖表顯示下列架構：

1. Amazon Route 53 提供網域名稱服務 (DNS) 組態。

1. Elastic Load Balancing (ELB) 會分配網路流量，以改善 Oracle BI 12c 元件跨多個可用區域的可擴展性和可用性。

1. Amazon Elastic Compute Cloud (Amazon EC2) Auto Scaling 群組跨多個可用區域託管 Oracle HTTP 伺服器、Weblogic Admin 伺服器和受管 BI 伺服器。

1. Oracle 資料庫的 Amazon Relational Database Service (Amazon RDS) 會跨多個可用區域存放 BI Server 中繼資料。

1. Amazon Elastic File System (Amazon EFS) 會掛載到每個 Oracle BI 12c 元件以進行共用檔案儲存。

**技術堆疊**
+ Amazon Elastic Block Store (Amazon EBS)
+ Amazon Elastic Compute Cloud (Amazon EC2)
+ Amazon Elastic File System (Amazon EFS)
+ Amazon RDS for Oracle
+ AWS Certificate Manager (ACM)
+ Elastic Load Balancing (ELB)
+ Oracle BI 12c
+ Oracle WebLogic Server 12c
+ Oracle HTTP 伺服器 (OHS)

## 工具
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速一致地佈建資源，以及在整個 AWS 帳戶和區域的生命週期進行管理。
+ [AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) 可協助您建立、存放和續約公有和私有 SSL/TLS X.509 憑證和金鑰，以保護 AWS 網站和應用程式。
+ [AWS Database Migration Service (AWS DMS)](https://docs.aws.amazon.com/dms/latest/userguide/Welcome.html) 可協助您將資料存放區遷移至 AWS 雲端，或在雲端和內部部署設定的組合之間遷移。
+ [Amazon Elastic Compute Cloud (Amazon EC2)](https://docs.aws.amazon.com/ec2/?id=docs_gateway) 在 AWS 雲端中提供可擴展的運算容量。您可以視需要啟動任意數量的虛擬伺服器，並快速向上或向下擴展。
+ [Amazon EC2 Auto Scaling](https://aws.amazon.com/ec2/autoscaling/) 可協助您維持應用程式可用性，並可讓您根據您定義的條件自動新增或移除 Amazon EC2 執行個體。 
+ [Amazon Elastic File System (Amazon EFS)](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) 可協助您在 AWS 雲端中建立和設定共用檔案系統。
+ [Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) 會將傳入的應用程式或網路流量分散到多個目標。例如，您可以在一或多個可用區域中跨 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體、容器和 IP 地址分配流量。
+ [Amazon Relational Database Service (Amazon RDS)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html) 可協助您在 AWS 雲端中設定、操作和擴展關聯式資料庫。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [Amazon Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可協助您在已定義的虛擬網路中啟動 AWS 資源。這個虛擬網路類似於您在自己的資料中心內操作的傳統網路，具有使用可擴展的 AWS 基礎設施的優勢。
+ [Oracle Data Pump](https://docs.oracle.com/cd/B19306_01/server.102/b14215/dp_overview.htm) 可協助您以高速將資料和中繼資料從一個資料庫移至另一個資料庫。
+ [Oracle Fusion Middleware](https://www.oracle.com/middleware/technologies/business-intelligence-v12214-downloads.html) 是一組應用程式開發工具和整合解決方案，可用於身分管理、協同合作和商業智慧報告。
+ [Oracle GoldenGate](https://www.oracle.com/integration/goldengate/#:~:text=OCI%20GoldenGate%20is%20a%20real,in%20the%20Oracle%20Cloud%20Infrastructure.) 可協助您在 Oracle Cloud Infrastructure 中設計、執行、協調和監控資料複寫和串流資料處理解決方案。
+ [Oracle WebLogic 指令碼工具 (WLST)](https://docs.oracle.com/middleware/12213/cross/wlsttasks.htm) 提供命令列界面，可協助您水平擴展 WebLogic 叢集。

## 史詩
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-epics"></a>

### 評估來源環境
<a name="assess-the-source-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 收集軟體庫存資訊。 | 識別每個來源技術堆疊軟體元件的版本和修補程式層級，包括下列項目：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Migration Architect、解決方案架構師、應用程式擁有者、Oracle BI 管理員 | 
| 收集運算和儲存庫存資訊。 | 在您的來源環境中，檢閱下列項目的目前和歷史使用率指標：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html)請務必考慮用量的歷史尖峰。 | 遷移架構師、解決方案架構師、應用程式擁有者、Oracle BI 管理員、系統管理員 | 
| 收集來源環境架構及其需求的相關資訊。 | 充分了解來源環境的架構及其需求，包括對下列項目的了解：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Migration Architect、解決方案架構師、應用程式擁有者、Oracle BI 管理員 | 
| 識別 Java Database Connectivity (JDBC) 資料來源。 | 收集來源環境 JDBC 資料來源及其使用之每個資料庫引擎的驅動程式的相關資訊。 | 遷移架構師、應用程式擁有者、Oracle BI 管理員、資料庫工程師或管理員 | 
| 收集環境特定設定的相關資訊。 | 收集您的來源環境特有的設定和組態相關資訊，包括下列項目：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Migration Architect、解決方案架構師、應用程式擁有者、Oracle BI 管理員 | 
| 識別其他應用程式的任何相依性。 | 收集來源環境中整合的相關資訊，以與其他應用程式建立相依性。請務必識別任何輕量型目錄存取通訊協定 (LDAP) 整合和其他聯網需求。 | Migration Architect、解決方案架構師、應用程式擁有者、Oracle BI 管理員 | 

### 設計您的目標環境
<a name="design-your-target-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立高階設計文件。 | 建立目標架構設計文件。請務必使用您在評估來源環境時所收集的資訊來通知設計文件。 | 解決方案架構師、應用程式架構師、資料庫工程師、遷移架構師 | 
| 取得設計文件的核准。 | 與利益相關者一起檢閱設計文件，並取得必要的核准。 | 應用程式或服務擁有者、解決方案架構師、應用程式架構師 | 

### 部署基礎設施
<a name="deploy-the-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 CloudFormation 中準備基礎設施程式碼。 | 建立 CloudFormation 範本以在 AWS 雲端中佈建 Oracle BI 12c 基礎設施。如需詳細資訊，請參閱《[AWS CloudFormation 使用者指南》中的使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html) *AWS CloudFormation *範本。最佳實務是為每個 Oracle BI 12c 層建立模組化 CloudFormation 範本，而不是為所有資源建立大型範本。如需 CloudFormation 最佳實務的詳細資訊，請參閱 [ AWS 部落格上的使用 AWS CloudFormation 自動化部署時的 8 個最佳實務](https://aws.amazon.com/blogs/infrastructure-and-automation/best-practices-automating-deployments-with-aws-cloudformation/)。 | Cloud Infrastructure Achitect， 解決方案架構師， 應用程式架構師 | 
| 下載必要的軟體。 | 從 [Oracle 網站](https://www.oracle.com/)DDownload下列軟體以及所需的版本和修補程式：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 遷移架構師、資料庫工程師、應用程式架構師 | 
| 準備安裝指令碼。 | 建立執行無訊息安裝的軟體安裝指令碼。這些指令碼可簡化部署自動化。如需詳細資訊，請參閱 Oracle [Support 網站上的 OBIEE 12c：如何執行無提示安裝？](https://support.oracle.com/knowledge/Enterprise%20Performance%20Management%20and%20Business%20Intelligence/2267490_1.html)。您需要 Oracle Support 帳戶才能檢視文件。 | 遷移架構師、資料庫工程師、應用程式架構師 | 
| 為您的 Web 和應用程式層建立 Amazon EBS 支援的 Linux AMI。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 遷移架構師、資料庫工程師、應用程式架構師 | 
| 使用 CloudFormation 啟動您的 AWS 基礎設施。 | 使用您建立的 CloudFormation 範本，在模組中部署 Oracle BI 12c Web 和應用程式層。如需說明，請參閱《[AWS CloudFormation 使用者指南](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/GettingStarted.html)*》中的 AWS CloudFormation *入門。 | 雲端基礎設施架構師、解決方案架構師、應用程式架構師 | 

### 使用全新安裝將 Oracle BI 12c 遷移至 AWS
<a name="migrate-oracle-bi-12c-to-aws-by-using-a-fresh-installation"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 暫存所需的軟體。 | 將必要的軟體放置在可供 Amazon EC2 執行個體存取的位置。例如，您可以在 Amazon S3 或另一個可供 Web 和應用程式伺服器存取的 Amazon EC2 執行個體中暫存軟體。 | Migration Architect， Oracle BI Architect， Cloud Infrastructure Achitect， Solutions Architect， Application Architect | 
| 準備您的儲存庫資料庫以進行 Oracle BI 12c 安裝。 | 透過在新的 Amazon RDS for Oracle 資料庫執行個體上執行 [Oracle 儲存庫建立公用程式 (RCU)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Oracle.Resources.RCU.html#Oracle.Resources.RCU.Installing) 來建立 Oracle BI 12c 結構描述。 [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Oracle.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Oracle.html) | Cloud Infrastructure Achitect、解決方案架構師、應用程式架構師、遷移架構師、Oracle BI 架構師 | 
| 安裝 Oracle Fusion Middleware 12c 和 Oracle BI 12c。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Migration Architect，Oracle BI Architect | 
| 設定 Oracle BI 12c 的 Oracle WebLogic Server 網域。 | 將您的 Oracle BI 12c 網域設定為非叢集部署。如需詳細資訊，請參閱《*Oracle Fusion Middleware Enterprise Deployment Guide for Oracle Business Intelligence*》中的[設定 BI 網域](https://docs.oracle.com/middleware/bi12214/lcm/BIEDG/GUID-FD80C4C4-A2E9-4190-8B6A-7AD659D8FBE2.htm#BIEDG-GUID-D4FC2F0A-88B0-453C-BF14-17D365018252)。 | Migration Architect，Oracle BI Architect | 
| 從 Oracle BI 12c 執行水平擴展。 | 水平擴展單一節點至所需的節點數量。如需詳細資訊，請參閱《[Oracle Fusion Middleware Enterprise Deployment Guide for Oracle Business Intelligence》中的擴展](https://docs.oracle.com/middleware/bi12214/lcm/BIEDG/GUID-B7BEA45C-A8C0-4591-B748-FC35C587DAE0.htm#BIEDG-GUID-B7BEA45C-A8C0-4591-B748-FC35C587DAE0) *Oracle Business Intelligence*。 | Migration Architect，Oracle BI Architect | 
| 安裝 Oracle HTTP Server 12c。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Migration Architect，Oracle BI Architect | 
| 設定 SSL 終止的負載平衡器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 雲端基礎設施架構師、遷移架構師 | 
| 將商業智慧中繼資料成品遷移至 AWS。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Migration Architect，Oracle BI Architect | 
| 執行遷移後任務。 | 匯入 BAR 檔案之後，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Migration Architect，Oracle BI Architect | 

### 測試新環境
<a name="test-the-new-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 測試新的 Oracle BI 12c 環境。 | 在新的 Oracle BI 12c 環境上執行end-to-end測試。盡可能使用自動化。測試活動的範例包括下列項目：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html)視需要執行額外的測試和驗證。 | Migration Architect、解決方案架構師、應用程式擁有者、Oracle BI 管理員 | 

### 切換到新環境
<a name="cut-over-to-the-new-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 中斷內部部署 Oracle BI 12c 環境的流量。 | 在指定的切換視窗中，停止所有流向內部部署 Oracle BI 12c 環境的流量。 | Migration Architect、解決方案架構師、應用程式擁有者、Oracle BI 管理員 | 
| 重新同步新的 Oracle BI 12c 儲存庫資料庫與來源資料庫。 | 重新同步 Amazon RDS Oracle BI 12c 儲存庫資料庫與內部部署資料庫。若要同步資料庫，您可以使用 [Oracle Data Pump 重新整理](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Oracle.Procedural.Importing.DataPump.html)或 [AWS DMS 變更資料擷取 (CDC)](https://aws.amazon.com/blogs/database/migrating-oracle-databases-with-near-zero-downtime-using-aws-dms/)。 | Oracle BI 管理員、資料庫工程師/管理員 | 
| 切換您的 Oracle BI 12c URLs 以指向新的 AWS 環境。 | 更新內部 DNS 伺服器上的 Oracle BI 12c URLs，使其指向新的 AWS 安裝。 | Migration Architect、解決方案架構師、應用程式擁有者、Oracle BI 管理員 | 
| 監控新環境。 | 使用下列任一工具監控新的 Oracle BI 12c 環境：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Oracle BI 管理員、資料庫工程師/管理員、應用程式管理員 | 
| 取得專案的簽署。 | 與利益相關者一起檢閱測試結果，並取得必要的核准來包裝遷移。 | 應用程式擁有者、服務擁有者、雲端基礎設施架構師、遷移架構師、Oracle BI 架構師 | 

## 相關資源
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-resources"></a>
+ [在 RDS for Oracle 上使用 Oracle 儲存庫建立公用程式](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Oracle.Resources.RCU.html) (*Amazon RDS 使用者指南*)
+ [Oracle on Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Oracle.html) (*Amazon RDS 使用者指南*)
+ [AWS 上的 Oracle WebLogic Server 12c](https://d1.awsstatic.com/whitepapers/Oracle-WebLogic-12c-on-AWS.pdf) (AWS 白皮書）
+ [部署 Oracle Business Intelligence 以獲得高可用性 ](https://docs.oracle.com/middleware/1221/biee/BIESG/highavail.htm#BIESG1584)(Oracle 說明中心）
+ [Oracle Business Intelligence 應用程式封存 (BAR) 檔案](https://docs.oracle.com/middleware/bi12214/biee/BIESG/GUID-7FCD90A3-E005-49BF-902F-30FBF9B41B07.htm#BIESG2889) (Oracle 說明中心）
+ [如何在環境之間遷移 OBI 12c](https://support.oracle.com/knowledge/Enterprise%20Performance%20Management%20and%20Business%20Intelligence/2203360_1.html) (Oracle Support) 

## 其他資訊
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-additional"></a>

以下是與將 Oracle BI 12c 遷移至 AWS 雲端相關的最佳實務清單。

**儲存庫資料庫**

最佳實務是在 Amazon RDS for Oracle 執行個體上託管 Oracle BI 12c 資料庫結構描述。此執行個體類型提供經濟實惠且可調整大小的容量，同時自動化管理任務，例如硬體佈建、資料庫設定、修補和備份。

如需詳細資訊，請參閱《*Amazon* [RDS 使用者指南》中的在 RDS for Oracle 上使用 Oracle 儲存庫建立公用程式](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Oracle.Resources.RCU.html)。

**Web 和應用程式層**

[記憶體最佳化的 Amazon EC2 執行個體](https://aws.amazon.com/ec2/instance-types/)通常非常適合 Oracle BI 12c 伺服器。無論您選擇何種執行個體類型，請確定您佈建的執行個體符合您系統的記憶體使用需求。此外，請確定您根據 Amazon EC2 執行個體的可用記憶體[設定足夠的 WebLogic Java 虛擬機器 (JVM) 堆積大小](https://docs.oracle.com/cd/E49933_01/server.770/es_install/src/tins_postinstall_jvm_heap.html#:~:text=The%20default%20JVM%20heap%20size%20for%20WebLogic%20is%203GB.,file%20for%20Linux%20or%20setDomainEnv.)。

**本機儲存**

I/O 在 Oracle BI 12c 應用程式的整體效能中扮演重要角色。Amazon Elastic Block Store (Amazon EBS) 提供針對不同工作負載模式最佳化的不同儲存類別。請務必選擇適合您使用案例的 Amazon EBS 磁碟區類型。

如需 EBS 磁碟區類型的詳細資訊，請參閱 [Amazon EBS 文件中的 Amazon EBS 功能](https://aws.amazon.com/ebs/features/)。

**共用儲存**

叢集 Oracle BI 12c 網域需要下列資源的共用儲存：
+ 組態檔案
+ Oracle BI 12c 單一資料目錄 (SDD)
+ Oracle 全域快取
+ Oracle BI 排程器指令碼
+ Oracle WebLogic Server 二進位檔

您可以使用[Amazon EFS](https://aws.amazon.com/efs/) 來滿足此共用儲存需求，該 EFS 提供可擴展、全受管的彈性網路檔案系統 (NFS) 檔案系統。

*微調共用儲存效能*

Amazon EFS 有兩種[輸送量模式](https://docs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes)：**佈建**和**爆量**。服務也有兩種[效能模式](https://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes)：**一般用途**和**最大 I/O**。

若要微調效能，請先在**一般用途**效能模式和**佈建**輸送量模式下測試工作負載。執行這些測試可協助您判斷這些基準模式是否足以滿足所需的服務水準。

如需詳細資訊，請參閱《[Amazon EFS 使用者指南》中的 Amazon EFS 效能](https://docs.aws.amazon.com/efs/latest/ug/performance.html)。 * EFS *

**可用性和災難復原**

最佳實務是在多個可用區域部署 Oracle BI 12c 元件，以便在可用區域故障時保護這些資源。以下是 AWS 雲端中託管之特定 Oracle BI 12c 資源的可用性和災難復原最佳實務清單：
+ **Oracle BI 12c 儲存庫資料庫**：將多可用區域 Amazon RDS 資料庫執行個體部署至 Oracle BI 12crepository 資料庫。在多可用區域部署中，Amazon RDS 會自動在不同的可用區域中佈建和維護同步待命複本。跨可用區域執行 Oracle BI 12c 儲存庫資料庫執行個體，可以在計劃的系統維護期間增強可用性，並協助保護您的資料庫免於執行個體和可用區域故障。
+ **Oracle BI 12c 受管伺服器**：為實現容錯能力，最佳實務是在設定為跨越多個可用區域的 Amazon EC2 Auto Scaling 群組中的受管伺服器上部署 Oracle BI 12c 系統元件。 Auto Scaling Auto Scaling 會根據[Amazon EC2 運作狀態檢查](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-health-checks.html)取代故障的執行個體。如果發生可用區域故障，Oracle HTTP 伺服器會繼續將流量導向正常運作可用區域中的受管伺服器。然後，Auto Scaling 會啟動執行個體，以符合您的主機計數需求。建議啟用 HTTP 工作階段狀態複寫，以協助確保現有工作階段順利容錯移轉至正常運作的受管伺服器。
+ **Oracle BI 12c 管理伺服器：**為了確保您的管理伺服器具有高可用性，請將它託管在設定為跨越多個可用區域的 Amazon EC2 Auto Scaling 群組中。然後，將群組的最小和最大大小設定為 **1**。如果發生可用區域故障，Amazon EC2 Auto Scaling 會在替代可用區域中啟動替代的管理伺服器。若要復原相同可用區域內任何失敗的基礎主機，您可以啟用[Amazon EC2 Auto Recovery](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-recover.html)。
+ **Oracle Web 層伺服器：**最佳實務是將 Oracle HTTP 伺服器與 Oracle WebLogic Server 網域建立關聯。為了獲得高可用性，請將 Oracle HTTP 伺服器部署在設定為擔任多個可用區域的 Amazon EC2 Auto Scaling 群組中。然後，將伺服器放在 ELB 彈性負載平衡器後方。若要提供額外的主機故障保護，您可以啟用 Amazon EC2 Auto Recovery。

**可擴展性**

AWS 雲端的彈性可協助您水平或垂直擴展應用程式，以回應工作負載需求。

*垂直擴展*

若要垂直擴展應用程式，您可以變更執行 Oracle BI 12c 元件的 Amazon EC2 執行個體的大小和類型。您不需要在部署開始時過度佈建執行個體，並產生不必要的成本。 

*水平擴展*

Amazon EC2 Auto Scaling 會根據工作負載需求自動新增或移除受管伺服器，協助您水平擴展應用程式。

**注意**  
使用 Amazon EC2 Auto Scaling 水平擴展需要指令碼編寫技能和徹底測試才能實作。

**備份和復原**

以下是 AWS 雲端中託管之特定 Oracle BI 12c 資源的備份和復原最佳實務清單：
+ **Oracle Business Intelligence 中繼資料儲存庫：**Amazon RDS 會自動建立和儲存資料庫執行個體的備份。這些備份會保留您指定的一段時間。請務必根據資料保護需求來設定 Amazon RDS 備份持續時間和保留設定。如需詳細資訊，請參閱 [Amazon RDS 備份和還原](https://aws.amazon.com/rds/features/backup/)。
+ **受管伺服器、管理伺服器和 Web 層伺服器：**請確定您根據資料保護和保留需求設定 [Amazon EBS 快照](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html)。
+ **共用儲存：**您可以使用 [AWS Backup](https://docs.aws.amazon.com/efs/latest/ug/awsbackup.html) Backup 管理存放在 Amazon EFS 中的檔案的備份和復原。AWS Backup 服務也可以部署，以集中管理其他服務的備份和復原，包括 Amazon EC2、Amazon EBS 和 Amazon RDS。如需詳細資訊，請參閱[什麼是 AWS Backup？](https://docs.aws.amazon.com/aws-backup/latest/devguide/whatisbackup.html) 在 *AWS Backup 開發人員指南*中。

**安全性與合規性**

以下是安全最佳實務和 AWS 服務的清單，可協助您保護 AWS 雲端中的 Oracle BI 12c 應用程式：
+ **靜態加密：**Amazon RDS、Amazon EFS 和 Amazon EBS 都支援業界標準加密演算法。您可以使用 [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 來建立和管理密碼編譯金鑰，並控制它們在 AWS 服務和應用程式中的使用。您也可以在託管 [Oracle BI 12c 儲存庫資料庫的 Amazon RDS for Oracle 資料庫執行個體上設定 Oracle 透明資料加密 (TDE)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.Oracle.Options.AdvSecurity.html)。
+ **傳輸中加密：**最佳實務是啟用 SSL 或 TLS 通訊協定，以保護 Oracle BI 12c 安裝的各個層之間的傳輸中資料。您可以使用 [AWS Certificate Manager (ACM)](https://aws.amazon.com/certificate-manager/) 為您的 Oracle BI 12c 資源佈建、管理和部署公有和私有 SSL 和 TLS 憑證。
+ **網路安全**：請確定您在已針對使用案例設定適當存取控制的 Amazon VPC 中部署 Oracle BI 12c 資源。設定您的安全群組，以篩選執行安裝之 Amazon EC2 執行個體的傳入和傳出流量。此外，請務必設定[網路存取控制清單 (NACLs)](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html)，以根據定義的規則允許或拒絕流量。
+ **監控和記錄**：您可以使用 [AWS CloudTrail](https://aws.amazon.com/cloudtrail/) 追蹤對 AWS 基礎設施的 API 呼叫，包括 Oracle BI 12c 資源。此功能在追蹤基礎設施的變更或執行安全分析時非常有用。您也可以使用 [Amazon CloudWatch](https://aws.amazon.com/cloudwatch/) 來檢視操作資料，讓您深入了解 Oracle BI 12c 應用程式的效能和運作狀態。您也可以設定警示，並根據這些警示採取自動化動作。Amazon RDS 提供額外的監控工具，包括[增強型監控](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Monitoring.OS.html)和[效能詳情](https://aws.amazon.com/rds/performance-insights/)。

# 將 ELK 堆疊遷移至 AWS 上的彈性雲端
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws"></a>

*Battulga Purevragchaa 和 Antony Prasad Thevaraj，Amazon Web Services*

*uday reddy，無*

## 總結
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-summary"></a>

[Elastic](https://www.elastic.co/) 已提供服務多年，其使用者和客戶通常會在內部部署中自行管理 Elastic。[Elastic Cloud](https://www.elastic.co/cloud) 是受管 [Elasticsearch 服務](https://www.elastic.co/elasticsearch/service)，提供一種使用 Elastic Stack (ELK Stack) 和解決方案的方法，用於[企業搜尋](https://www.elastic.co/enterprise-search)、[可觀測性](https://www.elastic.co/observability)[和安全性](https://www.elastic.co/security)。您可以使用 Logs、Metrics、APM （應用程式效能監控） 和 SIEM （安全資訊和事件管理） 等應用程式來存取彈性解決方案。您可以使用整合功能，例如機器學習、索引生命週期管理、Kibana Lens （用於拖放視覺化）。

當您從自我管理的 Elasticsearch 移至 Elastic Cloud 時，Elasticsearch 服務會處理下列事項：
+ 佈建和管理基礎基礎設施
+ 建立和管理 Elasticsearch 叢集
+ 向上和向下擴展叢集
+ 升級、修補和拍攝快照

這可讓您有更多時間專注於解決其他挑戰。

此模式定義如何將內部部署 Elasticsearch 7.13 遷移至 Amazon Web Services (AWS) 上的 Elastic Cloud。其他版本可能需要稍微修改竊賊模式中描述的程序。如需詳細資訊，請聯絡您的 Elastic 代表。

## 先決條件和限制
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-prereqs"></a>

**先決條件**
+ 可存取快照的 [Amazon Simple Storage Service](https://aws.amazon.com/s3/) (Amazon S3) 的作用中 [AWS 帳戶](https://aws.amazon.com/account/) 
+ 安全且足夠高頻寬的[私有連結](https://docs.aws.amazon.com/vpc/latest/userguide/vpn-connections.html)，可將快照資料檔案複製到 Amazon S3
+ [Amazon S3 Transfer Acceleration](https://aws.amazon.com/s3/transfer-acceleration/)
+ [彈性快照政策](https://www.elastic.co/guide/en/elasticsearch/reference/7.10/getting-started-snapshot-lifecycle-management.html)，以確保資料擷取定期封存至足夠大的本機資料存放區或遠端儲存 (Amazon S3)

您必須了解快照和隨附索引的[生命週期政策](https://www.elastic.co/guide/en/elasticsearch/reference/current/index-lifecycle-management.html)在內部部署中的大小，才能啟動遷移。如需詳細資訊，[請聯絡 Elastic](https://www.elastic.co/contact)。

**角色和技能**

遷移程序也需要下表所述的角色和專業知識。


| 
| 
| Role | 專業知識 | 責任 | 
| --- |--- |--- |
| 應用程式支援 | 熟悉現場部署的 Elastic Cloud 和 Elastic | 所有彈性相關任務 | 
| 系統管理員或 DBA | 深入了解現場部署彈性環境及其組態 | 能夠佈建儲存體、安裝和使用 AWS 命令列界面 (AWS CLI)，並識別提供現場部署彈性的所有資料來源 | 
| 網路管理員 | 了解內部部署到 AWS 網路連線能力、安全性和效能 | 了解連線頻寬，建立從內部部署到 Amazon S3 的網路連結 | 

**限制**
+ Elastic Cloud 上的 Elasticsearch 僅適用於[支援的 AWS 區域 (2021 年 9 月）](https://www.elastic.co/guide/en/cloud/current/ec-regions-templates-instances.html#ec-aws_regions)。

**產品版本**
+ Elasticsearch 7.13

## Architecture
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-architecture"></a>

**來源技術堆疊**

內部部署 Elasticsearch 7.13 或更新版本：
+ 叢集快照
+ 索引快照
+ [Beats](https://www.elastic.co/beats/) 組態

**來源技術架構**

下圖顯示具有不同擷取方法、節點類型和 Kibana 的典型內部部署架構。不同的節點類型反映 Elasticsearch 叢集、身分驗證和視覺化角色。

![\[八個步驟的程序，包括 Beats、Logstash、Elasticsearch 和 Kibana。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/23d1b437-22ff-420e-80ac-834f1116d234/images/937c4d22-429f-4673-86df-ae491d68389c.png)


1. 從 Beats 擷取到 Logstash

1. 從 Beats 擷取到 Apache Kafka 訊息佇列

1. 從 Filebeat 擷取至 Logstash

1. 從 Apache Kafka 訊息佇列擷取至 Logstash

1. 從 Logstash 擷取至 Elasticsearch 叢集

1. Elasticsearch 叢集

1. 身分驗證和通知節點

1. Kibana 和 Blob 節點

**目標技術堆疊**

Elastic Cloud 透過跨叢集複寫部署到您的多個 AWS 區域中的軟體即服務 (SaaS) 帳戶。
+ 叢集快照
+ 索引快照
+ Beats 組態
+ 彈性雲端
+ Network Load Balancer
+ Amazon Route 53
+ Amazon S3

**目標架構**

![\[Route 53 端點會將流量路由到兩個不同區域中的多可用區域環境。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/23d1b437-22ff-420e-80ac-834f1116d234/images/16cbac49-0adb-4469-b546-ae4b1ca35357.png)


 

受管彈性雲端基礎設施為：
+ 高可用性，存在於多個[可用區域](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/)和多個 AWS 區域。
+ 區域容錯，因為使用 Elastic [Cloudcross-cluster 複寫 (CCR) 複寫資料 （索引和快照）](https://www.elastic.co/guide/en/elasticsearch/reference/7.14/xpack-ccr.html)
+ 封存，因為快照會封存在 [Amazon S3](https://aws.amazon.com/s3/?p=pm&c=s3&z=4) 中
+ 透過 Network [Load Balancer ](https://aws.amazon.com/elasticloadbalancing/network-load-balancer/)和 [Route 53](https://aws.amazon.com/route53/) 的組合，可容忍網路分割區
+ 源自 （但不限於） [Elastic APM](https://www.elastic.co/apm/)、[Beats](https://www.elastic.co/beats/)、[Logstash](https://www.elastic.co/guide/en/logstash/current/index.html) 的資料擷取

**高階遷移步驟**

Elastic 已開發自己的規範方法，將內部部署 Elastic Cluster 遷移至 Elastic Cloud。彈性方法直接符合 AWS 遷移指引和最佳實務，包括 [Well-Architected Framework](https://aws.amazon.com/architecture/well-architected/?wa-lens-whitepapers.sort-by=item.additionalFields.sortDate&wa-lens-whitepapers.sort-order=desc) 和 [AWS Migration Acceleration Program](https://aws.amazon.com/migration-acceleration-program/) (MAP)。一般而言，三個 AWS 遷移階段如下：
+ 評估
+ 調動
+ 遷移和現代化

Elastic 遵循具有互補術語的類似遷移階段：
+ 啟動
+ 計畫
+ 實作
+ 交付
+ Close (關閉)

Elastic 使用彈性實作方法，協助交付專案成果。這在設計上具有包容性，以確保彈性、諮詢團隊和客戶團隊以清晰的方式合作，共同交付預期成果。

彈性方法在實作階段將傳統的瀑布假相與 Scrum 結合。技術需求的組態會以協作方式反覆交付，同時將風險降至最低。

![\[圖表顯示彈性實作方法的五個階段。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/23d1b437-22ff-420e-80ac-834f1116d234/images/b041c61d-980e-49a0-a721-791c20edde64.png)


 

## 工具
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-tools"></a>

**AWS 服務**
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) – Amazon Route 53 是高可用性且可擴展的網域名稱系統 (DNS) Web 服務。您可以使用 Route 53 執行三個主要功能的任意組合：網域註冊、DNS 路由和運作狀態檢查。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一種物件儲存服務。您可以使用 Amazon S3 隨時從 Web 任何地方存放和擷取任意資料量。此模式使用 S3 儲存貯體和 [Amazon S3 Transfer Acceleration](https://docs.aws.amazon.com/AmazonS3/latest/userguide/transfer-acceleration-examples.html)。
+ [Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) – Elastic Load Balancing 會自動將傳入流量分散到一或多個可用區域中的多個目標，例如 EC2 執行個體、容器和 IP 地址。

**其他工具**
+ [Beats](https://www.elastic.co/beats/) – Beats 從 Logstash 或 Elasticsearch 運送資料
+ [Elastic Cloud](https://www.elastic.co/cloud/) – Elastic Cloud 是一種託管 Elasticsearch 的受管服務。
+ [Elasticsearch](https://www.elastic.co/elasticsearch/) – Elasticsearch 是一種搜尋和分析引擎，使用 Elastic Stack 集中存放您的資料，以進行可擴展的搜尋和分析。此模式也會使用快照建立和跨叢集複寫。
+ [Logstash](https://www.elastic.co/logstash/) – Logstash 是一種伺服器端資料處理管道，可從多個來源擷取資料、轉換資料，然後將其傳送至您的資料儲存體。

## 史詩
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-epics"></a>

### 準備遷移
<a name="prepare-the-migration"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 識別執行內部部署彈性解決方案的伺服器。 | 確認支援彈性遷移。 | 應用程式擁有者 | 
| 了解內部部署伺服器組態。 | 若要了解在內部部署成功驅動工作負載所需的伺服器組態，請尋找目前正在使用的伺服器硬體足跡、網路組態和儲存特性 | 應用程式支援 | 
| 收集使用者和應用程式帳戶資訊。 | 識別內部部署彈性環境所使用的使用者名稱和應用程式名稱。 | 系統管理員、應用程式支援 | 
| 文件 Beats 和資料寄件人組態。 | 若要記錄組態，請查看現有的資料來源和目的地。如需詳細資訊，請參閱[彈性文件](https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html)。 | 應用程式支援 | 
| 判斷資料的速度和數量。 | 建立叢集正在處理多少資料的基準。 | 系統管理員、應用程式支援 | 
| 記錄 RPO 和 RTO 案例。 | 有關中斷和服務水準協議 (SLAs) 的文件復原點目標 (RPO) 和復原時間目標 (RTO) 案例。 | 應用程式擁有者、系統管理員、應用程式支援 | 
| 決定最佳快照生命週期設定。 | 定義在遷移*期間和之後*使用彈性快照保護資料的頻率。 | 應用程式擁有者、系統管理員、應用程式支援 | 
| 定義遷移後效能期望。 | 針對目前和預期的畫面重新整理、查詢執行期和使用者介面行為產生指標。 | 系統管理員、應用程式支援 | 
| 記錄網際網路存取傳輸、頻寬和可用性需求。 | 確定將快照複製到 Amazon S3 的網際網路連線速度、延遲和彈性。 | 網路管理員 | 
| 記錄 Elastic 內部部署執行時間的目前成本。 | 確保 AWS 目標環境的大小設計為高效能且符合成本效益。 | DBA、系統管理員、應用程式支援 | 
| 識別身分驗證和授權需求。 | Elastic Stack 安全功能提供內建領域，例如輕量型目錄存取通訊協定 (LDAP)、安全聲明標記語言 (SAML) 和 OpenID Connect (OIDC)。 | DBA、系統管理員、應用程式支援 | 
| 根據地理位置了解特定法規要求。 | 確保資料根據您的要求和任何相關的國家要求匯出和加密。 | DBA、系統管理員、應用程式支援 | 

### 實作遷移
<a name="implement-the-migration"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 Amazon S3 上準備預備區域。 | 若要在 Amazon S3 上接收快照，[請建立 S3 儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)體和具有新建立儲存貯體完整存取權的臨時 AWS Identity and Access Management (IAM) 角色。如需詳細資訊，請參閱[建立角色以將許可委派給 IAM 使用者](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html)。使用 AWS Security Token Service [請求臨時安全登入](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html)資料。保護存取金鑰 ID、私密存取金鑰和工作階段字符的安全。在儲存貯體上啟用 [Amazon S3 Transfer Acceleration](https://docs.aws.amazon.com/AmazonS3/latest/userguide/transfer-acceleration-examples.html)。 | AWS 管理員 | 
| 在內部部署安裝 AWS CLI 和 Amazon S3 外掛程式。 | 在每個 Elasticsearch 節點上執行下列命令。<pre>sudo bin/elasticsearch-plugin install repository-s3</pre>然後重新啟動節點。 | AWS 管理員 | 
| 設定 Amazon S3 用戶端存取。 | 執行下列命令來新增先前建立的金鑰。<pre>elasticsearch-keystore add s3.client.default.access_key</pre><pre>elasticsearch-keystore add s3.client.default.secret_key</pre><pre>elasticsearch-keystore add s3.client.default.session_token</pre> | AWS 管理員 | 
| 註冊彈性資料的快照儲存庫 | 使用 [Kibana 開發工具](https://www.elastic.co/guide/en/kibana/current/console-kibana.html)來告知內部部署本機叢集要寫入哪個遠端 S3 儲存貯體。 | AWS 管理員 | 
| 設定快照政策。 | 若要設定快照生命週期管理，請在 Kibana **政策**索引標籤上，選擇 **SLM 政策**，並定義應包含的時間、資料串流或索引，以及要使用的名稱。設定經常拍攝快照的政策。快照是增量式的，可有效利用儲存體。符合您的整備評估決策。政策也可以指定[保留政策](https://www.elastic.co/guide/en/elasticsearch/reference/current/slm-retention.html)，並在不再需要快照時自動刪除快照。 | 應用程式支援 | 
| 驗證快照是否正常運作。 | 在 Kibana 開發工具中，執行下列命令。<pre>GET _snapshot/<your_repo_name>/_all</pre> | AWS 管理員、應用程式支援、 | 
| 在 Elastic Cloud 上部署新的叢集。 | [登入 Elastic](https://cloud.elastic.co/login?redirectTo=%2Fhome)，並從準備度評估中的業務調查結果選擇「可觀測性、搜尋或安全性」叢集。 | AWS 管理員、應用程式支援 | 
| 設定叢集金鑰存放區存取權。 | 新叢集需要存取將存放快照的 S3 儲存貯體。在 Elasticsearch 服務主控台上，選擇**安全性**，然後輸入您先前建立的存取和秘密 IAM 金鑰。 | AWS 管理員 | 
| 設定 Elastic Cloud 託管叢集以存取 Amazon S3。 | 在 Amazon S3 中設定對先前建立的快照儲存庫的新叢集存取權。使用 Kibana，執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-an-elk-stack-to-elastic-cloud-on-aws.html) | AWS 管理員、應用程式支援 | 
| 驗證新的 Amazon S3 儲存庫。 | 請確定您可以存取 Elastic Cloud 叢集中託管的新儲存庫。 | AWS 管理員 | 
| 初始化 Elasticsearch 服務叢集。 | 在 Elasticsearch Service Console 上，從 S3 快照初始化 Elasticsearch 服務叢集。執行下列命令做為 POST。<pre>*/_close?expand_wildcards=all</pre><pre>/_snapshot/<your-repo-name>/  <your-snapshot-name>/_restore</pre><pre>*/_open?expand_wildcards=all</pre> | 應用程式支援 | 

### 完成遷移
<a name="complete-the-migration"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證快照還原是否成功。 | 使用 Kibana 開發工具，執行下列命令。<pre>GET _cat/indices</pre> | 應用程式支援 | 
| Redploy 擷取服務。 | 將 Beats 和 Logstash 的端點連接到新的 Elasticsearch 服務端點。 | 應用程式支援 | 

### 測試叢集環境並清除
<a name="test-the-cluster-environment-and-clean-up"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證叢集環境。 | 現場部署彈性叢集環境遷移至 AWS 之後，您就可以連線到該環境，並使用自己的使用者接受度測試 (UAT) 工具來驗證新環境。 | 應用程式支援 | 
| 清除資源。 | 驗證叢集已成功遷移後，請移除 S3 儲存貯體和用於遷移的 IAM 角色。 | AWS 管理員 | 

## 相關資源
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-resources"></a>

**彈性參考**
+ [彈性雲端](https://www.elastic.co/cloud/)
+ [AWS 上的 Managed Elasticsearch 和 Kibana](https://www.elastic.co/elasticsearch/service)
+ [彈性企業搜尋](https://www.elastic.co/enterprise-search)
+ [彈性整合](https://www.elastic.co/integrations?search=amazon)
+ [彈性可觀測性](https://www.elastic.co/observability)
+ [彈性安全性](https://www.elastic.co/security)
+ [打擊](https://www.elastic.co/beats/)
+ [彈性 APM](https://www.elastic.co/apm/)
+ [遷移至索引生命週期管理](https://www.elastic.co/guide/en/cloud-enterprise/current/ece-migrate-index-management.html)
+ [彈性訂閱](https://www.elastic.co/subscriptions)
+ [聯絡彈性](https://www.elastic.co/contact)

*彈性部落格文章*
+ [如何從自我管理的 Elasticsearch 遷移至 AWS 上的 Elastic Cloud](https://www.elastic.co/blog/how-to-migrate-from-self-managed-elasticsearch-to-elastic-cloud-on-aws) （部落格文章）
+ [遷移至 Elastic Cloud](https://www.elastic.co/blog/migrating-to-elastic-cloud) （部落格文章）

*彈性文件*
+ [教學課程：使用 SLM 自動化備份](https://www.elastic.co/guide/en/elasticsearch/reference/7.10/getting-started-snapshot-lifecycle-management.html)
+ [ILM：管理索引生命週期](https://www.elastic.co/guide/en/elasticsearch/reference/current/index-lifecycle-management.html)
+ [Logstash](https://www.elastic.co/guide/en/logstash/current/index.html)
+ [跨叢集複寫 (CCR)](https://www.elastic.co/guide/en/elasticsearch/reference/7.14/xpack-ccr.html)
+ [擷取管道](https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html)
+ [執行 Elasticsearch API 請求](https://www.elastic.co/guide/en/kibana/current/console-kibana.html)
+ [快照保留](https://www.elastic.co/guide/en/elasticsearch/reference/current/slm-retention.html)

*彈性影片和網路研討會*
+ [彈性雲端遷移](https://www.youtube.com/watch?v=WbPJi-APZ_Q)
+ [Elastic Cloud：為什麼客戶要遷移 ](https://www.elastic.co/webinars/elastic-cloud-why-customers-are-migrating-now)（網路研討會）

**AWS 參考**
+ [AWS Marketplace 上的彈性雲端](https://aws.amazon.com/marketplace/seller-profile?id=d8f59038-c24c-4a9d-a66d-6711d35d7305)
+ [AWS 命令列界面](https://docs.aws.amazon.com/AmazonS3/latest/userguide/setup-aws-cli.html)
+ [AWS Direct Connect](https://aws.amazon.com/directconnect/)
+ [Migration Acceleration Program (MAP)](https://aws.amazon.com/migration-acceleration-program/)
+ [Network Load Balancer](https://aws.amazon.com/elasticloadbalancing/network-load-balancer/)
+ [區域與可用區域](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/)
+ [Amazon Route 53](https://aws.amazon.com/route53/)
+ [Amazon Simple Storage Service](https://aws.amazon.com/s3/)
+ [Amazon S3 Transfer Acceleration](https://aws.amazon.com/s3/transfer-acceleration/)
+ [VPN 連線](https://docs.aws.amazon.com/vpc/latest/userguide/vpn-connections.html)
+ [Well-Architected 架構](https://aws.amazon.com/architecture/well-architected/?wa-lens-whitepapers.sort-by=item.additionalFields.sortDate&wa-lens-whitepapers.sort-order=desc)

## 其他資訊
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-additional"></a>

如果您打算遷移複雜的工作負載，請聯絡 [Elastic Consulting Services](https://www.elastic.co/consulting/engage)。如果您有與組態和服務相關的基本問題，請聯絡 [Elastic Support](mailto:support@elastic.co) 團隊。

# AWS 雲端 使用 Starburst 將資料遷移至
<a name="migrate-data-to-the-aws-cloud-by-using-starburst"></a>

*Antony Prasad Thevaraj 和 Suresh Vee Mirrori，Amazon Web Services*

*Shaun Van Staden，無*

## 總結
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-summary"></a>

Starburst 透過提供企業查詢引擎，在單一存取點中將現有資料來源整合在一起，協助加速資料遷移至 Amazon Web Services (AWS) 的旅程。您可以在完成任何遷移計畫之前，跨多個資料來源執行分析，以取得寶貴的洞見。在不中斷business-as-usual分析的情況下，您可以使用 Starburst 引擎或專用擷取、轉換和載入 (ETL) 應用程式來遷移資料。

## 先決條件和限制
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 虛擬私有雲端 (VPC)
+ Amazon Elastic Kubernetes Service (Amazon EKS) 叢集
+ Amazon Elastic Compute Cloud (Amazon EC2) Auto Scaling 群組
+ 需要遷移的目前系統工作負載清單
+ 從 AWS 到內部部署環境的網路連線

## Architecture
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-architecture"></a>

**參考架構**

下列高階架構圖顯示 中 Starburst Enterprise 的典型部署 AWS 雲端：

1. Starburst Enterprise 叢集會在您的 中執行 AWS 帳戶。

1. 使用者使用輕量型目錄存取協定 (LDAP) 或開放授權 (OAuth) 進行身分驗證，並直接與 Starburst 叢集互動。

1. Starburst 可以連線到數個 AWS 資料來源，例如 Amazon Simple Storage Service (Amazon S3) AWS Glue、Amazon Relational Database Service (Amazon RDS) 和 Amazon Redshift。Starburst 可在 、 AWS 雲端內部部署或其他雲端環境中跨資料來源提供聯合查詢功能。

1. 您可以使用 Helm Chart 在 Amazon EKS 叢集中啟動 Starburst Enterprise。

1. Starburst Enterprise 使用 Amazon EC2 Auto Scaling 群組和 Amazon EC2 Spot 執行個體來最佳化基礎設施。

1. Starburst Enterprise 會直接連線到現有的內部部署資料來源，以即時讀取資料。此外，如果您在此環境中有現有的 Starburst Enterprise 部署，則可以直接將 中的新 Starburst 叢集 AWS 雲端 連接到此現有的叢集。

![\[AWS 雲端中 Starburst Enterprise 部署的高階架構圖\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/12ae0463-9029-4a32-9d7b-70cdb5406fb0/images/e9975d3a-f75b-41a2-8c08-5b82539adf8c.png)


請注意以下內容：
+ Starburst 不是資料虛擬化平台。它是一種以 SQL 為基礎的大規模平行處理 (MPP) 查詢引擎，構成用於分析的整體資料網格策略的基礎。
+ 當 Starburst 部署為遷移的一部分時，它可以直接連線至現有的內部部署基礎設施。
+ Starburst 提供數個內建企業和開放原始碼連接器，可促進與各種舊版系統的連線。如需連接器及其功能的完整清單，請參閱 *Starburst Enterprise 使用者指南*中的[連接器](https://docs.starburst.io/latest/connector.html)。
+ Starburst 可以從內部部署資料來源即時查詢資料。這可防止資料遷移時中斷一般業務操作。
+ 如果您要從現有的現場部署 Starburst Enterprise 部署遷移，您可以使用特殊連接器 *Starburst Stargate*，將 中的 Starburst Enterprise 叢集 AWS 直接連接到您的現場部署叢集。當商業使用者和資料分析師將查詢從 聯合 AWS 雲端 到內部部署環境時，這提供額外的效能優勢。

**高階程序概觀**

您可以使用 Starburst 來加速資料遷移專案，因為 Starburst 會在遷移所有資料之前啟用洞見。下圖顯示使用 Starburst 遷移資料的一般程序。

![\[使用 Starburst 將資料遷移至 AWS 雲端的處理流程\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/12ae0463-9029-4a32-9d7b-70cdb5406fb0/images/e79b0084-7275-4824-8854-646236ec23dc.png)


**Roles (角色)**

使用 Starburst 完成遷移通常需要下列角色：
+ **雲端管理員** – 負責讓雲端資源可用於執行 Starburst Enterprise 應用程式
+ **Starburst 管理員** – 負責安裝、設定、管理和支援 Starburst 應用程式
+ **資料工程師** – 負責：
  + 將舊版資料遷移至雲端
  + 建置語意檢視以支援分析
+ **解決方案或系統擁有者** – 負責整體解決方案實作

## 工具
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-tools"></a>

**AWS 服務**
+ [Amazon Elastic Compute Cloud (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 在 AWS 雲端中提供可擴展的運算容量。您可以視需要啟動任意數量的虛擬伺服器，，並快速進行擴展或縮減。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) 可協助您在 上執行 Kubernetes， AWS 而無需安裝或維護您自己的 Kubernetes 控制平面或節點。

**其他工具**
+ [Helm](https://helm.sh/docs/) – Helm 是 Kubernetes 的套件管理員，可協助您在 Kubernetes 叢集上安裝和管理應用程式。
+ [Starburst Enterprise](https://docs.starburst.io/latest/index.html) – Starburst Enterprise 是以 SQL 為基礎的大量平行處理 (MPP) 查詢引擎，構成分析整體資料網格策略的基礎。
+ [Starburst Stargate](https://docs.starburst.io/latest/connector/starburst-stargate.html) – Starburst Stargate 會將一個 Starburst Enterprise 環境中的目錄和資料來源，例如內部部署資料中心的叢集，連結至另一個 Starburst Enterprise 環境中的目錄和資料來源，例如 中的叢集 AWS 雲端。

## 史詩
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-epics"></a>

### 評估資料
<a name="assess-the-data"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 識別您的資料並排定其優先順序。 | 識別您要移動的資料。大型內部部署舊版系統可以包含您想要與您不想要移動或由於合規原因而無法移動的資料一起遷移的核心資料。從資料庫存開始，可協助您排定應該優先鎖定哪些資料的優先順序。如需詳細資訊，請參閱[開始使用自動化產品組合探索](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/get-started-with-automated-portfolio-discovery.html)。 | 資料工程師，DBA | 
| 探索、清查和備份您的資料。 | 驗證使用案例資料的品質、數量和相關性。視需要備份或建立資料的快照，並完成資料的目標環境。 | 資料工程師，DBA | 

### 設定 Starburst Enterprise 環境
<a name="set-up-the-starburst-enterprise-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 中設定 Starburst Enterprise AWS 雲端。 | 當資料編製目錄時，請在受管 Amazon EKS 叢集中設定 Starburst Enterprise。如需詳細資訊，請參閱 *Starburst Enterprise 參考文件中*[的使用 Kubernetes 部署](https://docs.starburst.io/latest/k8s.html)。這允許在資料遷移過程中進行business-as-usual分析。 | AWS 管理員、應用程式開發人員 | 
| 將 Starburst 連接到資料來源。 | 在您識別資料並設定 Starburst Enterprise 之後，請將 Starburst 連線到資料來源。Starburst 會直接從資料來源讀取資料做為 SQL 查詢。如需詳細資訊，請參閱 [Starburst Enterprise 參考文件](https://docs.starburst.io/latest/overview.html)。 | AWS 管理員、應用程式開發人員 | 

### 遷移資料
<a name="migrate-the-data"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建置並執行 ETL 管道。 | 開始資料遷移程序。此活動可以與business-as-usual分析同時進行。對於遷移，您可以使用第三方產品或 Starburst。Starburst 能夠跨不同來源讀取和寫入資料。如需詳細資訊，請參閱 [Starburst Enterprise 參考文件](https://docs.starburst.io/latest/overview.html)。 | 資料工程師 | 
| 驗證資料。 | 遷移資料之後，請驗證資料，以確保所有必要的資料都已移動且完好無損。 | 資料工程師、DevOps 工程師 | 

### 切換
<a name="cut-over"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 剪下資料。 | 資料遷移和驗證完成後，您可以切換資料。這涉及變更 Starburst 中的資料連線連結。您可以指向新的雲端來源並更新語意檢視，而不是指向內部部署來源。如需詳細資訊，請參閱 *Starburst Enterprise 參考文件中*的[連接器](https://docs.starburst.io/latest/connector.html)。 | 資料工程師，Cutover 主管 | 
| 向使用者推出。 | 資料消費者開始處理遷移的資料來源。分析最終使用者看不到此程序。 | Cutover 潛在客戶，資料工程師 | 

## 相關資源
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-resources"></a>

**AWS Marketplace**
+ [Starburst Galaxy](https://aws.amazon.com/marketplace/pp/prodview-yugyv4gbgn5ss?ref_=srh_res_product_title)
+ [Starburst Enterprise](https://aws.amazon.com/marketplace/pp/prodview-pwnl3c6p2jycg?ref_=srh_res_product_title)
+ [Starburst Data JumpStart](https://aws.amazon.com/marketplace/pp/prodview-ou6drb23gch2u?ref_=srh_res_product_title)
+ [Starburst Enterprise 與 Graviton](https://aws.amazon.com/marketplace/pp/prodview-2bpppdqlesn6w?ref_=srh_res_product_title)

**Starburst 文件**
+ [Starburst Enterprise 使用者指南](https://docs.starburst.io/index.html)
+ [Starburst Enterprise 參考文件](https://docs.starburst.io/latest/index.html)

**其他 AWS 文件**
+ [開始使用自動化產品組合探索 ](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/get-started-with-automated-portfolio-discovery.html)(AWS 方案指引）
+ [使用 Starburst on 最佳化雲端基礎設施成本和效能 AWS](https://aws.amazon.com/blogs/architecture/optimizing-cloud-infrastructure-cost-and-performance-with-starburst-on-aws/) (AWS 部落格文章）

# 在 AWS 上最佳化輸入檔案大小的 ETL 擷取
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws"></a>

*Apoorva Patrikar，Amazon Web Services*

## 總結
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-summary"></a>

此模式說明如何在處理您的資料之前最佳化檔案大小，以最佳化 AWS Glue 上大數據和 Apache Spark 工作負載的擷取、轉換和載入 (ETL) 程序的擷取步驟。使用此模式來防止或解決*小型檔案問題*。也就是說，當大量小型檔案因為檔案的彙總大小而減慢資料處理速度時。例如，各僅數百 KB 的數百個檔案可以大幅降低 AWS Glue 任務的資料處理速度。這是因為 AWS Glue 必須在 Amazon Simple Storage Service (Amazon S3) 上執行內部清單函數，而 YARN (Yet Another Resource Negotiator) 必須存放大量中繼資料。若要改善資料處理速度，您可以使用分組讓 ETL 任務將一組輸入檔案讀取至單一記憶體內分割區。分割區會自動將較小的檔案分組在一起。或者，您可以使用自訂程式碼，將批次邏輯新增至現有的檔案。

## 先決條件和限制
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 一或多個 AWS 黏附[任務](https://docs.aws.amazon.com/glue/latest/dg/author-job.html)
+ 一或多個大數據或 [Apache Spark](https://spark.apache.org/) 工作負載
+ [S3 儲存貯體](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html)

## Architecture
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-architecture"></a>

下列模式顯示 AWS Glue 任務如何處理不同格式的資料，然後存放在 S3 儲存貯體中以取得效能的可見性。

![\[AWS Glue 任務會處理不同格式的資料，然後存放在 S3 儲存貯體中。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/88ee332f-2f12-4d88-b491-e78bbb173850/images/9a97b54a-3f67-4a48-94d2-5807373ace25.png)


該圖顯示以下工作流程：

1. 
**注意**  
AWS Glue 任務會將 CSV、JSON 和 Parquet 格式的小型檔案轉換為動態影格。：輸入檔案的大小對 AWS Glue 任務的效能影響最大。

1. AWS Glue 任務會在 S3 儲存貯體中執行內部清單函數。

## 工具
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-tools"></a>
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是全受管 ETL 服務。它可協助您可靠地分類、清理、擴充和移動資料存放區和資料串流之間的資料。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

## 史詩
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-epics"></a>

### 使用分組來最佳化讀取期間的 ETL 擷取
<a name="use-grouping-to-optimize-etl-ingestion-during-reading"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 指定群組大小。 | 如果您有超過 50，000 個檔案，預設會完成分組。不過，您也可以在 `connectionOptions` 參數中指定群組大小，以使用少於 50，000 個檔案的分組。`connectionOptions` 參數位於 `create_dynamic_frame.from_options`方法中。 | 資料工程師 | 
| 撰寫分組程式碼。 | 使用 `create_dynamic_frame`方法來建立動態影格。例如：<pre>S3bucket_node1 = glueContext.create_dynamic_frame.from_options(<br />    format_options={"multiline": False},<br />    connection_type="s3",<br />    format="json",<br />    connection_options={<br />        "paths": ["s3://bucket/prefix/file.json"],<br />        "recurse": True,<br />        "groupFiles": 'inPartition', <br />        "groupSize": 1048576<br />    },<br />    transformation_ctx="S3bucket_node1",<br />)</pre>使用 `groupFiles` 將 Amazon S3 分割區群組中的檔案分組。使用 `groupSize`設定要在記憶體中讀取之群組的目標大小。`groupSize` 以位元組 (1048576 = 1 MB 指定 )。 | 資料工程師 | 
| 將程式碼新增至工作流程。 | 在 AWS Glue 中將分組程式碼新增至您的任務[工作流程](https://docs.aws.amazon.com/glue/latest/dg/workflows_overview.html)。 | 資料工程師 | 

### 使用自訂邏輯來最佳化 ETL 擷取
<a name="use-custom-logic-to-optimize-etl-ingestion"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 選擇語言和處理平台。 | 選擇專為您的使用案例量身打造的指令碼語言和處理平台。 | 雲端架構師 | 
| 撰寫程式碼。 | 撰寫自訂邏輯，將檔案批次處理在一起。 | 雲端架構師 | 
| 將程式碼新增至工作流程。 | 在 AWS Glue 中將程式碼新增至您的任務[工作流程](https://docs.aws.amazon.com/glue/latest/dg/workflows_overview.html)。這可讓您的自訂邏輯在每次執行任務時套用。 | 資料工程師 | 

### 在轉換後寫入資料時重新分割
<a name="repartition-when-writing-data-after-transformation"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 分析消耗模式。 | 了解下游應用程式如何使用您寫入的資料。例如，如果他們每天查詢資料，而且您只有每個區域的分割區資料，或具有非常小的輸出檔案，例如每個檔案 2.5 KB，則這並非消耗的理想選擇。 | DBA | 
| 寫入前重新分割資料。 | 在處理期間 （根據處理邏輯） 和處理後 （根據耗用），根據聯結或查詢重新分割。例如，根據位元組大小重新分割，例如 `.repartition(100000)`，或根據資料欄重新分割，例如 `.repartition("column_name")`。 | 資料工程師 | 

## 相關資源
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-resources"></a>
+ [讀取較大群組中的輸入檔案](https://docs.aws.amazon.com/glue/latest/dg/grouping-input-files.html)
+ [監控 AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/monitor-glue.html)
+ [使用 Amazon CloudWatch 指標監控 AWS Glue ](https://docs.aws.amazon.com/glue/latest/dg/monitoring-awsglue-with-cloudwatch-metrics.html)
+ [任務監控與偵錯](https://docs.aws.amazon.com/glue/latest/dg/monitor-profile-glue-job-cloudwatch-metrics.html)
+ [AWS Glue 上的無伺服器 ETL 入門](https://docs.aws.amazon.com/prescriptive-guidance/latest/serverless-etl-aws-glue/welcome.html)

## 其他資訊
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-additional"></a>

**判斷檔案大小**

無法直接判斷檔案大小是否太大或太小。檔案大小對處理效能的影響取決於叢集的組態。在核心 Hadoop 中，我們建議您使用 128 MB 或 256 MB 的檔案，以充分利用區塊大小。

對於 AWS Glue 上的大多數文字檔案工作負載，我們建議 5-10 DPU 叢集的檔案大小介於 100 MB 到 1 GB 之間。若要找出輸入檔案的最佳大小，請監控 AWS Glue 任務的預先處理區段，然後檢查任務的 CPU 使用率和記憶體使用率。

**其他考量事項**

如果早期 ETL 階段的效能是瓶頸，請考慮在處理之前分組或合併資料檔案。如果您完全控制檔案產生程序，在原始資料傳送至 AWS 之前，在來源系統本身彙總資料點會更有效率。

# 使用 透過驗證、轉換和分割來協調 ETL 管道 AWS Step Functions
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions"></a>

*Sandip Gangapadhyay，Amazon Web Services*

## 總結
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-summary"></a>

此模式說明如何建置無伺服器擷取、轉換和載入 (ETL) 管道，以驗證、轉換、壓縮和分割大型 CSV 資料集，以實現效能和成本最佳化。管道由 協調， AWS Step Functions 並包含錯誤處理、自動重試和使用者通知功能。

當 CSV 檔案上傳至 Amazon Simple Storage Service (Amazon S3) 儲存貯體來源資料夾時，ETL 管道會開始執行。管道會驗證來源 CSV 檔案的內容和結構描述、將 CSV 檔案轉換為壓縮的 Apache Parquet 格式、依年、月和日分割資料集，並將其存放在單獨的資料夾中，以供分析工具處理。

自動執行此模式的程式碼可在具有儲存庫的 [ETL 管道 AWS Step Functions](https://github.com/aws-samples/aws-step-functions-etl-pipeline-pattern)的 GitHub 上取得。

## 先決條件和限制
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶。
+ AWS Command Line Interface (AWS CLI) 已安裝並使用 設定 AWS 帳戶，因此您可以透過部署 AWS CloudFormation 堆疊來建立 AWS 資源。建議使用第 2 AWS CLI 版。如需說明，請參閱 AWS CLI 文件中的[安裝或更新至最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)。如需組態指示，請參閱 AWS CLI 文件中的[組態和登入資料檔案設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)。
+ Amazon S3 儲存貯體。
+ 具有正確結構描述的 CSV 資料集。（此模式隨附的[程式碼儲存庫](https://github.com/aws-samples/aws-step-functions-etl-pipeline-pattern/)提供範例 CSV 檔案，其中包含您可以使用的正確結構描述和資料類型。)
+ 支援 的 Web 瀏覽器 AWS 管理主控台。（請參閱[支援的瀏覽器清單](https://aws.amazon.com/premiumsupport/knowledge-center/browsers-management-console/)。)
+ AWS Glue 主控台存取。
+ AWS Step Functions 主控台存取。

**限制**
+ 在 中 AWS Step Functions，保留歷史記錄日誌的限制上限為 90 天。如需詳細資訊，請參閱 AWS Step Functions 文件中的 [Step Functions 服務配額](https://docs.aws.amazon.com/step-functions/latest/dg/service-quotas.html)。

**產品版本**
+ 適用於 的 Python 3.13 AWS Lambda
+ AWS Glue 4.0 版

## Architecture
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-architecture"></a>

![\[從 S3 來源儲存貯體到 Step Functions、AWS Glue 和 Amazon SNS 的 ETL 程序，分 10 個步驟進行。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/8eb792b0-d35b-4a63-ba2d-71eb8d2c1203/images/054c8e9d-76a2-4334-b21a-cbe76af45923.png)


 

圖表中說明的工作流程包含下列高階步驟：

1. 使用者將 CSV 檔案上傳至 Amazon S3 中的來源資料夾。

1. Amazon S3 通知事件會啟動啟動 AWS Step Functions 狀態機器的 AWS Lambda 函數。

1. Lambda 函數會驗證原始 CSV 檔案的結構描述和資料類型。

1. 根據驗證結果：

   1. 如果驗證來源檔案成功，檔案會移至階段資料夾以進行進一步處理。

   1. 如果驗證失敗，檔案會移至錯誤資料夾，並透過 Amazon Simple Notification Service (Amazon SNS) 傳送錯誤通知。

1.  AWS Glue 爬蟲程式會從 Amazon S3 中的階段資料夾建立原始檔案的結構描述。

1.  AWS Glue 任務會將原始檔案轉換、壓縮和分割為 Parquet 格式。

1.  AWS Glue 任務也會將檔案移至 Amazon S3 中的轉換資料夾。

1.  AWS Glue 爬蟲程式會從轉換的檔案建立結構描述。產生的結構描述可供任何分析任務使用。您也可以使用 Amazon Athena 執行臨機操作查詢。

1. 如果管道完成時沒有發生錯誤，結構描述檔案會移至封存資料夾。如果遇到任何錯誤，檔案會改為移至錯誤資料夾。

1. Amazon SNS 會根據管道完成狀態傳送通知，指出成功或失敗。

此模式中使用的所有 AWS 資源都是無伺服器。沒有要管理的伺服器。

## 工具
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-tools"></a>

**AWS 服務**
+ [AWS Glue](https://aws.amazon.com/glue/) – AWS Glue 是一種全受管 ETL 服務，可讓客戶輕鬆準備和載入其資料以進行分析。
+ [AWS Step Functions](https://aws.amazon.com/step-functions/) – AWS Step Functions 是一種無伺服器協同運作服務，可讓您結合 AWS Lambda 函數和其他 AWS 服務 來建置業務關鍵型應用程式。透過 AWS Step Functions 圖形主控台，您會將應用程式的工作流程視為一系列的事件驅動步驟。
+ [Amazon S3](https://aws.amazon.com/s3/) – Amazon Simple Storage Service (Amazon S3) 是一種物件儲存服務，可提供業界領先的可擴展性、資料可用性、安全性和效能。
+ [Amazon SNS](https://aws.amazon.com/sns/) – Amazon Simple Notification Service (Amazon SNS) 是一種高可用性、耐用、安全、全受管的 pub/sub 訊息服務，可讓您解耦微服務、分散式系統和無伺服器應用程式。
+ [AWS Lambda](https://aws.amazon.com/lambda/) – AWS Lambda 是一種運算服務，可讓您在不佈建或管理伺服器的情況下執行程式碼。 只會在需要時 AWS Lambda 執行程式碼，並自動擴展，從每天的幾個請求擴展到每秒數千個請求。

**Code**

此模式的程式碼可在具有儲存庫的 [ETL 管道 AWS Step Functions](https://github.com/aws-samples/aws-step-functions-etl-pipeline-pattern)的 GitHub 上取得。程式碼儲存庫包含下列檔案和資料夾：
+ `template.yml` – AWS CloudFormation 使用 範本建立 ETL 管道 AWS Step Functions。
+ `parameter.json` – 包含所有參數和參數值。您可以更新此檔案以變更參數值，如 *Epics* 一節中所述。
+ `myLayer/python` 資料夾 – 包含建立此專案所需 AWS Lambda layer 所需的 Python 套件。
+ `lambda` 資料夾 – 包含下列 Lambda 函數：
  + `move_file.py` – 將來源資料集移至封存、轉換或錯誤資料夾。
  + `check_crawler.py` – 在傳送失敗訊息之前，檢查 AWS Glue 爬蟲程式的狀態，其次數與`RETRYLIMIT `環境變數所設定的次數相同。
  + `start_crawler.py` – 啟動 AWS Glue 爬蟲程式。
  + `start_step_function.py` – 開始 AWS Step Functions。
  + `start_codebuild.py` – 啟動 AWS CodeBuild 專案。
  + `validation.py` – 驗證輸入原始資料集。
  + `s3object.py` – 在 Amazon S3 儲存貯體內建立所需的目錄結構。
  + `notification.py` – 在管道結尾傳送成功或錯誤通知。

若要使用範例程式碼，請遵循 *Epics* 區段中的指示。

## 史詩
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-epics"></a>

### 準備來源檔案
<a name="prepare-the-source-files"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製範本程式碼儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 開發人員 | 
| 更新參數值。 | 在儲存庫的本機副本中，編輯 `parameter.json` 檔案並更新預設參數值，如下所示：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 開發人員 | 
| 將原始碼上傳至 Amazon S3 儲存貯體。 | 部署自動化 ETL 管道的 AWS CloudFormation 範本之前，您必須封裝範本的來源檔案，並將其上傳至 Amazon S3 儲存貯體。若要執行此操作，請使用預先設定的設定檔執行下列 AWS CLI 命令：<pre>aws cloudformation package --template-file template.yml --s3-bucket <bucket_name> --output-template-file packaged.template --profile <profile_name></pre>其中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 開發人員 | 

### 建立 堆疊。
<a name="create-the-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 CloudFormation 範本。 | 若要部署 AWS CloudFormation 範本，請執行下列 AWS CLI 命令：<pre>aws cloudformation deploy --stack-name <stack_name> --template-file packaged.template --parameter-overrides file://parameter.json --capabilities CAPABILITY_IAM --profile <profile_name></pre>其中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 開發人員 | 
| 檢查進度。 | 在 [AWS CloudFormation 主控台](https://console.aws.amazon.com/cloudformation/)上，檢查堆疊開發的進度。當狀態為 時`CREATE_COMPLETE`，堆疊已成功部署。 | 開發人員 | 
| 請記下 AWS Glue 資料庫名稱。 | 堆疊的**輸出**索引標籤會顯示 AWS Glue 資料庫的名稱。金鑰名稱為 `GlueDBOutput`。 | 開發人員 | 

### 測試管道
<a name="test-the-pipeline"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動 ETL 管道。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 開發人員 | 
| 檢查分割的資料集。 | 當 ETL 管道完成時，請確認 Amazon S3 轉換資料夾 ( `transform`或您在 `parameter.json` 檔案中設定的資料夾名稱） 中有可用的分割資料集。 | 開發人員 | 
| 檢查分割的 AWS Glue 資料庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 開發人員 | 
| 執行查詢。 | （選用） 使用 Amazon Athena 在分割和轉換的資料庫上執行臨機操作查詢。如需說明，請參閱 AWS 文件中的[在 Amazon Athena 中執行 SQL 查詢](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)。 | 資料庫分析師 | 

## 疑難排解
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| AWS Identity and Access Management AWS Glue 任務和爬蟲程式的 (IAM) 許可 | 如果您進一步自訂 AWS Glue 任務或爬蟲程式，請務必在 AWS Glue 任務使用的 IAM 角色中授予適當的 IAM 許可，或提供資料許可給 AWS Lake Formation。如需詳細資訊，請參閱 [AWS 文件](https://docs.aws.amazon.com/lake-formation/latest/dg/upgrade-glue-lake-formation.html)。 | 

## 相關資源
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-resources"></a>

**AWS 服務 文件**
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/)
+ [AWS Glue](https://docs.aws.amazon.com/glue/)
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/)
+ [Amazon S3](https://docs.aws.amazon.com/s3/)
+ [Amazon SNS](https://docs.aws.amazon.com/sns/)

## 其他資訊
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-additional"></a>

下圖顯示來自 AWS Step Functions **Inspector** 面板的成功 ETL 管道 AWS Step Functions 工作流程。** **

![\[Step Functions 工作流程，用於驗證輸入 .csv、爬取資料和執行 AWS Glue 任務。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/8eb792b0-d35b-4a63-ba2d-71eb8d2c1203/images/bd77de7b-4d04-44bb-95d2-3ec4599b3770.png)


下圖顯示 Step Functions **Inspector** 面板中，因輸入驗證錯誤而失敗之 ETL 管道的 AWS Step Functions 工作流程。

![\[Step Functions 工作流程失敗，因此檔案會移至錯誤資料夾。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/8eb792b0-d35b-4a63-ba2d-71eb8d2c1203/images/5fd7dd79-ba4c-4c20-b1f0-ad4b5f22bdfc.png)


 

# 使用 Amazon Redshift ML 執行進階分析
<a name="perform-advanced-analytics-using-amazon-redshift-ml"></a>

*Po Hong 和 Chyanna Antonio，Amazon Web Services*

## 總結
<a name="perform-advanced-analytics-using-amazon-redshift-ml-summary"></a>

在 Amazon Web Services (AWS) 雲端上，您可以使用 Amazon Redshift Machine Learning (Amazon Redshift ML) 對存放在 Amazon Redshift 叢集或 Amazon Simple Storage Service (Amazon S3) 中的資料執行 ML 分析。Amazon Redshift ML 支援監督式學習，通常用於進階分析。Amazon Redshift ML 的使用案例包括營收預測、信用卡詐騙偵測，以及客戶生命週期價值 (CLV) 或客戶流失預測。

Amazon Redshift ML 可讓資料庫使用者使用標準 SQL 命令輕鬆建立、訓練和部署 ML 模型。Amazon Redshift ML 使用 Amazon SageMaker Autopilot 根據您的資料自動訓練和調整分類或迴歸的最佳 ML 模型，同時保留控制和可見性。

Amazon Redshift、Amazon S3 和 Amazon SageMaker 之間的所有互動都會被抽象化和自動化。訓練並部署 ML 模型後，它在 Amazon Redshift 中會變成[使用者定義函數](https://docs.aws.amazon.com/redshift/latest/dg/user-defined-functions.html) (UDF)，可用於 SQL 查詢。 

此模式補充了 AWS 部落格中的[使用 SQL 搭配 Amazon Redshift ML 在 Amazon Redshift 中建立、訓練和部署 ML 模型](https://aws.amazon.com/blogs/big-data/create-train-and-deploy-machine-learning-models-in-amazon-redshift-using-sql-with-amazon-redshift-ml/)，以及[入門資源中心的](https://aws.amazon.com/getting-started/)[建置、訓練和部署 ML 模型 Amazon SageMaker](https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/)教學。

## 先決條件和限制
<a name="perform-advanced-analytics-using-amazon-redshift-ml-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ Amazon Redshift 資料表中的現有資料

**技能**
+ 熟悉 Amazon Redshift ML 所使用的術語和概念，包括*機器學習*、*訓練*和*預測*。如需詳細資訊，請參閱《Amazon Machine Learning (Amazon ML) 文件》中的[訓練 ML 模型](https://docs.aws.amazon.com/machine-learning/latest/dg/training-ml-models.html)。
+ 具有 Amazon Redshift 使用者設定、存取管理和標準 SQL 語法的經驗。如需詳細資訊，請參閱[《Amazon Redshift 文件](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html)》中的 Amazon Redshift 入門。
+ Amazon S3 和 AWS Identity and Access Management (IAM) 的知識和經驗。 
+ 在 AWS Command Line Interface (AWS CLI) 中執行命令的經驗也很有幫助，但並非必要。

**限制**
+ Amazon Redshift 叢集和 S3 儲存貯體必須位於相同的 AWS 區域。
+ 此模式的方法僅支援監督式學習模型，例如迴歸、二進位分類和多類別分類。 

## Architecture
<a name="perform-advanced-analytics-using-amazon-redshift-ml-architecture"></a>

![\[工作流程顯示 Amazon Redshift ML 如何與 SageMaker 搭配使用，以建置、訓練和部署 ML 模型。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/3b6a5f49-c647-45f4-940e-b623f989326a/images/36cc39fe-c1f3-4d68-b89e-e636156001a6.png)


下列步驟說明 Amazon Redshift ML 如何與 SageMaker 搭配使用來建置、訓練和部署 ML 模型： 

1. Amazon Redshift 會將訓練資料匯出至 S3 儲存貯體。

1. SageMaker Autopilot 會自動預先處理訓練資料。

1. 叫用`CREATE MODEL`陳述式之後，Amazon Redshift ML 會使用 SageMaker 進行訓練。

1. SageMaker Autopilot 會搜尋並建議 ML 演算法和最佳化評估指標的最佳超參數。

1. Amazon Redshift ML 會將輸出 ML 模型註冊為 Amazon Redshift 叢集中的 SQL 函數。

1. ML 模型的 函數可用於 SQL 陳述式。 

**技術堆疊**
+ Amazon Redshift
+ SageMaker
+ Amazon S3

## 工具
<a name="perform-advanced-analytics-using-amazon-redshift-ml-tools"></a>
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/dg/welcome.html) – Amazon Redshift 是一種企業級的 PB 級全受管資料倉儲服務。
+ [Amazon Redshift ML](https://docs.aws.amazon.com/redshift/latest/dg/machine_learning.html) – Amazon Redshift Machine Learning (Amazon Redshift ML) 是一種強大的雲端服務，可讓所有技能水準的分析師和資料科學家輕鬆使用 ML 技術。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是網際網路的儲存體。 
+ [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) – SageMaker 是全受管 ML 服務。 
+ [Amazon SageMaker Autopilot](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-automate-model-development.html) – SageMaker Autopilot 是一種功能集，可自動執行自動機器學習 (AutoML) 程序的關鍵任務。

 

**Code**

您可以使用下列程式碼，在 Amazon Redshift 中建立受監督的 ML 模型：

```
"CREATE MODEL customer_churn_auto_model
FROM (SELECT state,
             account_length,
             area_code,
             total_charge/account_length AS average_daily_spend, 
             cust_serv_calls/account_length AS average_daily_cases,
             churn 
      FROM customer_activity
      WHERE  record_date < '2020-01-01' 
     )
TARGET churn
FUNCTION ml_fn_customer_churn_auto
IAM_ROLE 'arn:aws:iam::XXXXXXXXXXXX:role/Redshift-ML'
SETTINGS (
  S3_BUCKET 'your-bucket'
);")
```

**注意**  
`SELECT` 狀態可以參考 Amazon Redshift 一般資料表、Amazon Redshift Spectrum 外部資料表或兩者。

## 史詩
<a name="perform-advanced-analytics-using-amazon-redshift-ml-epics"></a>

### 準備訓練和測試資料集
<a name="prepare-a-training-and-test-dataset"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 準備訓練和測試資料集。 | 登入 AWS 管理主控台並開啟 Amazon SageMaker 主控台。遵循[建置、訓練和部署機器學習模型](https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/)教學中的指示，建立具有標籤欄 (*監督式訓練*) 且無標頭的 .csv 或 Apache Parquet 檔案。 我們建議您隨機播放並將原始資料集分割為模型訓練的訓練集 (70%)，以及模型效能評估的測試集 (30%)。 | 資料科學家 | 

### 準備和設定技術堆疊
<a name="prepare-and-configure-the-technology-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立和設定 Amazon Redshift 叢集。 | 在 Amazon Redshift 主控台上，根據您的需求建立叢集。如需詳細資訊，請參閱 Amazon Redshift 文件中的[建立叢集](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-data-launch-cluster.html)。 Amazon Redshift 叢集必須使用`SQL_PREVIEW`維護軌道建立。如需預覽追蹤的詳細資訊，請參閱 Amazon Redshift 文件中的[選擇叢集維護追蹤](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-mgmt-maintenance-tracks)。 | DBA，雲端架構師 | 
| 建立 S3 儲存貯體以存放訓練資料和模型成品。 | 在 Amazon S3 主控台上，為訓練和測試資料建立 S3 儲存貯體。如需建立 S3 儲存貯體的詳細資訊，請參閱從 AWS Quick Starts [建立 S3 儲存貯](https://docs.aws.amazon.com/quickstarts/latest/s3backup/step-1-create-bucket.html)體。 請確定您的 Amazon Redshift 叢集和 S3 儲存貯體位於相同的區域。  | DBA，雲端架構師 | 
| 建立 IAM 政策並將其連接至 Amazon Redshift 叢集。 | 建立 IAM 政策，以允許 Amazon Redshift 叢集存取 SageMaker 和 Amazon S3。如需指示和步驟，請參閱 [Amazon Redshift 文件中的使用 Amazon Redshift ML 的叢集設定](https://docs.aws.amazon.com/redshift/latest/dg/cluster-setup.html)。 | DBA，雲端架構師 | 
| 允許 Amazon Redshift 使用者和群組存取結構描述和資料表。 | 授予許可，以允許 Amazon Redshift 中的使用者和群組存取內部和外部結構描述和資料表。如需步驟和說明，請參閱《Amazon Redshift 文件》中的[管理許可和擁有權](https://docs.aws.amazon.com/redshift/latest/dg/permissions-ownership.html)。 | DBA | 

### 在 Amazon Redshift 中建立和訓練 ML 模型
<a name="create-and-train-the-ml-model-in-amazon-redshift"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 Amazon Redshift 中建立和訓練 ML 模型。 | 在 Amazon Redshift ML 中建立和訓練您的 ML 模型。如需詳細資訊，請參閱 Amazon Redshift 文件中的 `CREATE MODEL`陳述式。 | 開發人員、資料科學家 | 

### 在 Amazon Redshift 中執行批次推論和預測
<a name="perform-batch-inference-and-prediction-in-amazon-redshift"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用產生的 ML 模型函數執行推論。 | 如需使用產生的 ML 模型函數執行推論的詳細資訊，請參閱 Amazon Redshift 文件中的[預測](https://docs.aws.amazon.com/redshift/latest/dg/prediction.html)。 | 資料科學家、商業智慧使用者 | 

## 相關資源
<a name="perform-advanced-analytics-using-amazon-redshift-ml-resources"></a>

**準備訓練和測試資料集**
+ [使用 Amazon SageMaker 建置、訓練和部署機器學習模型](https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/)

 

**準備和設定技術堆疊**
+ [建立 Amazon Redshift 叢集](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-data-launch-cluster.html)
+ [選擇 Amazon Redshift 叢集維護軌道](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-mgmt-maintenance-tracks)
+ [建立 S3 儲存貯體](https://docs.aws.amazon.com/quickstarts/latest/s3backup/step-1-create-bucket.html)
+ [設定 Amazon Redshift 叢集以使用 Amazon Redshift ML](https://docs.aws.amazon.com/redshift/latest/dg/cluster-setup.html)
+ [管理 Amazon Redshift 中的許可和擁有權](https://docs.aws.amazon.com/redshift/latest/dg/permissions-ownership.html)

 

**在 Amazon Redshift 中建立和訓練 ML 模型**
+ [Amazon Redshift 中的 CREATE MODEL 陳述式](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_MODEL.html#r_simple_create_model) 

 

**在 Amazon Redshift 中執行批次推論和預測**
+ [Amazon Redshift 中的預測](https://docs.aws.amazon.com/redshift/latest/dg/prediction.html) 

 

**其他資源**
+ [Amazon Redshift ML 入門](https://docs.aws.amazon.com/redshift/latest/dg/geting-started-machine-learning.html)
+ [使用 SQL 搭配 Amazon Redshift ML 在 Amazon Redshift 中建立、訓練和部署 ML 模型](https://aws.amazon.com/blogs/big-data/create-train-and-deploy-machine-learning-models-in-amazon-redshift-using-sql-with-amazon-redshift-ml/)
+ [Amazon Redshift 合作夥伴](https://aws.amazon.com/redshift/partners/?partner-solutions-cards.sort-by=item.additionalFields.partnerNameLower&partner-solutions-cards.sort-order=aschttps://aws.amazon.com/redshift/partners/?partner-solutions-cards.sort-by=item.additionalFields.partnerNameLower&partner-solutions-cards.sort-order=asc)
+ [AWS 機器學習能力合作夥伴](https://aws.amazon.com/machine-learning/partner-solutions/?partner-solutions-cards.sort-by=item.additionalFields.partnerNameLower&partner-solutions-cards.sort-order=asc)

# 使用 Amazon Athena 查詢具有 SQL 的 Amazon DynamoDB 資料表
<a name="query-amazon-dynamodb-tables-sql-amazon-athena"></a>

*Gavin Perrie、Ajit Ambike 和 Brad Yates，Amazon Web Services*

## 總結
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-summary"></a>

如果您的資料包含 Amazon Simple Storage Service (Amazon S3) 以外的來源，您可以使用聯合查詢來存取這些關聯式、非關聯式、物件或自訂資料來源。此模式說明如何使用 SQL 資料來源連接器，透過 Amazon Athena 設定對 Amazon DynamoDB 的聯合查詢存取。

使用此模式，您可以執行下列動作：
+ 使用 SQL 查詢 DynamoDB 資料表。
+ 在 Athena 中執行聯合 SQL 查詢，並將 DynamoDB 資料表與其他支援的資料來源聯結。

## 先決條件和限制
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-prereqs"></a>

**先決條件**
+ DynamoDB 資料表。
+ Athena 工作群組設定為使用 Athena 引擎版本 2。如需說明，請參閱 [Athena 文件](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-changing.html)。
+ `AthenaDynamoDBConnector` AWS Lambda 函數可以溢出資料的 S3 儲存貯體。S3 儲存貯體和 Lambda 函數必須位於相同的 AWS 區域。

如果這是您第一次存取 Athena，您將需要額外的 S3 儲存貯體來做為查詢結果位置。如需說明，請參閱 [Athena 文件](https://docs.aws.amazon.com/athena/latest/ug/querying.html#query-results-specify-location-console)。

**限制**
+ 不支援 [INSERT INTO](https://docs.aws.amazon.com/athena/latest/ug/insert-into.html) 等寫入操作。****

**產品版本**
+ [GitHub 上的 Athena 查詢聯合版本](https://github.com/awslabs/aws-athena-query-federation/releases)

## Architecture
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-architecture"></a>

**目標架構**

下圖顯示建立模式後的連線流程。使用者連線到 Amazon Athena 以提供查詢。Athena 會將查詢和目標傳遞至 DynamoDB 資料來源連接器 Lambda 函數，該函數會擷取資料並將其傳回給 Athena。如果傳回大量資料，Athena 會在封裝和傳回完整資料集之前，將暫時結果存放在溢出儲存貯體中。

![\[從使用者到 Athena 到 Lambda 的工作流程，這會連線至 S3 儲存貯體和 DynamoDB 資料表。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/9d1ee529-36f3-4c7e-a2e7-05b76e09a3d8/images/e50a00cf-a55a-4def-81d5-4d2755dc9a97.png)


## 工具
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-tools"></a>

**AWS 服務**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon Simple Storage Service (Amazon S3) 中分析資料。此模式使用 [Amazon Athena DynamoDB Connector](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb)，這是一種使用 Amazon Athena Query Federation SDK 建置並透過 安裝為 AWS Lambda 應用程式的工具 AWS Serverless Application Repository。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一項全受管 NoSQL 資料庫服務，可提供快速、可預期且可擴展的效能。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [Athena 查詢聯合](https://github.com/awslabs/aws-athena-query-federation/releases)儲存庫中使用。

## 史詩
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-epics"></a>

### 設定和測試 DynamoDB 資料來源連接器
<a name="set-up-and-test-the-ddb-data-source-connector"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 AthenaDynamoDBConnector 應用程式。 | 若要部署 AthenaDynamoDBConnecter，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/query-amazon-dynamodb-tables-sql-amazon-athena.html) | AWS DevOps | 
| 建立 Athena 的資料來源。 | 若要建立資料來源，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/query-amazon-dynamodb-tables-sql-amazon-athena.html) | AWS DevOps | 
| 使用 Athena 查詢 DynamoDB 資料表。 | 若要查詢 DynamoDB 資料表，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/query-amazon-dynamodb-tables-sql-amazon-athena.html) | 應用程式開發人員 | 

## 疑難排解
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 使用 查詢失敗`GENERIC_INTERNAL_ERROR: The bucket is in this region: <region>`*。* | 請確定在相同的 中建立 Athena 溢出儲存貯體和 Lambda 函數 AWS 區域。 | 
| Athena 主控台上看不到新建立的資料來源。 | Athena 資料目錄是區域性的。確定 `AthenaDynamoDBConnector` 已部署在您嘗試使用 Athena 的區域中。 | 
| 您無法針對新建立的資料來源執行查詢。 | 檢查**查詢結果位置**是否已設定。 | 

## 相關資源
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-resources"></a>
+ [Amazon Athena DynamoDB 連接器](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb)
+ [Amazon Athena 聯合查詢](https://docs.aws.amazon.com/athena/latest/ug/connect-to-a-data-source.html)

# 使用 Athena 存取、查詢和聯結 Amazon DynamoDB 資料表
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena"></a>

*Moinul Al-Mamun，Amazon Web Services*

## 總結
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-summary"></a>

此模式說明如何使用 Amazon Athena DynamoDB 連接器設定 Amazon Athena 和 Amazon DynamoDB 之間的連線。連接器使用 AWS Lambda 函數來查詢 DynamoDB 中的資料。您不需要撰寫任何程式碼來設定連線。建立連線後，您可以使用 [Athena 聯合查詢](https://docs.aws.amazon.com/athena/latest/ug/connect-to-a-data-source.html)從 Athena 執行 SQL 命令，快速存取和分析 DynamoDB 資料表。您也可以將一或多個 DynamoDB 資料表加入彼此或其他資料來源，例如 Amazon Redshift 或 Amazon Aurora。

## 先決條件和限制
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶，具有管理 DynamoDB 資料表、Athena 資料來源、Lambda 和 AWS Identity and Access Management (IAM) 角色的許可
+ Athena 可儲存查詢結果的 Amazon Simple Storage Service (Amazon S3) 儲存貯體
+ Athena DynamoDB 連接器可以短期儲存資料的 S3 儲存貯體
+ 支援 [Athena 引擎第 2 版的 AWS](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference-0002.html) 區域
+ 存取 Athena 和所需 S3 儲存貯體的 IAM 許可
+ [Amazon Athena DynamoDB 連接器](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb)，已安裝

**限制**

查詢 DynamoDB 資料表需要付費。超過幾 GB (GBs資料表大小可能會產生高成本。建議您在執行任何完整資料表 SCAN 操作之前考慮成本。如需詳細資訊，請參閱 [Amazon DynamoDB](https://aws.amazon.com/dynamodb/pricing/) 定價。為了降低成本並實現高效能，我們建議您在查詢中一律使用 LIMIT （例如 `SELECT * FROM table1 LIMIT 10`)。此外，在生產環境中執行 JOIN 或 GROUP BY 查詢之前，請考慮資料表的大小。如果您的資料表太大，請考慮其他選項，例如[將資料表遷移至 Amazon S3](https://aws.amazon.com/blogs/database/simplify-amazon-dynamodb-data-extraction-and-analysis-by-using-aws-glue-and-amazon-athena/)。

## Architecture
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-architecture"></a>

下圖顯示使用者如何從 Athena 在 DynamoDB 資料表上執行 SQL 查詢。

![\[用於連接 Athena 和 DynamoDB 以執行 SQL 查詢的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e6ff94af-d208-40c7-94e4-af257755a603/images/bc8e0132-b578-463b-bf55-3c39ce359c17.png)


該圖顯示以下工作流程：

1. 若要查詢 DynamoDB 資料表，使用者會從 Athena 執行 SQL 查詢。

1. Athena 啟動 Lambda 函數。

1. Lambda 函數會查詢 DynamoDB 資料表中請求的資料。

1. DynamoDB 會將請求的資料傳回至 Lambda 函數。然後，函數會透過 Athena 將查詢結果傳輸給使用者。

1. Lambda 函數會將資料存放在 S3 儲存貯體中。

**技術堆疊**
+ Amazon Athena
+ Amazon DynamoDB
+ Amazon S3
+ AWS Lambda

## 工具
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-tools"></a>
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon S3 中分析資料。
+ [Amazon Athena DynamoDB Connector](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb) 是一種 AWS 工具，可讓 Athena 與 DynamoDB 連線，並使用 SQL 查詢存取您的資料表。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一項全受管 NoSQL 資料庫服務，可提供快速、可預期且可擴展的效能。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而不需要佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。

## 史詩
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-epics"></a>

### 建立範例 DynamoDB 資料表
<a name="create-sample-dynamodb-tables"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立第一個範例資料表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html) | 開發人員 | 
| 將範例資料插入第一個資料表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html)<pre>{<br />  "PK1": "1234",<br />  "SK1": "info",<br />  "Salary": "5000"<br /> }</pre><pre>{<br />  "PK1": "1235",<br />  "SK1": "info",<br />  "Salary": "5200"<br /> }</pre> | 開發人員 | 
| 建立第二個範例資料表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html) | 開發人員 | 
| 將範例資料插入第二個資料表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html)<pre>{<br />  "PK2": "1234",<br /> "SK2": "bonus",<br /> "Bonus": "500"<br />}</pre><pre>{<br />  "PK2": "1235",<br /> "SK2": "bonus",<br /> "Bonus": "1000"<br />}</pre> | 開發人員 | 

### 在 Athena for DynamoDB 中建立資料來源
<a name="create-a-data-source-in-athena-for-dynamodb"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定資料來源連接器。 | 建立 DynamoDB 的資料來源，然後建立 Lambda 函數以連線至該資料來源。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html) | 開發人員 | 
| 確認 Lambda 函數可以存取 S3 溢出儲存貯體。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html)如果您遇到錯誤，請參閱此模式中*的其他資訊*一節以取得指引。 | 開發人員 | 

### 從 Athena 存取 DynamoDB 資料表
<a name="access-dynamodb-tables-from-athena"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 查詢 DynamoDB 資料表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html) | 開發人員 | 
| 聯結兩個 DynamoDB 資料表。 | DynamoDB 是 NoSQL 資料存放區，不支援 SQL 聯結操作。因此，您必須在兩個 DynamoDB 資料表上執行聯結操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html)<pre>SELECT pk1, salary, bonus FROM dydbtable1 t1<br /> JOIN dydbtable2 t2 ON t1.pk1 = t2.pk2;</pre> | 開發人員 | 

## 相關資源
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-resources"></a>
+ [Amazon Athena DynamoDB 連接器](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb) (AWS 實驗室）
+ [使用 Amazon Athena 的新聯合查詢查詢任何資料來源 ](https://aws.amazon.com/blogs/big-data/query-any-data-source-with-amazon-athenas-new-federated-query/)(AWS 大數據部落格）
+ [Athena 引擎版本參考](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference.html) (Athena 使用者指南）
+ [使用 AWS Glue 和 Amazon Athena 簡化 Amazon DynamoDB 資料擷取和分析](https://aws.amazon.com/blogs/database/simplify-amazon-dynamodb-data-extraction-and-analysis-by-using-aws-glue-and-amazon-athena/) (AWS 資料庫部落格）

## 其他資訊
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-additional"></a>

如果您在 Athena 中使用 `{bucket_name}/folder_name/` 格式`spill_bucket`的 執行查詢，則您可能會收到下列錯誤訊息：

```
"GENERIC_USER_ERROR: Encountered an exception[java.lang.RuntimeException] from your LambdaFunction[arn:aws:lambda:us-east-1:xxxxxx:function:testdynamodb] executed in context[retrieving meta-data] with message[You do NOT own the spill bucket with the name: s3://amzn-s3-demo-bucket/athena_dynamodb_spill_data/]
This query ran against the "default" database, unless qualified by the query. Please post the error message on our forum  or contact customer support with Query Id: [query-id]"
```

若要解決此錯誤，請將 Lambda 函數的環境變數更新`spill_bucket`為 `{bucket_name_only}`，然後針對儲存貯體寫入存取更新下列 Lambda IAM 政策：

```
{
             "Action": [
                 "s3:GetObject",
                 "s3:ListBucket",
                 "s3:GetBucketLocation",
                 "s3:GetObjectVersion",
                 "s3:PutObject",
                 "s3:PutObjectAcl",
                 "s3:GetLifecycleConfiguration",
                 "s3:PutLifecycleConfiguration",
                 "s3:DeleteObject"
            ],
             "Resource": [
                 "arn:aws:s3:::spill_bucket",
                 "arn:aws:s3:::spill_bucket/*"
            ],
             "Effect": "Allow"
        }
```

或者，您可以移除先前建立的 Athena 資料來源連接器，並僅使用 `{bucket_name}`重新建立`spill_bucket`。

# 使用純量 Python UDF 設定 Amazon Redshift 查詢結果的語言特定排序
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf"></a>

*Ethan Stark，Amazon Web Services*

## 總結
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-summary"></a>

此模式提供使用純量 Python UDF （使用者定義的函數） 設定 Amazon Redshift 查詢結果不區分大小寫語言排序的步驟和範例程式碼。必須使用純量 Python UDF，因為 Amazon Redshift 會根據二進位 UTF-8 排序傳回結果，且不支援語言特定的排序。Python UDF 是非 SQL 處理程式碼，以 Python 程式為基礎，並在資料倉儲中執行。您可以在單一查詢中使用 SQL 陳述式執行 Python UDF 程式碼。如需詳細資訊，請參閱 [Amazon Redshift 大數據部落格文章中的 Python UDFs 簡介](https://aws.amazon.com/blogs/big-data/introduction-to-python-udfs-in-amazon-redshift/) AWS 。

此模式中的範例資料是根據土耳其字母進行示範。此模式中的純量 Python UDF 旨在使 Amazon Redshift 的預設查詢結果符合土耳其文字元的語言順序。如需詳細資訊，請參閱此模式*額外資訊*區段中的*土耳其文語言範例*。您可以針對其他語言，以此模式修改純量 Python UDF。

## 先決條件和限制
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-prereqs"></a>

**先決條件**
+ 具有資料庫、結構描述和資料表的 [Amazon Redshift 叢集](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html) 
+ 具有 `CREATE TABLE`和 `CREATE FUNCTION`許可的 [Amazon Redshift 使用者](https://docs.aws.amazon.com/redshift/latest/dg/r_Users.html) 
+ [Python 2.7](https://www.python.org/download/releases/2.7/) 或更新版本

**限制**

此模式中查詢所使用的語言排序不區分大小寫。

## 工具
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-tools"></a>

**AWS 服務**
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html) 是 中的受管 PB 級資料倉儲服務 AWS 雲端。Amazon Redshift 已與您的資料湖整合，可讓您使用資料為您的企業和客戶取得新的洞見。

**其他工具**
+ [Python (UDFs) 使用者定義的函數](https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-introduction.html)是您可以在 Python 中撰寫，然後在 SQL 陳述式中呼叫 的函數。

## 史詩
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-epics"></a>

### 開發程式碼以語言順序排序查詢結果
<a name="develop-code-to-sort-query-results-in-linguistic-order"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 為您的範例資料建立資料表。 | 若要在 Amazon Redshift 中建立資料表並將範例資料插入資料表，請使用下列 SQL 陳述式：<pre>CREATE TABLE my_table (first_name varchar(30));<br /><br />INSERT INTO my_table (first_name)<br />VALUES<br />    ('ali'),<br />    ('Ali'),<br />    ('ırmak'),<br />    ('IRMAK'),<br />    ('irem'),<br />    ('İREM'),<br />    ('oğuz'),<br />    ('OĞUZ'),<br />    ('ömer'),<br />    ('ÖMER'),<br />    ('sedat'),<br />    ('SEDAT'),<br />    ('şule'),</pre>範例資料中的名字包含土耳其字母的特殊字元。如需此範例土耳其文考量事項的詳細資訊，請參閱此模式*額外資訊*區段中的*土耳其文語言範例*。 | 資料工程師 | 
| 檢查範例資料的預設排序。 | 若要在 Amazon Redshift 中查看範例資料的預設排序，請執行下列查詢：<pre>SELECT first_name FROM my_table ORDER BY first_name;</pre>查詢會從您先前建立的資料表傳回名字清單：<pre>first_name<br />---------------<br />Ali<br />IRMAK<br />OĞUZ<br />SEDAT<br />ali<br />irem<br />oğuz<br />sedat<br />ÖMER<br />ömer<br />İREM<br />ırmak<br />ŞULE<br />şule</pre>查詢結果的順序不正確，因為預設的二進位 UTF-8 排序並不符合土耳其文特殊字元的語言順序。 | 資料工程師 | 
| 建立純量 Python UDF。 | 若要建立純量 Python UDF，請使用下列 SQL 程式碼： <pre>CREATE OR REPLACE FUNCTION collate_sort (value varchar) <br />RETURNS varchar <br />IMMUTABLE <br />AS <br />$$    <br />    def sort_str(val):<br />        import string<br />        <br />        dictionary = {<br />            'I': 'ı', <br />            'ı': 'h~', <br />            'İ': 'i', <br />            'Ş': 's~', <br />            'ş': 's~', <br />            'Ğ': 'g~', <br />            'ğ': 'g~', <br />            'Ü': 'u~', <br />            'ü': 'u~', <br />            'Ö': 'o~', <br />            'ö': 'o~', <br />            'Ç': 'c~', <br />            'ç': 'c~'<br />        }<br />        <br />        for key, value in dictionary.items():<br />            val = val.replace(key, value)<br />        <br />        return val.lower()<br /> <br />    return sort_str(value)<br />    <br />$$ LANGUAGE plpythonu;</pre> | 資料工程師 | 
| 查詢範例資料。 | 若要使用 Python UDF 查詢範例資料，請執行下列 SQL 查詢：<pre>SELECT first_name FROM my_table ORDER BY collate_sort(first_name);</pre>查詢現在會以土耳其文語言順序傳回範例資料：<pre>first_name<br />---------------<br />ali<br />Ali<br />ırmak<br />IRMAK<br />irem<br />İREM<br />oğuz<br />OĞUZ<br />ömer<br />Ömer<br />sedat<br />SEDAT<br />şule<br />ŞULE</pre> | 資料工程師 | 

## 相關資源
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-resources"></a>
+ [ORDER BY 子句](https://docs.aws.amazon.com/redshift/latest/dg/r_ORDER_BY_clause.html) (Amazon Redshift 文件）
+ [建立純量 Python UDF ](https://docs.aws.amazon.com/redshift/latest/dg/udf-creating-a-scalar-udf.html)(Amazon Redshift 文件）

## 其他資訊
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-additional"></a>

**土耳其文語言範例**

Amazon Redshift 會根據二進位 UTF-8 排序順序傳回查詢結果，而非特定於語言的排序順序。這表示如果您查詢包含土耳其文字元的 Amazon Redshift 資料表，則查詢結果不會根據土耳其文語言的語言順序排序。土耳其文包含六個特殊字元 (ç、ı、ğ、ö、ş 和 ü)，不會顯示在拉丁字母中。這些特殊字元會根據二進位 UTF-8 順序放置在排序結果集的結尾，如下表所示。


| 
| 
| 二進位 UTF-8 排序 | 土耳其文語言排序 | 
| --- |--- |
| a | a | 
| b | b | 
| c | c | 
| d | **ç (\$1)** | 
| e | d | 
| f | e | 
| g | f | 
| h | g | 
| i | **ğ (\$1)** | 
| j | h | 
| k | **ı (\$1)** | 
| l | i | 
| m | j | 
| n | k | 
| o | l | 
| p | m | 
| r | n | 
| s | o | 
| t | **ö (\$1)** | 
| u | p | 
| v | r | 
| y | s | 
| z | **ş (\$1)** | 
| **ç (\$1)** | t | 
| **ğ (\$1)** | u | 
| **ı (\$1)** | **ü (\$1)** | 
| **ö (\$1)** | v | 
| **ş (\$1)** | y | 
| **ü (\$1)** | z | 

**注意**  
星號 (\$1) 表示土耳其文的特殊字元。

如上表所示，特殊字元 ****ç 在土耳其文語言排序中介於 **c** 和 **d** 之間，但在 **z** 之後以二進位 UTF-8 排序顯示。此模式中的純量 Python UDF 使用下列字元取代字典，以對應的拉丁同等字元取代土耳其文特殊字元。


| 
| 
| 土耳其文特殊字元 | 拉丁文同等角色 | 
| --- |--- |
| ç | c\$1 | 
| ı | h\$1 | 
| ğ | g\$1 | 
| ö | o\$1 | 
| ş | s\$1 | 
| ü | u\$1 | 

**注意**  
波狀符號 (\$1) 字元會附加到取代其對應土耳其文特殊字元的拉丁文字元結尾。

**修改純量 Python UDF 函數**

若要從此模式修改純量 Python UDF 函數，讓函數接受定位參數並支援多個交易字典，請使用下列 SQL 程式碼：

```
CREATE OR REPLACE FUNCTION collate_sort (value varchar, locale varchar) 
RETURNS varchar 
IMMUTABLE 
AS 
$$    
    def sort_str(val):
       import string
       # Turkish Dictionary
       if locale == 'tr-TR':
            dictionary = {
               'I': 'ı', 
               'ı': 'h~', 
               'İ': 'i', 
               'Ş': 's~', 
               'ş': 's~', 
               'Ğ': 'g~', 
               'ğ': 'g~', 
               'Ü': 'u~', 
               'ü': 'u~', 
               'Ö': 'o~', 
               'ö': 'o~', 
               'Ç': 'c~', 
               'ç': 'c~'
        }
        # German Dictionary
        if locale == 'de-DE':
            dictionary = {
               ....
               ....
        }
        
        for key, value in dictionary.items():
            val = val.replace(key, value)
        
        return val.lower()
 
    return sort_str(value)
    
$$ LANGUAGE plpythonu;
```

下列範例程式碼示範如何查詢修改後的 Python UDF：

```
SELECT first_name FROM my_table ORDER BY collate_order(first_name, 'tr-TR');
```

# 訂閱來自不同 AWS 區域中 S3 儲存貯體的事件通知的 Lambda 函數
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions"></a>

*Sureshonathala，Amazon Web Services*

*Andrew Preston 和 Arindom Sarkar，無*

## 總結
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-summary"></a>

[Amazon Simple Storage Service (Amazon S3) Event Notifications](https://docs.aws.amazon.com/AmazonS3/latest/userguide/NotificationHowTo.html) 會發佈 S3 儲存貯體中特定事件的通知 （例如，物件建立的事件、物件移除事件或還原物件事件）。您可以使用 AWS Lambda 函數，根據您的應用程式需求處理這些通知。不過，Lambda 函數無法直接從在不同 AWS 區域中託管的 S3 儲存貯體訂閱通知。

此模式的方法會部署[廣發性案例](https://docs.aws.amazon.com/sns/latest/dg/sns-common-scenarios.html)，透過為每個區域使用 Amazon S3 Simple Notification Service (Amazon SNS) 主題來處理來自跨區域 S3 儲存貯體的 Amazon S3 通知。這些區域 SNS 主題會將 Amazon S3 事件通知傳送至包含 Lambda 函數的中央區域中的 Amazon Simple Queue Service (Amazon SQS) 佇列。Lambda 函數會訂閱此 SQS 佇列，並根據組織的需求處理事件通知。

## 先決條件和限制
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 在多個區域中現有的 S3 儲存貯體，包括託管 Amazon SQS 佇列和 Lambda 函數的中央區域。
+ AWS Command Line Interface (AWS CLI)，已安裝並設定。如需詳細資訊，請參閱 [AWS CLI 文件中的安裝、更新和解除安裝](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) AWS CLI。 
+ 熟悉 Amazon SNS 中的廣發案例。如需詳細資訊，請參閱 [Amazon SNS 文件中的常見 Amazon SNS 案例](https://docs.aws.amazon.com/sns/latest/dg/sns-common-scenarios.html)。 Amazon SNS 

## Architecture
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-architecture"></a>

下圖顯示此模式方法的架構。 

![\[工作流程使用 Amazon SNS、S3 和 SQS 來處理來自跨區域 S3 儲存貯體的事件通知。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/cf6c1804-8c41-46f1-9f17-ff361708c595/images/760cf4c0-0cb3-48d1-92ae-1cf0fa8ae076.png)


該圖顯示以下工作流程：

1. Amazon S3 會將有關 S3 儲存貯體的事件通知 （例如，建立的物件、移除的物件或還原的物件） 傳送至相同區域中的 SNS 主題。

1. SNS 主題會將事件發佈至中央區域中的 SQS 佇列。

1. SQS 佇列設定為 Lambda 函數的事件來源，並緩衝 Lambda 函數的事件訊息。 

1. Lambda 函數會輪詢訊息的 SQS 佇列，並根據您的應用程式需求處理 Amazon S3 事件通知。

 

**技術堆疊**
+ Lambda
+ Amazon SNS
+ Amazon SQS
+ Amazon S3

## 工具
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-tools"></a>
+ [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) – AWS 命令列界面 (AWS CLI) 是一種開放原始碼工具，可透過命令列 shell 中的命令與 AWS 服務互動。透過最少的組態，您可以從命令提示中執行 AWS CLI 命令，該命令會實作相當於瀏覽器型 AWS 管理主控台所提供功能的功能。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) – AWS CloudFormation 可協助您建立模型並設定 AWS 資源、快速一致地佈建資源，以及在整個生命週期中管理資源。您可以使用範本來描述您的資源及其相依性，並將它們一起啟動和設定為堆疊，而不是個別管理資源。您可以管理和佈建跨多個 AWS 帳戶和 AWS 區域的堆疊。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – AWS Lambda 是一種運算服務，支援執行程式碼，無需佈建或管理伺服器。Lambda 只有在需要時才會執行程式碼，可自動從每天數項請求擴展成每秒數千項請求。只需為使用的運算時間支付費用，一旦未執行程式碼，就會停止計費。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) – Amazon Simple Notification Service (Amazon SNS) 會協調和管理發佈者和用戶端之間的訊息傳遞或傳送，包括 Web 伺服器和電子郵件地址。訂閱者會收到發佈到所訂閱主題的所有訊息，且某一主題的所有訂閱者均會收到相同訊息。
+ [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) – Amazon Simple Queue Service (Amazon SQS) 提供安全、耐用且可用的託管佇列，可讓您整合和解耦分散式軟體系統和元件。Amazon SQS 同時支援標準佇列和 FIFO 佇列。

## 史詩
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-epics"></a>

### 在中央區域中建立 SQS 佇列和 Lambda 函數
<a name="create-the-sqs-queue-and-lambda-function-in-your-central-region"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 Lambda 觸發條件建立 SQS 佇列。 | 登入 AWS 管理主控台，並使用 AWS [Lambda 文件中的教學課程使用 Lambda 搭配 Amazon SQS](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-example.html) 的指示，在您的中央區域中建立下列資源： AWS Lambda [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions.html)請務必將 SQS 佇列設定為 Lambda 函數的事件來源。 | AWS DevOps，雲端架構師 | 

### 為每個必要區域中的 S3 儲存貯體建立 SNS 主題並設定事件通知
<a name="create-an-sns-topic-and-set-up-event-notifications-for-the-s3-buckets-in-each-required-region"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
|  建立 SNS 主題以接收 Amazon S3 事件通知。 | 在您要接收 Amazon S3 事件通知的區域中建立 SNS 主題。如需詳細資訊，請參閱 [Amazon SNS 文件中的建立 SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)。 Amazon SNS  請務必記錄 SNS 主題的 Amazon Resource Name (ARN)。  | AWS DevOps，雲端架構師 | 
| 訂閱 SNS 主題至中央 SQS 佇列。 | 將您的 SNS 主題訂閱您的中央區域託管的 SQS 佇列。如需詳細資訊，請參閱 Amazon SNS [SNS 文件中的訂閱 SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-create-subscribe-endpoint-to-topic.html)。 | AWS DevOps，雲端架構師 | 
| 更新 SNS 主題的存取政策。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions.html)<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Sid": "0",<br />      "Effect": "Allow",<br />      "Principal": {<br />        "Service": "s3.amazonaws.com"<br />      },<br />      "Action": "sns:Publish",<br />      "Resource": "arn:aws:sns:us-west-2::s3Events-SNSTopic-us-west-2"<br />    }<br />  ]<br />}</pre> | AWS DevOps，雲端架構師 | 
| 設定區域中每個 S3 儲存貯體的通知。 | 設定區域中每個 S3 儲存貯體的事件通知。如需詳細資訊，請參閱《[Amazon S3 文件》中的使用 Amazon S3 主控台啟用和設定事件通知](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-event-notifications.html)。 Amazon S3 在**目的地**區段中，選擇 **SNS 主題**，並指定您先前建立之 SNS 主題的 ARN。 | AWS DevOps，雲端架構師 | 
| 針對所有必要的區域重複此史詩。 | 針對您要接收 Amazon S3 事件通知的每個區域重複此史詩中的任務，包括您的中央區域。 | AWS DevOps，雲端架構師 | 

## 相關資源
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-resources"></a>
+ [設定存取政策 ](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-add-permissions.html)(Amazon SQS 文件）
+ [將 SQS 佇列設定為事件來源 ](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html#events-sqs-eventsource)(AWS Lambda 文件）
+ [設定 SQS 佇列以啟動 Lambda 函數](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-lambda-function-trigger.html) (Amazon SQS 文件）
+ [AWS::Lambda::Function 資源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html) (AWS CloudFormation 文件）

# 將資料轉換為 Apache Parquet 的三種 AWS Glue ETL 任務類型
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet"></a>

*Adnan Alvee、Nitth Govindasivan 和 Karthikeyan Ramachandran，Amazon Web Services*

## 總結
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-summary"></a>

在 Amazon Web Services (AWS) 雲端上，AWS Glue 是全受管擷取、轉換和載入 (ETL) 服務。AWS Glue 可讓您以符合成本效益的方式分類資料、清理資料、擴充資料，並在各種資料存放區和資料串流之間可靠地移動資料。

此模式在 AWS Glue 中提供不同的任務類型，並使用三種不同的指令碼來示範撰寫 ETL 任務。

您可以使用 AWS Glue 在 Python shell 環境中寫入 ETL 任務。您也可以在受管 Apache Spark 環境中使用 Python (PySpark) 或 Scala 建立批次和串流 ETL 任務。為了協助您開始撰寫 ETL 任務，此模式著重於使用 Python shell、PySpark 和 Scala 的批次 ETL 任務。Python shell 任務適用於需要較少運算能力的工作負載。受管 Apache Spark 環境適用於需要高運算能力的工作負載。

Apache Parquet 旨在支援高效的壓縮和編碼機制。它可以加速您的分析工作負載，因為它以單欄式方式存放資料。將資料轉換為 Parquet 可以節省長時間執行時的儲存空間、成本和時間。若要進一步了解 Parquet，請參閱部落格文章 [Apache Parquet：如何使用開放原始碼單欄式資料格式成為英雄](https://blog.openbridge.com/how-to-be-a-hero-with-powerful-parquet-google-and-amazon-f2ae0f35ee04)。

## 先決條件和限制
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-prereqs"></a>

**先決條件**
+ AWS Identity and Access Management (IAM) 角色 （如果您沒有角色，請參閱[其他資訊](#three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-additional)一節。)

## Architecture
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-architecture"></a>

**目標技術堆疊**
+ AWS Glue
+ Amazon Simple Storage Service (Amazon S3)
+ Apache Parquet

**自動化和擴展**
+ [AWS Glue 工作流程](https://docs.aws.amazon.com/glue/latest/dg/workflows_overview.html)支援 ETL 管道的完整自動化。
+ 您可以變更資料處理單位 (DPUs或工作者類型的數量，以水平和垂直擴展。

## 工具
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-tools"></a>

**AWS 服務**
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是全受管 ETL 服務，可在各種資料存放區和資料串流之間分類、清理、擴充和移動資料。

**其他工具**
+ [Apache Parquet](https://parquet.apache.org/) 是一種開放原始碼資料欄導向的資料檔案格式，專為儲存和擷取而設計。

**組態**

使用下列設定來設定 AWS Glue ETL 的運算能力。若要降低成本，請在執行此模式中提供的工作負載時使用最小設定。 
+ **Python shell** – 您可以使用 1 個 DPU 來利用 16 GB 的記憶體，或使用 0.0625 個 DPU 來利用 1 GB 的記憶體。此模式使用 0.0625 DPU，這是 AWS Glue 主控台中的預設值。
+ **Python 或 Scala for Spark** – 如果您在主控台中選擇 Spark 相關任務類型，AWS Glue 預設會使用 10 個工作者和 G.1X 工作者類型。此模式使用兩個工作者，這是允許的最小數量，具有標準工作者類型，足夠且經濟實惠。

下表顯示 Apache Spark 環境的不同 AWS Glue 工作者類型。由於 Python shell 任務不使用 Apache Spark 環境來執行 Python，因此不會包含在資料表中。


| 
| 
|  | 標準 | G.1X | G.2X | 
| --- |--- |--- |--- |
| vCPU | 4 | 4 | 8 | 
| 記憶體 | 16 GB | 16 GB | 32 GB | 
| 磁碟空間 | 50 GB | 64 GB | 128 GB | 
| 每個工作者的執行器 | 2 | 1  | 1 | 

**Code**

如需此模式中使用的程式碼，包括 IAM 角色和參數組態，請參閱[其他資訊](#three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-additional)一節。

## 史詩
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-epics"></a>

### 上傳資料
<a name="upload-the-data"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將資料上傳至新的或現有的 S3 儲存貯體。 | 在帳戶中建立或使用現有的 S3 儲存貯體。從[附件](#attachments-8c926709-8fa4-417f-9aaf-bcc8113d018f)區段上傳 sample\$1data.csv 檔案，並記下 S3 儲存貯體和字首位置。 | 一般 AWS | 

### 建立並執行 AWS Glue 任務
<a name="create-and-run-the-aws-glue-job"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 AWS Glue 任務。 | 在 AWS Glue 主控台的 ETL 區段下，新增 AWS Glue 任務。選取適當的任務類型、AWS Glue 版本，以及對應的 DPU/工作者類型和工作者數量。如需詳細資訊，請參閱*組態*一節。 | 開發人員、雲端或資料 | 
| 變更輸入和輸出位置。 | 複製對應至 AWS Glue 任務的程式碼，並變更您在**上傳資料**圖示中記下的輸入和輸出位置。 | 開發人員、雲端或資料 | 
| 設定參數。 | 您可以使用[其他資訊](#three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-additional)區段中提供的程式碼片段來設定 ETL 任務的參數。AWS Glue 在內部使用四個引數名稱：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet.html)`--JOB_NAME` 參數必須在 AWS Glue 主控台上明確輸入。選擇**任務**、**編輯任務**、**安全組態、指令碼程式庫和任務參數 （選用）**。輸入 `--JOB_NAME`做為索引鍵，並提供值。您也可以使用 AWS Command Line Interface (AWS CLI) 或 AWS Glue API 來設定此參數。此`--JOB_NAME`參數由 Spark 使用，在 Python shell 環境任務中不需要。您必須在每個參數名稱`--`之前新增 ；否則，程式碼將無法運作。例如，對於程式碼片段，位置參數必須由 `--input_loc`和 調用`--output_loc`。 | 開發人員、雲端或資料 | 
| 執行 ETL 任務。 | 執行您的任務並檢查輸出。請注意，從原始檔案減少了多少空間。 | 開發人員、雲端或資料 | 

## 相關資源
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-resources"></a>

**參考**
+ [Apache Spark](https://spark.apache.org/)
+ [AWS Glue：運作方式](https://docs.aws.amazon.com/glue/latest/dg/how-it-works.html)
+ [AWS Glue 定價](https://aws.amazon.com/glue/pricing/)

**教學課程和影片**
+ [什麼是 AWS Glue？](https://www.youtube.com/watch?v=qgWMfNSN9f4)

## 其他資訊
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-additional"></a>

**IAM 角色**

建立 AWS Glue 任務時，您可以使用具有下列程式碼片段中所示許可的現有 IAM 角色或新角色。

若要建立新的角色，請使用下列 YAML 程式碼。

```
# (c) 2022 Amazon Web Services, Inc. or its affiliates. All Rights Reserved. This AWS Content is provided subject to the terms of the AWS Customer
# Agreement available at https://aws.amazon.com/agreement/ or other written agreement between Customer and Amazon Web Services, Inc.

AWSTemplateFormatVersion: "2010-09-09"

Description: This template will setup IAM role for AWS Glue service.

Resources:
  rGlueRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Service:
                - "glue.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSGlueServiceRole
      Policies:
        - PolicyName: !Sub "${AWS::StackName}-s3-limited-read-write-inline-policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - "s3:PutObject"
                  - "s3:GetObject"
                Resource: "arn:aws:s3:::*/*"
      Tags:
        - Key  : "Name"
          Value : !Sub "${AWS::StackName}"

Outputs:
  oGlueRoleName:
    Description: AWS Glue IAM role
    Value:
      Ref: rGlueRole
    Export:
      Name: !Join [ ":", [ !Ref "AWS::StackName", rGlueRole ] ]
```

**AWS Glue Python Shell**

Python 程式碼使用 Pandas 和 PyArrow 程式庫將資料轉換為 Parquet。Pandas 程式庫已可供使用。執行模式時會下載 PyArrow 程式庫，因為它是一次性執行。您可以使用 wheel 檔案將 PyArrow 轉換為程式庫，並以程式庫套件的形式提供檔案。如需封裝 wheel 檔案的詳細資訊，請參閱[提供您自己的 Python 程式庫](https://docs.aws.amazon.com/glue/latest/dg/add-job-python.html)。

*AWS Glue Python shell 參數*

```
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv, ["input_loc", "output_loc"])
```

*AWS Glue Python shell 程式碼*

```
from io import BytesIO
import pandas as pd
import boto3
import os
import io
import site
from importlib import reload
from setuptools.command import easy_install
install_path = os.environ['GLUE_INSTALLATION']
easy_install.main( ["--install-dir", install_path, "pyarrow"] )
reload(site)
import pyarrow


input_loc = "s3://bucket-name/prefix/sample_data.csv"
output_loc = "s3://bucket-name/prefix/"


input_bucket = input_loc.split('/', 1)[0]
object_key = input_loc.split('/', 1)[1]


output_loc_bucket = output_loc.split('/', 1)[0]
output_loc_prefix = output_loc.split('/', 1)[1] 


s3 = boto3.client('s3')
obj = s3.get_object(Bucket=input_bucket, Key=object_key)
df = pd.read_csv(io.BytesIO(obj['Body'].read()))


parquet_buffer = BytesIO()
s3_resource = boto3.resource('s3')
df.to_parquet(parquet_buffer, index=False) 
s3_resource.Object(output_loc_bucket, output_loc_prefix +  'data' + '.parquet').put(Body=parquet_buffer.getvalue())
```

**使用 Python 的 AWS Glue Spark 任務**

若要搭配 Python 使用 AWS Glue Spark 任務類型，請選擇 **Spark** 做為任務類型。選擇 **Spark 3.1、Python 3 搭配改善的任務啟動時間 (Glue 3.0 版） **做為 AWS Glue 版本。

*AWS Glue Python 參數*

```
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv, ["JOB_NAME", "input_loc", "output_loc"])
```

*使用 Python 程式碼的 AWS Glue Spark 任務*

```
import sys
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.transforms import *
from awsglue.dynamicframe import DynamicFrame
from awsglue.utils import getResolvedOptions
from awsglue.job import Job


sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)

input_loc = "s3://bucket-name/prefix/sample_data.csv"
output_loc = "s3://bucket-name/prefix/"

inputDyf = glueContext.create_dynamic_frame_from_options(\
    connection_type = "s3", \
    connection_options = { 
        "paths": [input_loc]}, \
    format = "csv",
    format_options={
        "withHeader": True,
        "separator": ","
    })


outputDF = glueContext.write_dynamic_frame.from_options(\
    frame = inputDyf, \
    connection_type = "s3", \
    connection_options = {"path": output_loc \
        }, format = "parquet")
```

對於大量壓縮大型檔案 （例如 1，000 個檔案，每個檔案約為 3 MB)，請使用 `compressionType` 參數與 `recurse` 參數來讀取字首內可用的所有檔案，如下列程式碼所示。

```
input_loc = "bucket-name/prefix/"
output_loc = "bucket-name/prefix/"

inputDyf = glueContext.create_dynamic_frame_from_options(
                    connection_type = "s3", 
                    connection_options = {"paths": [input_loc], 
                                            "compressionType":"gzip","recurse" :"True",
                                            },
                    format = "csv",
                    format_options={"withHeader": True,"separator": ","}
                    )
```

對於大量壓縮的小型檔案 （例如，各約 133 KB 的 1，000 個檔案），請使用 `groupFiles` 參數，以及 `compressionType`和 `recurse` 參數。`groupFiles` 參數會將小型檔案分組為多個大型檔案，而 `groupSize` 參數會以位元組為單位 （例如 1 MB) 將分組控制為指定的大小。下列程式碼片段提供在程式碼中使用這些參數的範例。

```
input_loc = "bucket-name/prefix/"
output_loc = "bucket-name/prefix/"

inputDyf = glueContext.create_dynamic_frame_from_options(
                    connection_type = "s3", 
                    connection_options = {"paths": [input_loc], 
                                            "compressionType":"gzip","recurse" :"True",
                                             "groupFiles" :"inPartition",  "groupSize" :"1048576",
                                            },
                    format = "csv",
                    format_options={"withHeader": True,"separator": ","}
                    )
```

如果工作者節點沒有任何變更，這些設定可讓 AWS Glue 任務讀取多個檔案 （無論有無壓縮），並以 Parquet 格式寫入目標。

**使用 Scala 的 AWS Glue Spark 任務**

若要搭配 Scala 使用 AWS Glue Spark 任務類型，請選擇 **Spark** 做為任務類型，選擇**語言**做為 **Scala**。選擇 **Spark 3.1、Scala 2 搭配改善的任務啟動時間 (Glue 3.0 版） **做為 AWS Glue 版本。為了節省儲存空間，下列具有 Scala 範例的 AWS Glue 也會使用 `applyMapping`功能來轉換資料類型。

*AWS Glue Scala 參數*

```
import com.amazonaws.services.glue.util.GlueArgParser val args = GlueArgParser.getResolvedOptions(sysArgs, Seq("JOB_NAME", "inputLoc", "outputLoc").toArray)
```

*具有 Scala 程式碼的 AWS Glue Spark 任務*

```
import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.MappingSpec
import com.amazonaws.services.glue.DynamicFrame
import com.amazonaws.services.glue.errors.CallSite
import com.amazonaws.services.glue.util.GlueArgParser
import com.amazonaws.services.glue.util.Job
import com.amazonaws.services.glue.util.JsonOptions
import org.apache.spark.SparkContext
import scala.collection.JavaConverters._


object GlueScalaApp {
  def main(sysArgs: Array[String]) {
    
    @transient val spark: SparkContext = SparkContext.getOrCreate()
    val glueContext: GlueContext = new GlueContext(spark)

    val inputLoc = "s3://bucket-name/prefix/sample_data.csv"
    val outputLoc = "s3://bucket-name/prefix/"

    val readCSV = glueContext.getSource("csv", JsonOptions(Map("paths" -> Set(inputLoc)))).getDynamicFrame()

    val applyMapping = readCSV.applyMapping(mappings = Seq(("_c0", "string", "date", "string"), ("_c1", "string", "sales", "long"),
    ("_c2", "string", "profit", "double")), caseSensitive = false)

    val formatPartition = applyMapping.toDF().coalesce(1)

    val dynamicFrame = DynamicFrame(formatPartition, glueContext)

    val dataSink = glueContext.getSinkWithFormat(
        connectionType = "s3", 
        options = JsonOptions(Map("path" -> outputLoc )),
        transformationContext = "dataSink", format = "parquet").writeDynamicFrame(dynamicFrame)
  }
}
```

## 附件
<a name="attachments-8c926709-8fa4-417f-9aaf-bcc8113d018f"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/8c926709-8fa4-417f-9aaf-bcc8113d018f/attachments/attachment.zip)

# 使用 Amazon Athena 和 Amazon QuickSight 視覺化 Amazon Redshift 稽核日誌
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight"></a>

*Sanket Sirsikar 和 Gopal Krishna Bhatia，Amazon Web Services*

## 總結
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-summary"></a>

安全性是 Amazon Web Services (AWS) 雲端上資料庫操作不可或缺的一部分。您的組織應確保監控資料庫使用者活動和連線，以偵測潛在的安全事件和風險。此模式可協助您監控資料庫以進行安全性和疑難排解，也就是稱為資料庫稽核的程序。

 此模式提供 SQL 指令碼，可自動在 Amazon QuickSight 中建立報告儀表板的 Amazon Athena 資料表和檢視，協助您稽核 Amazon Redshift 日誌。 Amazon QuickSight 這可確保負責監控資料庫活動的使用者可以方便地存取資料安全功能。 

## 先決條件和限制
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 現有的 Amazon Redshift 叢集。如需詳細資訊，請參閱 [Amazon Redshift 文件中的建立 Amazon Redshift 叢集](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-data-launch-cluster.html)。
+ 存取現有的 Athena 工作群組。如需詳細資訊，請參閱 Amazon Athena 文件中的[工作群組運作方式](https://docs.aws.amazon.com/athena/latest/ug/user-created-workgroups.html)。 
+ 具有必要 AWS Identity and Access Management (IAM) 許可的現有 Amazon Simple Storage Service (Amazon S3) 來源儲存貯體。如需詳細資訊，請參閱 [Amazon Redshift 文件中的資料庫稽核記錄的 Amazon Redshift 稽核記錄儲存貯體許可](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-bucket-permissions)。 [https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html)

## Architecture
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-architecture"></a>

![\[Data flow diagram showing Amazon Redshift, logs, S3 bucket, Amazon Athena, and Amazon Quick.\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/90e69009-001e-4ced-bef0-3c361f93ae87/images/9fde7f01-17ab-4207-8a59-a12daf85a382.png)


 

**技術堆疊**
+ Athena
+ Amazon Redshift 
+ Amazon S3 
+ QuickSight

## 工具
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-tools"></a>
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) – Athena 是一種互動式查詢服務，可讓您使用標準 SQL 輕鬆分析 Amazon S3 中的資料。 
+ [Amazon QuickSight](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) – QuickSight 是可擴展、無伺服器、可內嵌、採用機器學習的商業智慧 (BI) 服務。 
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html) – Amazon Redshift 是一種企業級的 PB 級全受管資料倉儲服務。 
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是網際網路的儲存體。

## 史詩
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-epics"></a>

### 設定 Amazon Redshift 叢集
<a name="configure-the-amazon-redshift-cluster"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
|  啟用 Amazon Redshift 叢集的稽核記錄。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight.html) | DBA，資料工程師 | 
| 在 Amazon Redshift 叢集參數群組中啟用記錄。 | 您可以使用 AWS 管理主控台、Amazon Redshift API 參考或 AWS Command Line Interface (AWS CLI)，同時啟用連線日誌、使用者日誌和使用者活動日誌的稽核。 若要稽核使用者活動日誌，您必須啟用`enable_user_activity_logging`資料庫參數。如果您只啟用稽核記錄功能，但不啟用相關聯的參數，資料庫稽核會記錄連線和使用者日誌的記錄資訊，但不會記錄使用者活動日誌。`enable_user_activity_logging` 參數預設為未啟用，但您可以將其從 變更為 `false`來啟用它`true`。您需要在啟用 參數的情況下建立新的叢集`user_activity_logging`參數群組，並將其連接至您的 Amazon Redshift 叢集。如需詳細資訊，請參閱 Amazon Redshift 文件中的[修改叢集](https://docs.aws.amazon.com/redshift/latest/mgmt/managing-clusters-console.html#modify-cluster)。如需此任務的詳細資訊，請參閱 [Amazon Redshift 文件中的 Amazon Redshift 參數群組](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html)和[使用主控台設定稽核](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing-console.html)。 | DBA，資料工程師 | 
| 設定 Amazon Redshift 叢集記錄的 S3 儲存貯體許可。 | 當您啟用記錄時，Amazon Redshift 會收集記錄資訊，並將其上傳至存放在 S3 儲存貯體中的日誌檔案。您可以使用現有的 S3 儲存貯體或建立新的儲存貯體。確定 Amazon Redshift 具有存取 S3 儲存貯體所需的 IAM 許可。如需詳細資訊，請參閱 [Amazon Redshift 文件中的資料庫稽核記錄的 Amazon Redshift 稽核記錄儲存貯體許可](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-bucket-permissions)。 [https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html) | DBA，資料工程師 | 

### 建立 Athena 資料表和檢視
<a name="create-the-athena-table-and-views"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Athena 資料表和檢視，從 S3 儲存貯體查詢 Amazon Redshift 稽核日誌資料。 | 開啟 Amazon Athena 主控台，並使用 `AuditLogging.sql` SQL 指令碼 （已連接） 的資料定義語言 (DDL) 查詢來建立使用者活動日誌、使用者日誌和連線日誌的資料表和檢視。如需詳細資訊和說明，請參閱 Amazon Athena 研討會中的[建立資料表和執行查詢](https://athena-in-action.workshop.aws/30-basics/301-create-tables.html)教學課程。 | 資料工程師 | 

### 在 QuickSight 儀表板中設定日誌監控
<a name="set-up-log-monitoring-in-the-quicksight-dashboard"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 Athena 作為資料來源建立 QuickSight 儀表板。 | 開啟 Amazon QuickSight 主控台，並依照 Amazon Athena 研討會中的[使用 Athena 視覺化 QuickSight ](https://athena-in-action.workshop.aws/30-basics/307-quicksight.html)教學課程中的指示建立 QuickSight 儀表板。 | DBA，資料工程師 | 

## 相關資源
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-resources"></a>
+ [在 Athena 中建立資料表並執行查詢](https://athena-in-action.workshop.aws/30-basics/301-create-tables.html)
+ [使用 Athena 透過 QuickSight 視覺化](https://athena-in-action.workshop.aws/30-basics/307-quicksight.html)

## 附件
<a name="attachments-90e69009-001e-4ced-bef0-3c361f93ae87"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/90e69009-001e-4ced-bef0-3c361f93ae87/attachments/attachment.zip)

# 使用 Amazon Quick Sight 視覺化所有 AWS 帳戶的 IAM 登入資料報告
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight"></a>

*Parag Nagwekar 和 Arun Chandapillai，Amazon Web Services*

## 摘要
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-summary"></a>


| 
| 
| 警告：IAM 使用者具有長期登入資料，這會造成安全風險。為了協助降低此風險，建議您只為這些使用者提供執行任務所需的許可，並在不再需要這些使用者時將其移除。 | 
| --- |

您可以使用 AWS Identity and Access Management (IAM) 登入資料報告，協助您滿足組織的安全性、稽核和合規要求。[登入資料報告](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html)提供 AWS 帳戶中所有使用者的清單，並顯示其登入資料的狀態，例如密碼、存取金鑰和多重驗證 (MFA) 裝置。您可以針對 AWS [AWS Organizations](https://docs.aws.amazon.com/whitepapers/latest/organizing-your-aws-environment/core-concepts.html) 帳戶使用登入資料報告。

此模式包含步驟和程式碼，可協助您使用 Amazon Quick Sight 儀表板建立和共用組織中所有 AWS 帳戶的 IAM 登入資料報告。您可以與組織中的利益相關者共用儀表板。這些報告可協助您的組織實現以下目標業務成果：
+ 識別與 IAM 使用者相關的安全事件
+ 追蹤 IAM 使用者的即時遷移至單一登入 (SSO) 身分驗證
+ 追蹤 IAM 使用者存取的 AWS 區域
+ 保持合規
+ 與其他利益相關者共用資訊

## 先決條件和限制
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 具有成員帳戶[的組織](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_tutorials_basic.html) 
+ 具有存取 Organizations 中帳戶許可的 [IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) 
+ 安裝 [https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html#getting-started-install-instructions](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html#getting-started-install-instructions)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) AWS Command Line Interface (AWS CLI) 第 2 版
+ [Amazon Quick Enterprise Edition](https://docs.aws.amazon.com/quicksight/latest/user/editions.html) 的[訂閱](https://docs.aws.amazon.com/quicksight/latest/user/signing-up.html) 

## Architecture
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-architecture"></a>

**技術堆疊**
+ Amazon Athena
+ Amazon EventBridge
+ Amazon Quick Sight
+ Amazon Simple Storage Service (Amazon S3)
+ AWS Glue
+ AWS Identity and Access Management (IAM)
+ AWS Lambda
+ AWS Organizations

**目標架構**

下圖顯示用於設定從多個 AWS 帳戶擷取 IAM 憑證報告資料的工作流程的架構。

![\[下列螢幕擷取畫面說明架構圖表\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/8724ff28-40f6-4c43-9c65-fbd18bbbfd0f/images/e780916a-4ab7-4fdc-8ecc-c837c7d90d13.png)


1. EventBridge 每天叫用 Lambda 函數。

1. Lambda 函數會在組織的每個 AWS 帳戶中擔任 IAM 角色。然後，函數會建立 IAM 登入資料報告，並將報告資料存放在集中式 S3 儲存貯體中。您必須在 S3 儲存貯體上啟用加密和停用公有存取。

1. AWS Glue 爬蟲程式每天爬取 S3 儲存貯體，並相應地更新 Athena 資料表。

1. Quick Sight 會匯入和分析登入資料報告中的資料，並建置儀表板，供利益相關者視覺化和共用。

## 工具
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-tools"></a>

**AWS 服務**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可讓您使用標準 SQL 輕鬆分析 Amazon S3 中的資料。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一種無伺服器事件匯流排服務，可協助您將應用程式與來自各種來源的即時資料連線。例如，Lambda 函數、使用 API 目的地的 HTTP 調用端點，或其他 AWS 帳戶中的事件匯流排。
+ [Amazon Quick Sight](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) 是一種雲端規模的商業智慧 (BI) 服務，可協助您在單一儀表板中視覺化、分析和報告您的資料。Quick Sight 是 Amazon Quick 的核心元件，提供互動式資料視覺化、SPICE 記憶體內分析、內嵌分析和儀表板共用。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 可透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。

**Code**

此模式的程式碼可在 GitHub [getiamcredsreport-allaccounts-org](https://github.com/aws-samples/getiamcredsreport-allaccounts-org) 儲存庫中使用。您可以使用此儲存庫中的程式碼，跨 Organizations 中的 AWS 帳戶建立 IAM 登入資料報告，並將其存放在中央位置。

## 史詩
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-epics"></a>

### 設定基礎設施
<a name="set-up-the-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 Amazon Quick Enterprise 版本。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html) | AWS 管理員、AWS DevOps、雲端管理員、雲端架構師 | 
| 將 Amazon Quick Sight 與 Amazon S3 和 Athena 整合。 | 在部署 AWS CloudFormation 堆疊之前，您必須[授權](https://docs.aws.amazon.com/quicksight/latest/user/troubleshoot-connect-to-datasources.html) Quick Sight 使用 Amazon S3 和 Athena。 AWS CloudFormation  | AWS 管理員、AWS DevOps、雲端管理員、雲端架構師 | 

### 部署基礎設施
<a name="deploy-the-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製 GitHub 儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html) | AWS 管理員 | 
| 部署 基礎設施。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html) | AWS 管理員 | 
| 建立 IAM 許可政策。 | 使用下列許可，為組織中的每個 AWS [帳戶建立 IAM 政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html)：<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Effect": "Allow",<br />      "Action": [<br />        "iam:GenerateCredentialReport",<br />        "iam:GetCredentialReport"<br />        ],<br />      "Resource": "*"<br />    }<br />  ]<br />}</pre> | AWS DevOps、雲端管理員、雲端架構師、資料工程師 | 
| 使用信任政策建立 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html)<pre>{<br />   "Version": "2012-10-17",		 	 	 <br />   "Statement":[<br />      {<br />         "Effect":"Allow",<br />         "Principal":{<br />            "AWS":[<br />               "arn:aws:iam::<MasterAccountID>:role/<LambdaRole>"<br />            ]<br />         },<br />         "Action":"sts:AssumeRole"<br />      }<br />   ]<br />}</pre>`arn:aws:iam::<MasterAccountID>:role/<LambdaRole>` 將 取代為您先前記下的 Lambda 角色 ARN。組織通常會使用自動化為其 AWS 帳戶建立 IAM 角色。如果可用，我們建議您使用此自動化。或者，您可以從** **程式碼儲存庫使用`CreateRoleforOrg.py`指令碼。指令碼需要現有的管理角色或任何其他 IAM 角色，這些角色具有在每個 AWS 帳戶中建立 IAM 政策和角色的許可。 | 雲端管理員、雲端架構師、AWS 管理員 | 
| 設定 Amazon Quick Sight 以視覺化資料。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html) | AWS DevOps、雲端管理員、雲端架構師、資料工程師 | 

## 其他資訊
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-additional"></a>

**其他考量事項**

考慮下列各項：
+ 使用 CloudFormation 部署基礎設施後，您可以等待 Athena 在 Amazon S3 中建立並分析報告，直到 Lambda 和 AWS Glue 根據其排程執行。或者，您可以手動執行 Lambda 以取得 Amazon S3 中的報告，然後執行 AWS Glue 爬蟲程式以取得從資料建立的 Athena 資料表。
+ Quick 是一種功能強大的工具，可根據您的業務需求分析和視覺化資料。您可以使用 Quick 中的[參數](https://docs.aws.amazon.com/quicksight/latest/user/parameters-in-quicksight.html)，根據您選擇的資料欄位來控制小工具資料。此外，您可以使用快速分析從資料集建立參數 （例如，帳戶、日期和使用者欄位`partition_0`，例如 `partition_1`、 和 `user`)，以新增帳戶、日期和使用者的參數控制項。
+ 若要建置自己的 Quick Sight 儀表板，請參閱 AWS Workshop Studio 網站上的 [Quick Workshops](https://catalog.workshops.aws/quicksight/en-US)。
+ 若要查看 Quick Sight 儀表板範例，請參閱 GitHub [getiamcredsreport-allaccounts-org](https://github.com/aws-samples/getiamcredsreport-allaccounts-org) 程式碼儲存庫。

**目標業務成果**

您可以使用此模式來實現下列目標業務成果：
+ **識別與 IAM 使用者相關的安全事件 **– 使用單一窗格來調查組織中每個 AWS 帳戶的每個使用者。您可以追蹤 IAM 使用者最近存取的個別 AWS 區域及其使用之服務的趨勢。
+ **追蹤 IAM 使用者的即時遷移至 SSO 身分驗證 **– 透過使用 SSO，使用者可以使用單一登入資料登入一次，並存取多個 AWS 帳戶和應用程式。如果您打算將 IAM 使用者遷移至 SSO，此模式可協助您轉換至 SSO，並追蹤所有 AWS 帳戶的所有 IAM 使用者登入資料用量 （例如存取 AWS 管理主控台或存取金鑰的使用）。
+ **追蹤 IAM 使用者存取的 AWS 區域 **– 您可以基於各種目的控制 IAM 使用者對區域的存取，例如資料主權和成本控制。您也可以追蹤任何 IAM 使用者對 區域的使用。
+ **保持合規 **– 透過遵循最低權限原則，您只能授予執行特定任務所需的特定 IAM 許可。此外，您也可以追蹤對 AWS 服務、AWS 管理主控台和長期憑證用量的存取。
+ **與其他利益相關者共用資訊 **– 您可以與其他利益相關者共用精心策劃的儀表板，而無需授予他們存取 IAM 登入資料報告或 AWS 帳戶的權限。

# 更多模式
<a name="analytics-more-patterns-pattern-list"></a>

**Topics**
+ [使用 Amazon Cognito 和 AWS Amplify UI 驗證現有的 React 應用程式使用者](authenticate-react-app-users-cognito-amplify-ui.md)
+ [使用 Amazon Textract 從 PDF 檔案自動擷取內容](automatically-extract-content-from-pdf-files-using-amazon-textract.md)
+ [在 Amazon SageMaker AI Studio Lab 中將 DeepAR 用於時間序列，以建置冷啟動預測模型](build-a-cold-start-forecasting-model-by-using-deepar.md)
+ [使用 AWS Cost Explorer 建立 Amazon EMR 叢集的詳細成本和用量報告](create-detailed-cost-and-usage-reports-for-amazon-emr-clusters-by-using-aws-cost-explorer.md)
+ [建立 Amazon RDS 和 Amazon Aurora 的詳細成本和用量報告](create-detailed-cost-and-usage-reports-for-amazon-rds-and-amazon-aurora.md)
+ [使用 AWS Cost Explorer 建立 AWS Glue 任務的詳細成本和用量報告 Cost Explorer](create-detailed-cost-and-usage-reports-for-aws-glue-jobs-by-using-aws-cost-explorer.md)
+ [使用 Kinesis Data Streams 和 Firehose 搭配 將 DynamoDB 記錄交付至 Amazon S3 AWS CDK](deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk.md)
+ [使用 AWS CodePipeline CI/CD 管道部署 AWS Glue 任務 AWS CodePipeline](deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline.md)
+ [使用 Amazon Cognito 和 IaC 自動化將 Amazon Quick Sight 視覺化元件內嵌至 Web 應用程式 IaC](embed-quick-sight-visual-components-into-web-apps-cognito-iac.md)
+ [Amazon DynamoDB 資料表的預估儲存成本](estimate-storage-costs-for-an-amazon-dynamodb-table.md)
+ [使用 Terraform 執行 Amazon Redshift SQL 查詢](execute-redshift-sql-queries-using-terraform.md)
+ [在資料湖中擷取和查詢 AWS IoT SiteWise 中繼資料屬性](extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake.md)
+ [在 Quick Sight 中使用 AWS Mainframe Modernization 和 Amazon Q 產生資料洞見](generate-data-insights-by-using-aws-mainframe-modernization-and-amazon-q-in-quicksight.md)
+ [使用 Quick Sight 中的 AWS Mainframe Modernization 和 Amazon Q 產生 Db2 z/OS 資料洞見](generate-db2-zos-data-insights-aws-mainframe-modernization-amazon-q-in-quicksight.md)
+ [讓 SageMaker 筆記本執行個體暫時存取另一個 AWS 帳戶中的 CodeCommit 儲存庫](give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.md)
+ [當 Amazon Data Firehose 資源未使用 AWS KMS 金鑰加密時，識別和提醒](identify-and-alert-when-amazon-data-firehose-resources-are-not-encrypted-with-an-aws-kms-key.md)
+ [將 psycopg2 程式庫匯入 AWS Lambda ，以與您的 PostgreSQL 資料庫互動](import-psycopg2-library-lambda.md)
+ [在 Microsoft Sentinel 中擷取和分析 AWS 安全日誌](ingest-analyze-aws-security-logs-sentinel.md)
+ [使用 AWS DMS，以 SSL 模式將 Amazon RDS for Oracle 遷移至 Amazon RDS for PostgreSQL](migrate-amazon-rds-for-oracle-to-amazon-rds-for-postgresql-in-ssl-mode-by-using-aws-dms.md)
+ [使用 Oracle GoldenGate 平面檔案轉接器，將 Oracle 資料庫遷移至 Amazon RDS for Oracle](migrate-an-oracle-database-to-amazon-rds-for-oracle-by-using-oracle-goldengate-flat-file-adapters.md)
+ [使用 AWS DMS 和 AWS SCT 將 Oracle 資料庫遷移至 Amazon Redshift](migrate-an-oracle-database-to-amazon-redshift-using-aws-dms-and-aws-sct.md)
+ [使用 DistCp 搭配適用於 Amazon S3 的 AWS PrivateLink，將資料從內部部署 Hadoop 環境遷移至 Amazon S3](migrate-data-from-an-on-premises-hadoop-environment-to-amazon-s3-using-distcp-with-aws-privatelink-for-amazon-s3.md)
+ [從 Couchbase Server 遷移至 AWS 上的 Couchbase Capella](migrate-from-couchbase-server-to-couchbase-capella-on-aws.md)
+ [將內部部署 Cloudera 工作負載遷移至 AWS 上的 Cloudera 資料平台](migrate-on-premises-cloudera-workloads-to-cloudera-data-platform-on-aws.md)
+ [使用應用程式復原控制器管理 EMR 叢集的多可用區域容錯移轉](multi-az-failover-spark-emr-clusters-arc.md)
+ [使用 IaC 原則自動化 Amazon Aurora 全域資料庫的藍/綠部署](p-automate-blue-green-deployments-aurora-global-databases-iac.md)
+ [使用 GitHub 動作根據 AWS CloudFormation 範本佈建 AWS Service Catalog 產品](provision-aws-service-catalog-products-using-github-actions.md)
+ [AWS Glue 使用 pytest 架構在 中執行 Python ETL 任務的單元測試](run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.md)
+ [設定 AWS ParallelCluster 的 Grafana 監控儀表板](set-up-a-grafana-monitoring-dashboard-for-aws-parallelcluster.md)
+ [將資料從 Amazon Redshift 叢集跨帳戶卸載至 Amazon S3](unload-data-from-amazon-redshift-cross-accounts-to-amazon-s3.md)
+ [使用 Flask 和 視覺化 AI/ML 模型結果 AWS Elastic Beanstalk](visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.md)