

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# AWS Lambda を使用して六角形アーキテクチャで Python プロジェクトを構築する
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda"></a>

*Amazon Web Services、Furkan Oruc、Dominik Goby、Darius Kunce、Michal Ploski*

## 概要
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-summary"></a>

このパターンは、AWS Lambda を使用して Python プロジェクトを六角形アーキテクチャで構築する方法を示しています。このパターンでは、Infrastructure as Code (IaC) ツールとして AWS Cloud Development Kit (AWS CDK)、REST API として Amazon API Gateway、パーシスタンスレイヤーとして Amazon DynamoDB を使用しています。六角形アーキテクチャは、ドメイン主導型の設計原則に従っています。六角形アーキテクチャでは、ソフトウェアはドメイン、ポート、アダプターの 3 つのコンポーネントで構成されます。六角形アーキテクチャとその利点の詳細については、「[ で六角形アーキテクチャを構築する](https://docs.aws.amazon.com/prescriptive-guidance/latest/hexagonal-architectures/)」ガイドを参照してください。**

## 前提条件と制限事項
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-prereqs"></a>

**前提条件**
+ アクティブなAWS アカウント
+ Python の使用経験
+ AWS Lambda、AWS CDK、Amazon API Gateway、DynamoDB に精通していること
+ GitHub アカウント (「[サインアップの手順](https://docs.github.com/en/get-started/signing-up-for-github/signing-up-for-a-new-github-account)」を参照)
+ Git (「[インストール手順](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)」を参照)
+ 変更を加えたり、コードを GitHub にプッシュしたりするためのコードエディタ ([Visual Studio Code](https://code.visualstudio.com/)、[JetBrains PyCharm](https://www.jetbrains.com/pycharm/) など)
+ Docker がインストールされ、Docker デーモンが起動して実行されていること

**製品バージョン**
+ Git バージョン 2.24.3 以降
+ Python バージョン 3.7 以降。
+ AWS CDK v2
+ Poetry バージョン 1.1.13 以降
+ Python バージョン 1.25.6 以降向け AWS Lambda Powertools
+ pytest バージョン 7.1.1 以降
+ Moto バージョン 3.1.9 以降
+ pPydantic バージョン 1.9.0 以降
+ Boto3 バージョン 1.22.4 以降
+ mypy-boto3-dynamodb バージョン 1.24.0 以降

## アーキテクチャ
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-architecture"></a>

**ターゲットテクノロジースタック**

ターゲットテクノロジースタックは、API Gateway、Lambda、および DynamoDB を使用する Python サービスで構成されます。このサービスは DynamoDB アダプターを使用してデータを保持します。エントリポイントとして Lambda を使用する関数を提供します。このサービスは Amazon API Gateway を使用して REST API を公開します。API は AWS Identity and Access Management (IAM) を使用して[クライアントの認証を行います](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)。

**ターゲットアーキテクチャ**

実装を説明するために、このパターンではサーバーレスターゲットアーキテクチャをデプロイします。クライアントは API Gateway エンドポイントにリクエストを送信できます。API Gateway は、六角形アーキテクチャパターンを実装するターゲット Lambda 関数にリクエストを転送します。Lambda 関数は、DynamoDB テーブルで作成、読み取り、更新、および削除 (CRUD) 操作を実行します。


| 
| 
| このパターンは PoC 環境でテストされました。アーキテクチャを実稼働環境にデプロイする前に、セキュリティレビューを実施して脅威モデルを特定し、安全なコードベースを作成する必要があります。 | 
| --- |

![\[Python プロジェクトを六角形アーキテクチャで構築するためのターゲットアーキテクチャ\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/images/pattern-img/25bd7169-ea5e-4a21-a865-c91c30a3c0da/images/de0d4f0d-ad19-43ec-bd10-676b25477b64.png)


API は、製品エンティティに対する 5 つの操作をサポートします。
+ `GET /products` はすべての製品を返します。
+ `POST /products` は新しい製品を作成します。
+ `GET /products/{id}` は特定の商品を返します。
+ `PUT /products/{id}` は特定の製品を更新します。
+ `DELETE /products/{id}` は特定の製品を削除します。

以下のフォルダ構造を使用して、六角形アーキテクチャパターンに従ってプロジェクトを整理できます。  

```
app/  # application code
|--- adapters/  # implementation of the ports defined in the domain
     |--- tests/  # adapter unit tests
|--- entrypoints/  # primary adapters, entry points
     |--- api/  # api entry point
          |--- model/  # api model
          |--- tests/  # end to end api tests
|--- domain/  # domain to implement business logic using hexagonal architecture
     |--- command_handlers/  # handlers used to execute commands on the domain
     |--- commands/  # commands on the domain
     |--- events/  # events triggered via the domain
     |--- exceptions/  # exceptions defined on the domain
     |--- model/  # domain model
     |--- ports/  # abstractions used for external communication
     |--- tests/  # domain tests
|--- libraries/  # List of 3rd party libraries used by the Lambda function
infra/  # infrastructure code
simple-crud-app.py  # AWS CDK v2 app
```

## ツール
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-tools"></a>

** サービス**
+ [Amazon API Gateway](https://aws.amazon.com/api-gateway/) は、デベロッパーがあらゆる規模で API の公開、保守、モニタリング、セキュリティ保護を簡単に行えるフルマネージドサービスです。
+ [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) は、あらゆる規模で高性能アプリケーションを実行できるように設計された、完全マネージド型のサーバーレスのキーバリュー型 NoSQL データベースです。
+ [AWS Lambda](https://aws.amazon.com/lambda/) は、サーバーレスのイベント駆動型のコンピューティングサービスで、サーバーのプロビジョニングや管理を行わなくても、実質あらゆるタイプのアプリケーションやバックエンドサービスのコードを実行できます。200 以上の Software as a Service (SaaS) アプリケーションから Lambda 関数を起動できます。お支払いいただくのは使用した分のみです。

**ツール**
+ このパターンでは、コード開発のバージョン管理システムとして [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) が使用されます。
+ このパターンのプログラミング言語には [Python](https://www.python.org/) が使用されています。Python は、高レベルのデータ構造とオブジェクト指向プログラミングへのアプローチを提供します。AWS Lambda には Python サービスの操作を簡素化する組み込みの Python ランタイムが用意されています。
+ このパターンの開発とテストには、[Visual Studio Code](https://code.visualstudio.com/) が IDE として使用されています。Python 開発のサポートには、任意の IDE ([PyCharm](https://www.jetbrains.com/pycharm/) など) を使用できます。
+ [AWS Cloud Development Kit (AWS CDK)](https://aws.amazon.com/cdk/) は、使い慣れたプログラミング言語を使用してクラウドアプリケーションリソースを定義できるオープンソースのソフトウェア開発フレームワークです。このパターンでは、CDK を使用してクラウドインフラストラクチャをコードとして記述し、デプロイします。
+ [Poetry](https://python-poetry.org/) はパターン内の依存関係を管理するために使用されます。
+ [Docker](https://www.docker.com/) は AWS CDK が Lambda パッケージとレイヤーを構築するために使用します。

**コード**

このパターンのコードは、GitHub 内の「[Lambda 六角形アーキテクチャのサンプル](https://github.com/aws-samples/lambda-hexagonal-architecture-sample)」リポジトリで利用できます。

## ベストプラクティス
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-best-practices"></a>

実稼働環境でこのパターンを使用するには、次のベストプラクティスに従ってください。
+ AWS Key Management Service (AWS KMS) のカスタマーマネージドキーを使用して [Amazon CloudWatch Logs グループ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html)と [Amazon DynamoDB テーブル](https://docs.aws.amazon.com/kms/latest/developerguide/services-dynamodb.html)を暗号化します。
+ 組織のネットワークからのアクセスのみを許可するように [Amazon API Gateway 用 WAF](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-aws-waf.html) を構成します。
+ IAM がニーズを満たさない場合は、API Gateway 認可の他のオプションを検討してください。たとえば、[Amazon Cognito ユーザープール](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html)や [API Gateway Lambda オーソライザー](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)を使用できます。
+ [DynamoDB バックアップ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)の使用
+ [仮想プライベートクラウド (VPC) のデプロイ](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)で Lambda 関数を構成し、ネットワークトラフィックをクラウド内に維持します。
+ [クロスオリジンリソースシェアリング (CORS) プリフライト](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)の許可オリジン構成を更新して、リクエスト元のオリジンドメインのみにアクセス制限します。
+ [cdk-nag](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/check-aws-cdk-applications-or-cloudformation-templates-for-best-practices-by-using-cdk-nag-rule-packs.html) を使用して、AWS CDK コードのセキュリティベストプラクティスを確認します。
+ コードスキャンツールを使用して、コードの一般的なセキュリティ問題を見つけることを検討してください。たとえば、[Bandit](https://bandit.readthedocs.io/en/latest/) は Python コードの一般的なセキュリティ問題を検出するために設計されたツールです。[Pip-audit](https://pypi.org/project/pip-audit/) は Python 環境をスキャンして、既知の脆弱性があるパッケージを探します。

このパターンでは、[AWS X-Ray](https://aws.amazon.com/xray/?nc1=h_ls) を使用して、アプリケーションのエントリポイント、ドメイン、アダプタを通じてリクエストをトレースします。AWS X-Ray は、開発者がボトルネックを特定して高いレイテンシーを洗い出し、アプリケーションのパフォーマンスを向上させるのに役立ちます。

## エピック
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-epics"></a>

### プロジェクトを初期化する
<a name="initialize-the-project"></a>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| 独自のリポジトリを作成します。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| 依存関係をインストールします。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| IDE を構成する。 | Visual Studio Code をお勧めしますが、Python をサポートする任意の IDE でもかまいません。次の手順は、Visual Studio Code 用です。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| ユニットテストを実行する。オプション 1: Visual Studio コードを使用する。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| ユニットテストを実行する。オプション 2: シェルコマンドを使用する。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 

### アプリケーションをデプロイしてテストする
<a name="deploy-and-test-the-application"></a>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| 一時的な認証情報をリクエストします。 | `cdk deploy` の実行時にシェルに AWS 認証情報を保存するには、AWS IAM アイデンティティセンター (AWS シングルサインオンの後継) を使用して一時的な認証情報の作成を行います。手順については、ブログ記事「[ IAM アイデンティティセンター で CLI を使用するための短期認証情報を取得する方法](https://aws.amazon.com/blogs/security/aws-single-sign-on-now-enables-command-line-interface-access-for-aws-accounts-using-corporate-credentials/)」を参照してください。 | アプリ開発者、AWS DevOps | 
| アプリケーションをデプロイします。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者、AWS DevOps | 
| API をテストする。オプション 1: コンソールを使用する。 | [API Gateway コンソール](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-test-method.html)を使用して API メソッドをテストします。API の操作とリクエスト/レスポンスメッセージの詳細については、GitHub リポジトリの 「[readme ファイルの API 使用状況セクション](https://github.com/aws-samples/lambda-hexagonal-architecture-sample/blob/main/README.md#api-usage)」を参照してください。 | アプリ開発者、AWS DevOps | 
| API をテストする。オプション 2: Postman を使用する。 | [Postman](https://www.postman.com/) などのツールを使用する場合:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者、AWS DevOps | 

### サービスの開発
<a name="develop-the-service"></a>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| ビジネスドメインのユニットテストを書きます。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| コマンドとコマンドハンドラーを実装します。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| セカンダリアダプターの統合テストを書く。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| セカンダリアダプタを実装する。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| エンドツーエンドテストを作成する。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 
| プライマリアダプタを実装する。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | アプリ開発者 | 

## 関連リソース
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-resources"></a>

**APG ガイド**
+ [ で六角形アーキテクチャを構築する](https://docs.aws.amazon.com/prescriptive-guidance/latest/hexagonal-architectures/)

**AWS リファレンス**
+ [AWS Lambda ドキュメント](https://docs.aws.amazon.com/lambda/)
+ [AWS CDK ドキュメント](https://docs.aws.amazon.com/cdk/)
  + [初めての CDK アプリケーション](https://docs.aws.amazon.com/cdk/v2/guide/hello_world.html)
+ [API Gateway ドキュメント](https://docs.aws.amazon.com/apigateway/)
  + [IAM アクセス許可により API へのアクセスを制御する](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)
  + [API Gateway コンソールを使用して REST API メソッドをテストする](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-test-method.html)
+ [Amazon DynamoDB ドキュメント](https://docs.aws.amazon.com/dynamodb/)

**ツール**
+ [git-scm.com ウェブサイト](https://git-scm.com/)
+ [Git のインストール](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
+ [新しい GitHub リポジトリの作成](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository)
+ [Python ウェブサイト](https://www.python.org/)
+ 「[AWS Lambda Powertools for Python](https://docs.powertools.aws.dev/lambda/python/latest/)」
+ [Postman ウェブサイト](https://www.postman.com/)
+ [Python モックオブジェクトライブラリ](https://docs.python.org/3/library/unittest.mock.html)
+ [Poetry ウェブサイト](https://python-poetry.org/)

**IDE**
+ [Visual Studio Code ウェブサイト](https://code.visualstudio.com/)
+ [PyCharm ウェブサイト](https://www.jetbrains.com/pycharm/)