

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# AWS Lambda를 사용하여 육각형 아키텍처로 Python 프로젝트 구조화
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda"></a>

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

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

이 패턴은 AWS Lambda를 사용하여 Python 프로젝트를 육각형 아키텍처로 구성하는 방법을 보여줍니다. 이 패턴은 AWS Cloud Development Kit(AWS CDK)를 코드형 인프라(IaC) 도구로, Amazon API Gateway를 REST API로, Amazon DynamoDB를 지속성 계층으로 사용합니다. 육각형 아키텍처는 도메인 기반 설계 원칙을 따릅니다. 육각형 아키텍처에서 소프트웨어는 도메인, 포트, 어댑터라는 세 가지 구성 요소로 구성됩니다. 육각형 아키텍처와 그 이점에 대한 자세한 내용은 [AWS 기반 육각형 아키텍처 구축](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 이상
+ AWS Lambda Powertools for Python 버전 1.25.6 이상
+ pytest 버전 7.1.1 이상
+ Moto 버전 3.1.9 이상
+ pydantic 버전 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/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/25bd7169-ea5e-4a21-a865-c91c30a3c0da/images/de0d4f0d-ad19-43ec-bd10-676b25477b64.png)


API는 제품 엔티티에 대한 다섯 가지 작업을 지원합니다.
+ `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개 이상의 AWS 서비스와 서비스형 소프트웨어(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 로그 그룹](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용 AWS 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)을 사용합니다.
+ [Virtual Private Cloud(VPC) 배포](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)로 Lambda 함수를 구성하여 네트워크 트래픽을 클라우드 내에 유지합니다.
+ [Cross-origin resource sharing(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/ko_kr/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/ko_kr/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/ko_kr/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 앱 개발자 | 
| 유닛 테스트 실행 옵션 1: Visual Studio Code | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/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/ko_kr/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 Identity Center(AWS Single Sign-On 후속)를 사용하여 임시 보안 인증 정보를 생성합니다. 지침은 [AWS IAM Identity Center에서 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/ko_kr/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/ko_kr/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/ko_kr/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/ko_kr/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/ko_kr/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/ko_kr/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/ko_kr/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/ko_kr/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 가이드**
+ [AWS에서 육각형 아키텍처 구축](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/)
  + [첫 번째 AWS 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/)
+ [Python용 AWS Lambda Powertools](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/)