

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

# DevOps
<a name="devops-pattern-list"></a>

**Topics**
+ [Backstage와 셀프 서비스 Amazon SageMaker AI 템플릿으로 MLOps 가속화](accelerate-mlops-with-backstage-and-sagemaker-templates.md)
+ [Amazon Bedrock을 사용하여 AWS 인프라 작업 자동화](automate-aws-infrastructure-operations-by-using-amazon-bedrock.md)
+ [Terraform을 사용하여 로드 밸런서 엔드포인트 변경 시 CloudFront 업데이트 자동화](automate-cloudfront-updates-when-load-balancer-endpoints-change.md)
+ [GitHub Actions를 사용하여 AWS CDK Python 애플리케이션에 대한 Amazon CodeGuru 리뷰 자동화](automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.md)
+ [GitHub Actions, Artifactory 및 Terraform을 사용하여 다중 리포지토리 설정에서 AWS Supply Chain 데이터 레이크 배포 자동화](automate-the-deployment-of-aws-supply-chain-data-lakes.md)
+ [AWS 리소스 평가 자동화](automate-aws-resource-assessment.md)
+ [오픈소스 도구를 사용하여 SAP 시스템을 자동으로 설치](install-sap-systems-automatically-by-using-open-source-tools.md)
+ [AWS CDK를 사용하여 AWS Service Catalog 포트폴리오 및 제품 배포 자동화](automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.md)
+ [AWS Service Catalog 및를 사용하여 Gitflow 환경에 핫픽스 솔루션을 배포하기 위한 동적 파이프라인 관리 자동화 AWS CodePipeline](automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.md)
+ [AWS CloudFormation 스택 및 관련 리소스의 삭제 자동화](automate-deletion-cloudformation-stacks-associated-resources.md)
+ [Terraform을 사용하여 Amazon Managed Grafana에서 Amazon MWAA 사용자 지정 지표의 수집 및 시각화 자동화](automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.md)
+ [AWS CodePipeline 및 AWS CodeBuild를 사용하여 스택 세트 배포를 자동화하기](automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.md)
+ [Cloud Custodian 및 AWS CDK를 사용하여 Systems Manager용 AWS 관리형 정책을 EC2 인스턴스 프로파일에 자동으로 연결](automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.md)
+ [AWS CDK를 사용하여 마이크로서비스용 CI/CD 파이프라인 및 Amazon ECS 클러스터 자동으로 구축](automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.md)
+ [GitHub Actions 및 Terraform을 사용하여 Docker 이미지를 빌드하고 Amazon ECR에 푸시](build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform.md)
+ [AWS CodeCommit, AWS CodePipeline, AWS Device Farm을 사용하여 iOS 앱을 구축하고 테스트할 수 있습니다.](build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm.md)
+ [Amazon EKS에서 실행되는 애플리케이션에 대한 상호 TLS 인증을 구성합니다.](configure-mutual-tls-authentication-for-applications-running-on-amazon-eks.md)
+ [를 사용하여 Amazon WorkSpaces 애플리케이션 리소스 생성 자동화 AWS CloudFormation](automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.md)
+ [Firelens 로그 라우터를 사용하여 Amazon ECS용 사용자 지정 로그 구문 분석기를 생성](create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.md)
+ [GitHub Actions 및 Terragrunt를 사용하여 API 기반 리소스 오케스트레이션 프레임워크 생성](create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.md)
+ [GitHub Actions를 사용하여 Terraform 관리형 AWS 인프라에 대한 자동 풀 요청 생성](create-automated-pull-requests-for-terraform-managed-aws-infrastructure.md)
+ [Java 및 Python 프로젝트를 위한 동적 CI 파이프라인을 자동으로 생성](create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.md)
+ [Terraform을 사용하여 CloudWatch Synthetics canary 배포](deploy-cloudwatch-synthetics-canaries-by-using-terraform.md)
+ [채팅 애플리케이션에서 Amazon Q Developer 사용자 지정 작업 및를 사용하여 SAST 스캔 결과를 관리하는 ChatOps 솔루션 배포 CloudFormation](deploy-chatops-solution-to-manage-sast-scan-results.md)
+ [Terraform을 사용하여 CrewAI 프레임워크를 사용하여 Amazon Bedrock에 에이전트 시스템 배포](deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.md)
+ [AWS CodePipeline CI/CD 파이프라인을 사용하여 AWS Glue 작업 배포](deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline.md)
+ [AWS CodePipeline, AWS CodeCommit, AWS CodeBuild를 사용하여 여러 AWS 리전에 코드 배포](deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild.md)
+ [Azure DevOps 파이프라인에서 프라이빗 Amazon EKS 클러스터로 워크로드 배포](deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.md)
+ [Terraform을 사용하여 Amazon Redshift SQL 쿼리 실행](execute-redshift-sql-queries-using-terraform.md)
+ [AWS Organizations의 조직 전체에서 AWS Backup 보고서를 CSV 파일로 내보내기](export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.md)
+ [Amazon EC2 인스턴스 목록의 태그를 CSV 파일로 내보내기](export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file.md)
+ [Troposphere를 사용하여 AWS Config 관리형 규칙이 포함된 AWS CloudFormation 템플릿을 생성합니다.](generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere.md)
+ [SageMaker 노트북 인스턴스에 다른 AWS 계정의 CodeCommit 리포지토리에 대한 임시 액세스 권한 부여](give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.md)
+ [다중 계정 DevOps 환경을 위한 GitHub Flow 분기 전략 구현](implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.md)
+ [다중 계정 DevOps 환경을 위한 Gitflow 분기 전략 구현](implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.md)
+ [다중 계정 DevOps 환경을 위한 트렁크 분기 전략 구현](implement-a-trunk-branching-strategy-for-multi-account-devops-environments.md)
+ [AWS 인프라를 배포하기 전에 중앙 집중식 사용자 지정 Checkov 스캔을 구현하여 정책을 적용합니다.](centralized-custom-checkov-scanning.md)
+ [K8sGPT 및 Amazon Bedrock 통합을 사용하여 AI 기반 Kubernetes 진단 및 문제 해결 구현](implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration.md)
+ [CodeCommit의 모노리포지토리에 대한 변경 사항 자동 감지 및 다양한 CodePipeline 파이프라인 시작](automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.md)
+ [AWS CloudFormation을 사용하여 Bitbucket 리포지토리를 AWS Amplify와 통합](integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.md)
+ [Step Functions와 Lambda 프록시 함수를 사용하여 여러 AWS 계정에서 CodeBuild 프로젝트 시작](launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.md)
+ [Application Recovery Controller를 사용하여 EMR 클러스터에 대한 다중 AZ 장애 조치 관리](multi-az-failover-spark-emr-clusters-arc.md)
+ [AWS 코드 서비스 및 AWS KMS 다중 리전 키를 사용하여 여러 계정 및 리전에 대한 마이크로서비스의 블루/그린 배포를 관리](manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.md)
+ [AWS CloudFormation과 AWS Config를 사용하여 Amazon ECR 리포지토리에서 와일드카드 권한 모니터링](monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config.md)
+ [AWS CDK 및 GitHub Actions 워크플로를 사용하여 다중 계정 서버리스 배포 최적화](optimize-multi-account-serverless-deployments.md)
+ [GitHub Actions를 사용하여 AWS CloudFormation 템플릿을 기반으로 AWS Service Catalog 제품 프로비저닝](provision-aws-service-catalog-products-using-github-actions.md)
+ [역할 벤딩 머신 솔루션을 배포하여 최소 권한 IAM 역할 프로비저닝](provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.md)
+ [Amazon CloudWatch 지표를 CSV 파일에 게시](publish-amazon-cloudwatch-metrics-to-a-csv-file.md)
+ [AWS Lambda 자동화 AWS Managed Microsoft AD 를 사용하여 AWS 계정 에서의 Amazon EC2 항목 제거](remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.md)
+ [AWS Lambda 자동화를 AWS 계정 AWS Managed Microsoft AD 사용하여 동일한에서 Amazon EC2 항목 제거](remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.md)
+ [pytest 프레임워크를 AWS Glue 사용하여에서 Python ETL 작업에 대한 단위 테스트 실행](run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.md)
+ [AWS CodePipeline 및 AWS CDK를 사용하여 CI/CD 파이프라인 설정하기](set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.md)
+ [Terraform을 사용하여 엔터프라이즈 규모로 중앙 집중식 로깅 설정](set-up-centralized-logging-at-enterprise-scale-by-using-terraform.md)
+ [cert-manager 및 Let's Encrypt를 사용하여 Amazon EKS의 애플리케이션에 대한 종단 간 암호화 설정](set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt.md)
+ [Flux를 사용하여 Amazon EKS 멀티 테넌트 애플리케이션 배포 간소화](simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.md)
+ [자동화된 워크플로를 사용하여 Amazon Lex 봇 개발 및 배포 간소화](streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.md)
+ [AWS Fargate WaitCondition 후크 구성을 사용하여 리소스 종속성과 작업 실행을 조정합니다.](use-the-aws-fargate-waitcondition-hook-construct.md)
+ [AWS CodePipeline의 타사 Git 소스 리포지토리 사용](use-third-party-git-source-repositories-in-aws-codepipeline.md)
+ [AWS CodePipeline을 사용하여 Terraform 구성을 검증하는 CI/CD 파이프라인 생성](create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.md)
+ [패턴 더 보기](devops-more-patterns-pattern-list.md)

# Backstage와 셀프 서비스 Amazon SageMaker AI 템플릿으로 MLOps 가속화
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates"></a>

*Ashish Bhatt, Shashank hirematt, Shivanshu Suryakar, Amazon Web Services*

## 요약
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-summary"></a>

기계 학습 운영(MLOps) 시스템을 사용하는 조직들은 ML 인프라를 확장, 표준화 및 보호하는 데 상당한 어려움을 겪고 있습니다. 이 패턴은 오픈 소스 개발자 포털인 [Backstage](https://backstage.io/)를 [Amazon SageMaker AI](https://aws.amazon.com/sagemaker/) 및 강화된 코드형 인프라(IaC) 모듈과 결합하여 데이터 과학 팀이 ML 워크플로를 개발, 배포, 관리하는 방법을 개선하는 혁신적인 접근 방식을 적용합니다.

이 패턴의 IaC 모듈은 GitHub [AWS AIOps 모듈](https://github.com/awslabs/aiops-modules/tree/main/modules/sagemaker) 리포지토리에서 제공됩니다. 이러한 모듈은 ML 인프라를 설정하고 일관된 ML 환경을 생성하도록 사전 구축된 템플릿을 제공합니다. 그러나 데이터 과학자는 인프라 전문 지식이 필요하기 때문에 이러한 템플릿을 직접 사용하는 데 어려움을 겪는 경우가 많습니다. Backstage와 같은 개발자 포털을 추가하면 데이터 과학자가 기본 인프라 세부 정보를 이해할 필요 없이 표준화된 ML 환경을 배포할 수 있는 사용자 친화적인 방법이 만들어집니다.

Backstage를 셀프 서비스 플랫폼으로 사용하고 미리 구성된 SageMaker AI 템플릿을 통합하여 다음을 수행할 수 있습니다.
+ ML 이니셔티브의 가치 실현 시간을 단축합니다.
+ 일관된 보안 및 거버넌스를 적용하는 데 도움이 됩니다.
+ 데이터 과학자에게 표준화된 규정 준수 환경을 제공합니다.
+ 운영 오버헤드와 인프라 복잡성을 줄입니다.

이 패턴은 MLOps의 중요한 문제를 해결하는 솔루션을 제공하고 조직 표준을 유지하면서 혁신을 가능케 하는 확장 및 반복 가능한 프레임워크도 제공합니다.

**대상 청중**

이 패턴은 조직 내 ML, 클라우드 아키텍처 및 플랫폼 엔지니어링과 관련된 광범위한 대상을 대상으로 합니다. 여기에는 다음이 포함됩니다.
+ ML 워크플로 배포를 표준화하고 자동화하려는 **ML 엔지니어**.
+ 사전 구성되고 규정을 준수하는 ML 환경에 대한 셀프 서비스 액세스를 원하는 **데이터 과학자**.
+ 내부 개발자 플랫폼 및 공유 인프라를 구축하고 유지 관리할 책임이 있는 **플랫폼 엔지니어**.
+ MLOps를 위한 확장 가능하고 안전하며 비용 효율적인 클라우드 솔루션을 설계하는 **클라우드 아키텍트**.
+ 지속적 통합 및 지속적 전달(CI/CD) 방식을 ML 인프라 프로비저닝 및 워크플로로 확장하는 데 관심이 있는 **DevOps 엔지니어**.
+ ML 이니셔티브를 감독하고 팀 생산성, 거버넌스 및 시장 출시 시간을 개선하고자 하는 **기술 책임자 및 관리자**.

MLOps 과제, SageMaker AI MLOps 모듈 및이 패턴에서 제공하는 솔루션이 ML 팀의 니즈를 어떻게 해결하는지 자세히 알아보려면 [추가 정보](#accelerate-mlops-with-backstage-and-sagemaker-templates-additional) 섹션을 참조하세요.

## 사전 조건 및 제한 사항
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-prereqs"></a>

**사전 조건 **
+ AWS Identity and Access Management 에 리소스를 프로비저닝하기 위한 (IAM) [역할 및 권한](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#prerequisites) AWS 계정
+ [Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated.html), [SageMaker Projects](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-projects-whatis.html), [SageMaker Pipelines](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html) 및 [SageMaker Model Registry](https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry.html) 개념에 대한 이해
+ [AWS Cloud Development Kit (AWS CDK)](https://aws.amazon.com/cdk/)와 같은 도구를 사용한 IaC 원칙 및 경험에 대한 이해

**제한 사항 **
+ **제한된 템플릿 적용 범위**. 현재 이 솔루션은 더 포괄적인 AIOps 솔루션의 SageMaker AI 관련 [AIOps](https://github.com/awslabs/aiops-modules) 모듈만 지원합니다. Amazon Elastic Kubernetes Service(Amazon EKS)의 Ray, MLflow, Apache Airflow, Amazon Bedrock의 미세 조정과 같은 다른 모듈은 아직 Backstage 템플릿으로 사용할 수 없습니다.
+ **구성할 수 없는 기본 설정**. 템플릿에는 AIOps SageMaker 모듈의 고정 기본 구성이 사용자 지정 없이 사용됩니다. 특정 사용 사례에 대한 유연성을 제한하는 Backstage 인터페이스를 통해 인스턴스 유형, 스토리지 크기, 네트워킹 구성 또는 보안 정책을 수정할 수 없습니다.
+ **AWS만 지원**. 플랫폼은 AWS 배포 전용으로 설계되었으며 멀티클라우드 시나리오를 지원하지 않습니다. 외부에서 클라우드 서비스를 사용하는 조직은 ML 인프라 요구 사항에 이러한 템플릿을 사용할 수 AWS 클라우드 없습니다.
+ **수동 자격 증명 관리**. 각 배포에 대한 AWS 자격 증명을 수동으로 제공해야 합니다. 이 솔루션은 기업 자격 증명 공급자와의 통합 AWS IAM Identity Center또는 자동 자격 증명 교체를 제공하지 않습니다.
+ **제한적 수명 주기 관리**. 템플릿에는 자동 정리 정책, 비용 최적화 권장 사항, 인프라 드리프트 감지와 같은 포괄적인 리소스 수명 주기 관리 기능이 없습니다. 생성된 후 배포된 리소스를 수동으로 관리하고 모니터링해야 합니다.

## 아키텍처
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-architecture"></a>

다음 다이어그램은 환경 전반에서 SageMaker AI를 사용하여 ML 인프라 배포를 표준화하고 가속화하는 통합 개발자 포털의 솔루션 아키텍처를 보여줍니다.

![\[Backstage, CNOE, GitHub Actions 및 Seed-Farmer를 사용하는 통합 개발자 포털용 아키텍처입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/c16160cf-d637-423e-93a7-485ffbb28646/images/233adab3-83cf-42f3-a1de-72d0b8ade5ae.png)


이 아키텍처에서,

1. [AWS 애플리케이션 현대화 블루프린트는](https://github.com/aws-samples/appmod-blueprints.git) [클라우드 네이티브 운영 우수성(CNOE)](https://cnoe.io/) 프레임워크의 기반으로 [Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) 클러스터를 사용하여 인프라 설정을 프로비저닝합니다. 이 포괄적인 솔루션은 확장 가능한 내부 개발자 플랫폼(IDP)을 제공하여 복잡한 클라우드 네이티브 인프라 관리 문제를 해결합니다. 블루프린트는 진화하는 조직의 요구 사항에 맞게 조정할 수 있는 강력하고 유연한 인프라를 설정하는 체계적인 접근 방식을 제공합니다.

1. CNOE 오픈 소스 프레임워크는 통합 플랫폼 엔지니어링 접근 방식을 통해 DevOps 도구를 통합하고 에코시스템 조각화를 해결합니다. 서로 다른 도구와 기술을 결합하여 클라우드 네이티브 개발의 복잡한 환경을 간소화하므로 팀은 도구 체인을 관리하는 것이 아니라 혁신에 집중할 수 있습니다. 프레임워크는 개발 도구를 선택, 통합 및 관리하기 위한 표준화된 방법론을 제공합니다.

1. CNOE를 사용하면 Backstage가 Amazon EKS 클러스터 내에 바로 사용 가능한 솔루션으로 배포됩니다. 백스테이지는 [Keycloak](https://www.keycloak.org/)를 통한 강력한 인증과 [Argo CD](https://argo-cd.readthedocs.io/en/stable/)를 통한 포괄적인 배포 워크플로로 번들링됩니다. 이 통합 플랫폼은 개발 프로세스를 관리하기 위한 중앙 집중식 환경을 생성하고 팀이 한곳에서 여러 환경에서 인프라와 애플리케이션에 액세스, 배포, 모니터링할 수 있게 합니다.

1. GitHub 리포지토리에는 전체 SageMaker AI 수명 주기를 포함하는 사전 구성된 AIOps 소프트웨어 템플릿이 포함되어 있습니다. 이 템플릿은 SageMaker Studio 프로비저닝, 모델 훈련, 추론 파이프라인, 모델 모니터링 등, 중요한 ML 인프라 니즈를 해결합니다. 이 템플릿은 ML 이니셔티브를 가속화하고 다양한 프로젝트 및 팀 간의 일관성을 보장하는 데 도움이 됩니다.

1. [GitHub Actions](https://github.com/features/actions)는 [Seed-Farmer](https://github.com/awslabs/seed-farmer) 유틸리티를 통해 리소스 프로비저닝을 동적으로 트리거하는 자동화된 워크플로를 구현합니다. 이 접근 방식은 Backstage 카탈로그를 AIOps 모듈 리포지토리와 통합하고 간소화된 인프라 배포 프로세스를 생성합니다. 이러한 자동화는 수동 개입을 줄이고 인적 오류를 최소화하며 다양한 환경에서 빠르고 일관된 인프라 생성을 보장합니다.

1. [AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/home.html)는 코드형 인프라를 정의하고 프로비저닝하는 데 도움이 되며 지정된 AWS 계정에서 반복 가능하고 안전하며 규정을 준수하는 리소스 배포를 보장합니다. 이 접근 방식은 최소한의 수동 개입으로 최대 거버넌스를 제공하므로 쉽게 복제, 버전 관리 및 감사할 수 있는 표준화된 인프라 템플릿을 생성할 수 있습니다.

## 도구
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-tools"></a>

**AWS 서비스**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)는 코드로 AWS 클라우드 인프라를 정의하고 프로비저닝하는 데 도움이 되는 소프트웨어 개발 프레임워크입니다.
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)를 사용하면 자체 Kubernetes 컨트롤 플레인 또는 노드를 설치하거나 유지 관리할 필요 AWS 없이에서 Kubernetes를 실행할 수 있습니다.
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/)는 ML 모델을 구축하고 학습시킬 수 있으며 해당 모델을 프로덕션 지원 호스팅 환경에 배포할 수 있는 관리형 ML 서비스입니다.

**기타 도구**
+ [Backstage](https://backstage.io/)는 내부 개발자 포털을 구축하는 데 도움이 되는 오픈 소스 프레임워크입니다.
+ [GitHub Actions](https://github.com/features/actions)는 코드 빌드, 테스트 및 배포와 같은 작업을 비롯하여 소프트웨어 개발 워크플로를 자동화하는 CI/CD 플랫폼입니다.

**코드 리포지토리**

이 패턴에는 다음 GitHub 리포지토리의 코드와 템플릿이 사용됩니다.
+ [Backstage 리포지토리를 사용하는 AIOps 내부 개발자 플랫폼(IDP)](https://github.com/aws-samples/sample-aiops-idp-backstage/) 
+ [AWS AIOps 모듈](https://github.com/awslabs/aiops-modules) 리포지토리의 SageMaker AI 관련 모듈 
+ [AWS의 현대적 엔지니어링](https://github.com/aws-samples/appmod-blueprints) 리포지토리

**구현**

이 구현은 [AWS의 현대적 엔지니어링](https://github.com/aws-samples/appmod-blueprints) 리포지토리에서 백스테이지용 프로덕션급 배포 패턴을 사용합니다. 이 접근 방식은 보안 및 확장성에 대한 AWS 모범 사례를 통합하면서 설정 프로세스를 크게 간소화합니다.

이 패턴의 [Epics](#accelerate-mlops-with-backstage-and-sagemaker-templates-epics) 섹션에서는 구현 접근 방식을 간략하게 설명합니다. 자세한 단계별 배포 지침은 [Backstage를 사용한 AIOps 내부 개발자 플랫폼(IDP)](https://github.com/aws-samples/sample-aiops-idp-backstage/) 리포지토리에서 제공되는 포괄적인 [배포 가이드](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md)를 참조하세요. 이 구현에는 다음이 포함됩니다.
+ 초기 Backstage 플랫폼 배포
+ SageMaker 소프트웨어 템플릿을 Backstage와 통합
+ Backstage 템플릿 사용 및 유지 관리

배포 가이드에는 지속적인 유지 관리, 문제 해결 및 플랫폼 조정에 대한 지침도 포함되어 있습니다.

## 모범 사례
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-best-practices"></a>

MLOps 인프라 구현에서 보안, 거버넌스 및 운영 우수성을 보장하려면 다음 모범 사례를 따릅니다.

**템플릿 관리**
+ 라이브 템플릿을 변경해서는 안 됩니다.
+ 프로덕션 배포 전에 항상 업데이트를 철저히 테스트합니다.
+ 명확하고 잘 문서화된 템플릿 버전을 유지 관리합니다.

**보안**
+ GitHub 작업을 특정 커밋 보안 해시 알고리즘(SHA)으로 고정하여 공급망 공격을 방지합니다.
+ 세분화된 권한으로 최소 권한 IAM 역할을 사용합니다.
+ 민감한 자격 증명은 [GitHub Secrets](https://docs.github.com/en/actions/concepts/security/secrets) 및 [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)에 저장합니다.
+ 템플릿에서 자격 증명을 하드코딩하지 마세요.

**거버넌스 및 추적**
+ 포괄적인 리소스 태깅 표준을 구현합니다.
+ 정교한 비용 추적 및 규정 준수 모니터링을 활성화합니다.
+ 인프라 변경에 대한 명확한 감사 추적을 유지 관리합니다.

이 가이드에서는 Backstage, SageMaker AI 및 IaC 모듈을 사용하여 이러한 모범 사례를 구현하기 위한 강력한 기초를 제공합니다.

## 에픽
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-epics"></a>

### ML 환경 설정
<a name="set-up-your-ml-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Backstage를 배포합니다. | 이 단계에서는 리포지토리의 [최신 엔지니어링의 AWS](https://github.com/aws-samples/appmod-blueprints) 블루프린트를 사용하여 여러를 통합하여 ML 워크플로 AWS 서비스 를 위한 중앙 집중식 IDP를 생성하는 강력하고 확장 가능한 인프라를 구축합니다. 배포 가이드의 [백스테이지 배포 섹션에](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#backstage-deployment) 있는 지침에 따라 리포지토리를 복제하고, 종속성을 설치하고, 환경 변수 AWS CDK 구성을 부트스트랩하고, 백스테이지 플랫폼을 배포합니다.이 인프라를 Amazon EKS를 IDP 구성 요소를 배포하기 위한 컨테이너 오케스트레이션 플랫폼으로 사용합니다. Amazon EKS 아키텍처에는 엄격한 네트워크 격리를 설정하고 액세스 패턴을 제어하는 보안 네트워킹 구성이 포함되어 있습니다. 이 플랫폼은 인증 메커니즘과 통합되어 서비스 및 환경 전반에서 사용자 액세스를 보호합니다. | 플랫폼 엔지니어 | 
| SageMaker AI 템플릿을 설정합니다. | 이 단계에서는 GitHub [AIOps 내부 개발자 플랫폼(IDP)의 스크립트를 Backstage](https://github.com/aws-samples/sample-aiops-idp-backstage/) 리포지토리와 함께 사용합니다. 배포 가이드의 [SageMaker 템플릿 설정](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#sagemaker-template-setup) 섹션에 있는 지침에 따라 리포지토리를 복제하고, 사전 조건을 설정하고, 설정 스크립트를 실행합니다.이 프로세스는 Backstage와의 통합에 필요한 SageMaker AI 템플릿이 포함된 리포지토리를 생성합니다. | 플랫폼 엔지니어 | 
| SageMaker AI** **템플릿을 Backstage와 통합합니다. | 배포 가이드의 [SageMaker 템플릿 통합](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#sagemaker-templates-integration) 섹션에 있는 지침에 따라 SageMaker AI 템플릿을 등록합니다.이 단계에서는 ML 인프라 요구 사항을 셀프 서비스할 수 있도록 AIOps 모듈(마지막 단계의 SageMaker AI 템플릿)을 백스테이지 배포에 통합니다. | 플랫폼 엔지니어 | 
| Backstage의 SageMaker AI 템플릿을 사용합니다. | 배포 가이드의 [SageMaker 템플릿 사용](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#using-sagemaker-templates) 섹션에 나와 있는 지침에 따라 Backstage 포털에 액세스하고 SageMaker Studio에서 ML 환경을 생성합니다.Backstage 포털에서 SageMaker Studio 환경, SageMaker 노트북, 사용자 지정 SageMaker 프로젝트 템플릿 및 모델 배포 파이프라인에 대한 옵션을 비롯하여 사용 가능한 SageMaker AI 템플릿 중에서 선택할 수 있습니다. 구성 파라미터를 제공하면 플랫폼은 전용 리포지토리를 자동으로 생성하고 GitHub Actions 및 Seed-Farmer를 통해 AWS 리소스를 프로비저닝합니다. GitHub Actions 로그와 Backstage 구성 요소 카탈로그를 통해 진행 상황을 모니터링할 수 있습니다. | 데이터 과학자, 데이터 엔지니어, 개발자 | 

### 거버넌스 및 규정 준수를 위한 템플릿 관리
<a name="manage-templates-for-governance-and-compliance"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| SageMaker AI 템플릿을 업데이트합니다. | Backstage에서 SageMaker AI 템플릿을 업데이트하려면 다음 단계를 따릅니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/accelerate-mlops-with-backstage-and-sagemaker-templates.html) | 플랫폼 엔지니어 | 
| 템플릿의 여러 버전을 생성하고 관리합니다. | 주요 변경 사항 또는 업그레이드의 경우 SageMaker AI 템플릿의 여러 버전을 생성해야 할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/accelerate-mlops-with-backstage-and-sagemaker-templates.html) | 플랫폼 엔지니어 | 

### ML 환경 확장
<a name="extend-your-ml-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 템플릿 적용 범위를 SageMaker AI를 외부로 확장합니다. | 현재 솔루션은 SageMaker AI 관련 AIOps 템플릿만 구현합니다. [AIOps 모듈을](https://github.com/awslabs/aiops-modules) 추가하고 추가 AWS 서비스 및 애플리케이션을 위한 사용자 지정 소프트웨어 템플릿을 통합하여 ML 환경을 확장할 수 있습니다. Backstage에서 템플릿 디자이너 인터페이스를 사용하거나, 사용자 지정 스캐폴더 작업을 구현하거나, 표준 메타데이터로 템플릿 리포지토리를 유지 관리하여 템플릿을 생성할 수 있습니다. 플랫폼은 일관성을 위해 템플릿 버전 관리, 팀 간 공유 및 검증 워크플로를 지원합니다. 자세한 내용은 [Backstage 설명서](https://backstage.io/docs/overview/what-is-backstage/)를 참조하세요.템플릿 상속 패턴을 구현하여 기본 템플릿의 특수 버전을 생성할 수도 있습니다. 이러한 확장성을 통해 SageMaker AI를 넘어 다양한 AWS 리소스와 애플리케이션을 관리하는 동시에 간소화된 개발자 환경을 유지하고 조직의 표준을 유지할 수 있습니다. | 플랫폼 엔지니어 | 
| 동적 파라미터 주입을 사용합니다. | 현재 템플릿은 사용자 지정 없이 기본 구성을 사용하고 Seed-Farmer CLI를 실행하여 기본 변수가 있는 리소스를 배포합니다. 모듈별 구성에 동적 파라미터 주입을 사용하여 기본 구성을 확장할 수 있습니다. | 플랫폼 엔지니어 | 
| 보안 및 규정 준수 개선 | AWS 리소스 생성 시 보안을 강화하기 위해 역할 기반 액세스 제어(RBAC)와 AWS Single Sign-On(SSO), SAML, OpenID Connect(OIDC) 및 정책을 코드 적용 수단으로 사용할 수 있습니다. | 플랫폼 엔지니어 | 
| 자동 리소스 정리 기능을 추가합니다. | 자동 정리 정책에 대한 기능을 활성화하고 인프라 드리프트 감지 및 문제 해결 기능을 추가할 수도 있습니다. | 플랫폼 엔지니어 | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Backstage 인프라 및 SageMaker AI 리소스를 제거합니다. | ML 환경 사용을 마치면 배포 가이드의 [정리 및 리소스 관리](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#cleanup-and-resource-management) 섹션에 있는 지침에 따라 Backstage 인프라를 제거하고 ML 환경에서 SageMaker AI 리소스를 삭제합니다. | 플랫폼 엔지니어 | 

## 문제 해결
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| AWS CDK 부트스트랩 실패 |  AWS 자격 증명 및 리전 구성을 확인합니다. | 
| Amazon EKS 클러스터 액세스 문제 | **kubectl** 구성 및 IAM 권한을 확인합니다. | 
| Application Load Balancer 연결 문제 | 보안 그룹에서 포트 80/443에 인바운드 트래픽을 허용하는지 확인합니다. | 
| GitHub 통합 문제 | GitHub 토큰 권한 및 조직 액세스를 확인합니다. | 
| SageMaker AI 배포 실패 | [AWS 서비스 할당량](https://docs.aws.amazon.com/general/latest/gr/sagemaker.html#limits_sagemaker) 및 IAM 권한을 확인합니다. | 

## 관련 리소스
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-resources"></a>
+ [플랫폼 엔지니어링](https://docs.aws.amazon.com/prescriptive-guidance/latest/aws-caf-platform-perspective/platform-eng.html)(*AWS Cloud Adoption Framework: 플랫폼 관점* 가이드)
+ [Amazon SageMaker AI 설명서](https://docs.aws.amazon.com/sagemaker/)
+ [Backstage 소프트웨어 템플릿](https://backstage.io/docs/features/software-templates/)(Backstage 웹 사이트)
+ [AIOps 모듈 리포지토리](https://github.com/awslabs/aiops-modules)(ML용 재사용 가능한 IaC 모듈 컬렉션)
+ [Backstage 리포지토리를 사용하는 AIOps 내부 개발자 플랫폼(IDP)](https://github.com/aws-samples/sample-aiops-idp-backstage/) 
+ [AWS의 현대적 엔지니어링](https://github.com/aws-samples/appmod-blueprints) 리포지토리
+ [Cloud Native Operational Excellence(CNOE) 웹 사이트](https://cnoe.io/)

## 추가 정보
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-additional"></a>

**비즈니스 과제**

MLOps 이니셔티브를 시작하거나 확장하는 조직은 다음과 같은 비즈니스 및 기술 문제에 직면하는 경우가 많습니다.
+ **일관되지 않은 환경**. 표준화된 개발 및 배포 환경이 부족하면 협업이 어렵고 배포에 따른 리스크가 증가합니다.
+ **수동 프로비저닝 오버헤드**. SageMaker Studio, Amazon Simple Storage Service(Amazon S3) 버킷, IAM 역할 및 CI/CD 파이프라인을 사용하여 ML 인프라를 수동으로 설정하려면 시간이 많이 걸리고 오류가 발생하기 쉬우며 데이터 과학자가 모델 개발의 핵심 작업에 집중하지 못하게 됩니다.
+ **검색 가능성 및 재사용 부족**. 중앙 집중식 카탈로그가 없기 때문에 기존 ML 모델, 데이터 세트, 파이프라인을 찾기가 어렵습니다. 이로 인해 중복 작업이 발생하고 재사용 기회를 놓치게 됩니다.
+ **복잡한 거버넌스 및 규정 준수**. ML 프로젝트가 조직의 보안 정책, 데이터 개인 정보 보호 규정, Health Insurance Portability and Accountability Act(HIPAA), General Data Protection Regulation(GDPR) 등의 규정 준수 표준을 준수하도록 하는 것은 자동화된 가드레일 없이는 어려울 수 있습니다.
+ **느린 가치 실현**. 이러한 문제가 누적되면 ML 프로젝트 수명 주기가 연장되고 ML 투자에 따른 비즈니스 가치 실현이 지연됩니다.
+ **보안 리스크**. 구성 및 수동 프로세스가 일관되지 않으면 보안 취약성이 발생하여 최소 권한 및 네트워크 격리를 적용하기 어려울 수 있습니다.

이러한 문제는 개발 주기를 지연시키고 운영 오버헤드를 높이며 보안 리스크를 초래합니다. ML의 반복적인 특성상 반복 가능한 워크플로와 효율적인 협업이 필요합니다.

2026년까지 소프트웨어 엔지니어링 조직의 80%가 플랫폼 팀을 갖출 것으로 예상됩니다. (Gartner 웹 사이트에서 [Platform Engineering Empowers Developers to be Better, Faster, Happier](https://www.gartner.com/en/experts/top-tech-trends-unpacked-series/platform-engineering-empowers-developers) 참조) 이러한 예측은 IDP가 소프트웨어 제공을 어떻게 가속화하는지 단적으로 보여줍니다. IDP로서 백스테이지는 복잡한 인프라로 순서를 복원하는 데 도움이 되므로 팀이 고품질 코드를 빠르고 안전하게 제공할 수 있습니다. Backstage와 강화된 AIOps 모듈을 통합하면 사후 대응적 문제 해결 방식에서 사전 예방적 방식으로 전환할 수 있습니다.

**MLOps SageMaker 모듈**

이 패턴에 사용되는 GitHub 리포지토리의 [AIOps 모듈은](https://github.com/awslabs/aiops-modules) 재사용 가능하고 강화된 IaC를 AWS 통해에서 MLOps를 표준화하기 위한 중요한 기반을 제공합니다. 이 모듈은 복잡성을 줄이고 ML 환경 설정을 가속화하는 것을 목표로 SageMaker 프로젝트, 파이프라인 및 관련 네트워킹 및 스토리지 리소스를 프로비저닝하는 모범 사례를 캡슐화합니다. 이 템플릿을 다양한 MLOps 사용 사례에 사용하여 ML 워크플로에 대한 보다 통제되고 효율적인 접근 방식을 조성하는 일관되고 안전한 배포 패턴을 설정할 수 있습니다.

AIOps 모듈을 직접 사용하려면 플랫폼 팀이 이 IaC 템플릿을 배포하고 관리해야 하는 경우가 많으므로, 셀프 서비스 액세스를 원하는 데이터 과학자에게 문제가 될 수 있습니다. 사용 가능한 템플릿을 검색하고 이해하며, 필요한 파라미터를 구성하고, 배포를 트리거하려면 AWS 서비스 콘솔을 탐색하거나 IaC 도구와 직접 상호 작용해야 할 수 있습니다. 이렇게 하면 마찰이 발생하고, ML 작업에 집중하기를 선호하는 데이터 과학자의 인지 부하가 증가하고, 중앙 집중식의 사용자 친화적 인터페이스를 통해 이러한 템플릿을 관리하지 않을 경우 일관되지 않거나 조직 표준에서 벗어나 파라미터화될 수 있습니다. 이러한 강력한 AIOps 모듈을 Backstage와 같은 IDP와 통합하면 이러한 표준화된 MLOps 구성 요소를 사용하기 위한 간소화된 셀프 서비스 환경, 향상된 검색 가능성 및 강력한 거버넌스 제어를 제공하므로 이 같은 문제를 해결하는 데 도움이 됩니다.

**IDP로서의 Backstage**

내부 개발자 플랫폼(IDP)은 개발자가 애플리케이션을 빌드, 배포 및 관리하는 방법을 간소화하고 표준화하기 위해 플랫폼 팀이 구축하는 셀프 서비스 계층입니다. 인프라 복잡성을 추상화하고 개발자가 통합 인터페이스를 통해 도구, 환경, 서비스에 쉽게 액세스할 수 있도록 합니다.

IDP의 주요 목표는 다음을 통해 개발자 경험과 생산성을 개선하는 것입니다.
+ 서비스 생성 및 배포와 같은 작업에 셀프 서비스 활성화.
+ 표준 템플릿을 통해 일관성과 규정 준수 촉진.
+ 개발 수명 주기(CI/CD, 모니터링 및 문서화) 전반에 걸쳐 도구 통합.

Backstage는 Spotify에서 생성한 오픈 소스 개발자 포털이며 이제 Cloud Native Computing Foundation(CNCF)의 일부로 제공됩니다. 이를 통해 조직은 소프트웨어 구성 요소, 도구 및 설명서를 관리할 수 있는 확장 가능한 중앙 집중식 플랫폼을 제공하여 자체 IDP를 구축할 수 있습니다. Backstage에서 개발자는 다음을 수행할 수 있습니다.
+ 소프트웨어 카탈로그를 통해 모든 내부 서비스를 검색하고 관리합니다.
+ 스캐폴더 플러그인을 통해 사전 정의된 템플릿을 사용하여 새 프로젝트를 생성합니다.
+ 한곳에서 CI/CD 파이프라인, Kubernetes 대시보드, 모니터링 시스템과 같은 통합 도구에 액세스합니다.
+ TechDocs를 통해 일관된 마크다운 기반 설명서를 유지 관리합니다.

**FAQ**

**이 Backstage 템플릿을 사용하는 것과 SageMaker 콘솔을 통해 SageMaker Studio를 수동으로 배포하는 것에는 어떤 차이가 있나요?**

백스테이지 템플릿은 조직 모범 사례를 따르는 표준화된 구성, Seed-Farmer 및를 사용한 자동화된 IaC 배포 AWS CDK, 기본 제공 보안 정책 및 규정 준수 조치, GitHub를 통한 조직의 개발자 워크플로와의 통합 등 수동 AWS 콘솔 배포에 비해 여러 가지 이점을 제공합니다. 또한 템플릿은 버전 관리를 사용하여 재현 가능한 배포를 생성하므로 다양한 단계(개발, 스테이징, 프로덕션)에서 환경을 더 쉽게 복제하고 팀 간에 일관성을 유지할 수 있습니다. 또한 템플릿에는 자동 정리 기능이 포함되어 있으며 Backstage를 통해 조직의 자격 증명 관리 시스템과 통합됩니다. 콘솔을 통한 수동 배포에는 심층적인 AWS 전문 지식이 필요하며 버전 제어 또는 템플릿이 제공하는 것과 동일한 수준의 표준화 및 거버넌스를 제공하지 않습니다. 이러한 이유로 콘솔 배포는 프로덕션 ML 환경보다 일회성 실험에 더 적합합니다.

**Seed-Farmer란 무엇이며 이 솔루션에서 Seed-Farmer를 사용하는 이유는 무엇인가요?**

Seed-Farmer는를 사용하여 인프라 모듈을 관리하는 AWS 배포 오케스트레이션 도구입니다 AWS CDK. 이 패턴은 AI/ML 워크로드용으로 특별히 설계된 표준화된 재사용 가능한 인프라 구성 요소를 제공하고, 간의 복잡한 종속성을 AWS 서비스 자동으로 처리하고, 다양한 환경에 걸쳐 일관된 배포를 보장하기 때문에 Seed-Farmer를 사용합니다.

**이러한 템플릿을 사용하려면 AWS CLI 를 설치해야 하나요?**

아니요. 컴퓨터에 AWS CLI 를 설치할 필요가 없습니다. 템플릿은 클라우드의 GitHub Actions를 통해 완벽하게 실행됩니다. 백스테이지 인터페이스를 통해 AWS 자격 증명(액세스 키, 보안 키 및 세션 토큰)을 제공하면 GitHub Actions 환경에서 배포가 자동으로 수행됩니다.

**SageMaker Studio 환경을 배포하는 데 얼마나 걸리나요?**

일반적인 SageMaker Studio 배포를 완료하는 데 15\$125분이 걸립니다. 여기에는 AWS CDK 부트스트래핑(2\$13분), Seed-Farmer 도구 체인 설정(3\$15분), 리소스 생성(10\$115분)이 포함됩니다. 정확한 시간은 AWS 리전 및 네트워킹 설정의 복잡성에 따라 달라집니다.

**동일한 AWS 계정에 여러 SageMaker 환경을 배포할 수 있나요?**

예, 가능합니다. 각 배포는 템플릿에 제공한 구성 요소 이름을 기반으로 고유한 이름을 가진 리소스를 생성합니다. 그러나 할당 AWS 서비스 량에 유의하세요. 각 계정에는 리전당 제한된 수의 SageMaker 도메인이 있을 수 있으므로 여러 환경을 생성하기 전에 [할당량을 확인하세요](https://docs.aws.amazon.com/general/latest/gr/sagemaker.html#limits_sagemaker).

# Amazon Bedrock을 사용하여 AWS 인프라 작업 자동화
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock"></a>

*Ishwar Chauthaiwale 및 Anand Bukkapatnam Tirumala, Amazon Web Services*

## 요약
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-summary"></a>

클라우드 네이티브 솔루션에서 공통 인프라 운영을 자동화하는 것은 효율적이고 안전하며 비용 효율적인 환경을 유지하는 데 중요한 역할을 합니다. 작업을 수동으로 처리하는 것은 시간이 많이 걸리고 인적 오류가 발생하기 쉽습니다. 또한 다양한 수준의 AWS 전문 지식을 갖춘 팀원은 보안 프로토콜을 준수하면서 이러한 작업을 수행해야 합니다. 이 패턴은 Amazon Bedrock을 사용하여 자연어 처리(NLP)를 통해 일반적인 AWS 인프라 작업을 자동화하는 방법을 보여줍니다.

이 패턴은 조직이 여러 환경에 생성형 AI 기반 인프라를 배포하기 위한 재사용 가능한 모듈식 보안 코드를 개발하는 데 도움이 될 수 있습니다. 코드형 인프라(IaC) 및 자동화에 중점을 둠으로써 버전 관리, 일관된 배포, 오류 감소, 더 빠른 프로비저닝, 향상된 협업 등 DevOps의 주요 이점을 제공합니다.

이 패턴은 팀이 다음을 AWS 서비스 포함하여 키와 관련된 작업을 관리할 수 있는 보안 아키텍처를 구현합니다.
+ Amazon Simple Storage Service(Amazon S3) 버킷 버전 관리
+ Amazon Relational Database Service(Amazon RDS) 스냅샷 생성
+ Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스 관리

아키텍처는 보안 통신을 위해 Amazon Virtual Private Cloud(Amazon VPC) 엔드포인트와 프라이빗 네트워킹을 사용하며, 프라이빗 서브넷 내에서 작업 실행기로 작동하는 AWS Lambda 함수를 사용합니다. Amazon S3는 데이터 관리를 제공하고 포괄적인 AWS Identity and Access Management (IAM) 역할 및 권한을 구현하여 적절한 액세스 제어를 보장합니다. 이 솔루션에는 채팅 기록 기능이 포함되어 있지 않으며 채팅이 저장되지 않습니다.

## 사전 조건 및 제한 사항
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-prereqs"></a>
+ 활성. AWS 계정
+ 액세스를 보호하고 제어하는 데 도움이 되는 적절한 액세스 제어 조치가 마련되어 있어야 합니다. 액세스 제어의 예로는 사용 AWS Systems Manager, 파운데이션 모델 액세스, 배포를 위한 IAM 역할 및 서비스 기반 역할, Amazon S3 버킷에 대한 퍼블릭 액세스 비활성화, 배달 못한 편지 대기열 설정이 있습니다.
+  AWS Key Management Service (AWS KMS) [고객 관리형 키](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#customer-cmk)입니다.
+ AWS Command Line Interface (AWS CLI) 버전 2 이상, 배포 환경에 [설치](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) 및 [구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)됨.
+ Terraform AWS Provider 버전 4 이상이 [설치](https://registry.terraform.io/providers/-/aws/latest/docs/guides/version-4-upgrade) 및 구성되었습니다.
+ Terraform 버전 1.5.7 이상 [설치](https://developer.hashicorp.com/terraform/install) 및 구성.
+ [Amazon Bedrock에서 에이전트의 작업 그룹에 대한 OpenAPI 스키마를 검토하고 정의하여 무단 액세스로부터 보호하고 데이터 무결성을 유지할 수 있습니다](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-api-schema.html).
+ 필요한 Amazon Titan Text Embeddings v2 및 Claude 3.5 Sonnet 또는 Claude 3 Haiku 파운데이션 모델에 AWS 계정 대해에서 [액세스가 활성화](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html)되었습니다. [https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html) 배포 실패를 방지하려면 대상 배포가 AWS 리전 [필요한 모델을 지원하는지](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) 확인합니다.
+ [AWS Well Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/framework/sec-design.html) 모범 사례를 따르는 구성된 Virtual Private Cloud(VPC)입니다.
+ [Amazon Responsible AI 정책에](https://aws.amazon.com/ai/responsible-ai/policy/) 대한 검토를 완료했습니다.

**제품 버전**
+ Amazon Titan Text Embeddings v2
+ Anthropic Claude 3.5 Sonnet 또는 Claude 3 Haiku
+ Terraform AWS Provider 버전 4 이상
+ Terraform 버전 1.5.7 이상

## 아키텍처
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-architecture"></a>

다음 다이어그램은 이 패턴의 워크플로 및 구성 요소를 보여 줍니다.

![\[Amazon Bedrock을 사용하여 일반적인 AWS 인프라 작업을 자동화하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/924e503f-bfc5-4452-abdf-d72a58d4d36f/images/bd56ad29-b435-4543-8ee8-dc4e1d38df18.png)


솔루션 아키텍처는 자연어 요청을 처리하고 해당 AWS 작업을 실행하기 위해 함께 작동하는 여러 계층으로 구성됩니다.

1. 사용자는 Amazon Bedrock 채팅 콘솔을 통해 작업을 요청합니다.

1. 챗봇은 요청 처리를 위해 Amazon Bedrock 지식 기반을 사용합니다. 자연어 처리를 위해 Amazon Titan Text Embeddings v2 모델을 구현합니다.

1. 사용자 프롬프트에 작업 요청이 포함된 경우 Amazon Bedrock 작업 그룹은 실행 로직에 Anthropic Claude 3 Haiku 또는 Claude 3.5 Sonnet 모델(선택에 따라 다름)을 사용하고 OpenAPI 스키마를 통해 작업을 정의합니다.

1. 작업 그룹은 보안 서비스 통신을 AWS PrivateLink 위해를 사용하여 Amazon VPC [엔드포인트](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html)에 도달합니다.

1.  AWS Lambda 함수는 Amazon Bedrock 서비스의 Amazon VPC 엔드포인트를 통해 연결됩니다.

1. Lambda 함수는 기본 실행 엔진입니다. 요청에 따라 Lambda 함수는 API를 직접적으로 호출하여 AWS 서비스에서 작업을 수행합니다. Lambda 함수는 작업 라우팅 및 실행도 처리합니다.

1. Lambda 함수에서 API 요청 AWS 서비스 가져오기 및 해당 작업이 수행됩니다.

1. Lambda 함수는 Amazon Bedrock이 이해하는 출력 페이로드를 계산합니다.

1. 이 페이로드는 보안 서비스 통신을 위해 PrivateLink를 사용하여 Amazon Bedrock으로 전송됩니다. Amazon Bedrock에서 사용하는 대규모 언어 모델(LLM)은이 페이로드를 이해하고 이를 사람이 이해할 수 있는 형식으로 변환합니다.

1. 그러면 Amazon Bedrock 채팅 콘솔에서 사용자에게 출력이 표시됩니다.

솔루션은 다음과 같은 기본 작업을 활성화합니다.
+ Amazon S3 - 버전 관리를 위해 버킷 버전 관리를 활성화합니다.
+ Amazon RDS - 백업을 위한 데이터베이스 스냅샷을 생성합니다.
+ Amazon EC2 - 인스턴스를 나열하고 인스턴스의 시작 및 중지를 제어합니다.

## 도구
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-tools"></a>

**AWS 서비스**
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)은 선도적인 AI 스타트업과 Amazon의 고성능 파운데이션 모델(FM)을 통합 API를 통해 사용할 수 있게 해주는 완전 관리형 서비스입니다.
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 셸의 명령을 AWS 서비스 통해와 상호 작용하는 데 도움이 되는 오픈 소스 도구입니다.
+ [Amazon Elastic Compute Cloud(Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)는 AWS 클라우드에서 확장 가능한 컴퓨팅 용량을 제공합니다. 필요한 만큼 가상 서버를 시작하고 빠르게 스케일 업하거나 스케일 다운할 수 있습니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-overview.html)는 Amazon OpenSearch Service를 위한 온디맨드 서버리스 구성입니다.
+ [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html)는 Virtual Private Cloud(VPC)에서 VPC 외부 서비스로의 단방향 프라이빗 연결을 생성하는 데 도움이 됩니다.
+ [Amazon Relational Database Service(RDS)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html)는 AWS 클라우드에서 관계형 데이터베이스를 설정, 운영 및 조정하는 데 도움이 됩니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html)은 AWS 클라우드에서 실행되는 애플리케이션 및 인프라를 관리하는 데 도움을 줍니다. 애플리케이션 및 리소스 관리를 간소화하고, 운영 문제를 감지 및 해결하는 시간을 단축하며, AWS 리소스를 대규모로 안전하게 관리하는 데 도움이 됩니다.
+ [Amazon Virtual Private Cloud(Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)를 사용하면 정의한 가상 네트워크에서 AWS 리소스를 시작할 수 있습니다. 이 가상 네트워크는 AWS의 확장 가능한 인프라를 사용한다는 이점과 함께 고객의 자체 데이터 센터에서 운영하는 기존 네트워크와 유사합니다.

**기타 도구**
+ [Git](https://git-scm.com/docs)은 오픈 소스 분산 버전 제어 시스템입니다.
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [aws-samples/infra-ops-orchestrator](https://github.com/aws-samples/infra-ops-orchestrator) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-best-practices"></a>
+ Lambda 실행 로그를 정기적으로 모니터링합니다. 자세한 내용은 [Lambda 함수 모니터링 및 문제 해결](https://docs.aws.amazon.com/lambda/latest/dg/lambda-monitoring.html)을 참조하십시오. 모범 사례에 대한 자세한 내용은 [AWS Lambda 함수 작업 모범 사례를 참조하세요](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html).
+ 보안 구성을 주기적으로 검토하여 조직의 요구 사항을 준수하는지 확인합니다. 자세한 내용은 [보안 모범 사례](https://docs.aws.amazon.com/wellarchitected/latest/framework/sec-bp.html)를 참조하세요.
+ 최소 권한 원칙을 따르고 작업을 수행하는 데 필요한 최소 권한을 부여하세요. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv) 및 [보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)를 참조하세요.

## 에픽
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-epics"></a>

### 솔루션 배포
<a name="deploy-the-solution"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리포지토리를 복제합니다. | 리포지토리를 로컬 시스템에 복제하려면 다음 명령을 실행하세요.<pre>git clone "git@github.com:aws-samples/infra-ops-orchestrator.git"<br />cd infra-ops-orchestrator</pre> | AWS DevOps, DevOps 엔지니어 | 
| 환경 변수를 편집합니다. | 복제된 리포지토리의 루트 디렉터리에서 `terraform.tfvars` 파일을 편집합니다. 로 표시된 자리 표시자를 검토하고 환경에 따라 `[XXXXX]`업데이트합니다. | AWS DevOps, DevOps 엔지니어 | 
| 인프라를 생성합니다. | 인프라를 생성하려면 다음 명령을 실행합니다.<pre>terraform init</pre><pre>terraform plan</pre>실행 계획을 주의 깊게 검토합니다. 계획된 변경 사항이 허용 가능한 경우 다음 명령을 실행합니다.<pre>terraform apply --auto-approve</pre> | AWS DevOps, DevOps 엔지니어 | 

### 솔루션에 액세스
<a name="access-the-solution"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 솔루션에 액세스합니다. | 배포에 성공한 후 다음 단계에 따라 채팅 기반 인터페이스를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-infrastructure-operations-by-using-amazon-bedrock.html) | AWS DevOps, DevOps 엔지니어 | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 생성된 리소스를 삭제합니다. | 이 패턴으로 생성된 모든 인프라를 삭제하려면 다음 명령을 실행합니다.<pre>terraform plan -destroy </pre>폐기 계획을 주의 깊게 검토합니다. 계획된 삭제가 허용 가능한 경우 다음 명령을 실행합니다.<pre>terraform destroy</pre>참고:이 명령은이 패턴으로 생성된 모든 리소스를 영구적으로 삭제합니다. 명령을 실행하면 리소스를 제거하기 전에 확인 메시지가 표시됩니다. | AWS DevOps, DevOps 엔지니어 | 

## 문제 해결
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 에이전트 동작  | 이 문제에 대한 자세한 내용은 Amazon Bedrock 설명서의 [에이전트 동작 테스트 및 문제 해결](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-networking.html)을 참조하세요. | 
| Lambda 네트워크 문제 | 이러한 문제에 대한 자세한 내용은 [Lambda 설명서의 Lambda의 네트워킹 문제 해결을](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-networking.html) 참조하세요. | 
| IAM 권한 | 이러한 문제에 대한 자세한 내용은 [IAM 설명서의 IAM 문제 해결](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot.html)을 참조하세요. | 

## 관련 리소스
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-resources"></a>
+ [Amazon RDS용 단일 AZ DB 인스턴스의 DB 스냅샷 생성](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateSnapshot.html)
+ [Amazon Bedrock에서 에이전트의 작업 그룹에 대한 OpenAPI 스키마 정의](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-api-schema.html)
+ [버킷에서 버전 관리 활성화](https://docs.aws.amazon.com/AmazonS3/latest/userguide/manage-versioning-examples.html)
+ [Amazon Bedrock Agents 작동 방식](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-how.html)
+ [Amazon Bedrock 지식 기반을 사용하여 데이터 검색 및 AI 응답 생성](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/aws-privatelink.html)
+ [를 통해 서비스에 안전하게 액세스 AWS PrivateLink](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/aws-privatelink.html)
+ [Amazon EC2 인스턴스 중지 및 시작](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html)
+ [작업 그룹을 사용하여 에이전트가 수행할 작업 정의](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-create.html)

# Terraform을 사용하여 로드 밸런서 엔드포인트 변경 시 CloudFront 업데이트 자동화
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change"></a>

*Tamilselvan P, Mohan Annam, Naveen Suthar, Amazon Web Services*

## 요약
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-summary"></a>

Amazon Elastic Kubernetes Service(Amazon EKS) 사용자가 Helm 차트를 통해 수신 구성을 삭제하고 다시 설치하면 새 Application Load Balancer(ALB)가 생성됩니다. 이렇게 하면 Amazon CloudFront가 이전 ALB의 DNS 레코드를 계속 참조하기 때문에 문제가 발생합니다. 따라서이 엔드포인트로 향하는 서비스에 연결할 수 없습니다. (이 문제가 있는 워크플로에 대한 자세한 내용은 [추가 정보](#automate-cloudfront-updates-when-load-balancer-endpoints-change-additional)를 참조하세요.)

이 문제를 해결하기 위해이 패턴은 Python으로 개발된 사용자 지정 AWS Lambda 함수를 사용하는 방법을 설명합니다. 이 Lambda 함수는 Amazon EventBridge 규칙을 통해 새 ALB가 생성되는 시기를 자동으로 감지합니다. 그런 다음 함수 AWS SDK for Python (Boto3)는를 사용하여 CloudFront 구성을 새 ALB의 DNS 주소로 업데이트하여 트래픽이 올바른 엔드포인트로 라우팅되도록 합니다.

이 자동화된 솔루션은 추가 라우팅 또는 지연 시간 없이 서비스 연속성을 유지합니다. 이 프로세스는 기본 인프라가 변경되더라도 CloudFront가 항상 올바른 ALB DNS 엔드포인트를 참조하도록 하는 데 도움이 됩니다.

## 사전 조건 및 제한 사항
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ Helm을 사용하여 Amazon EKS에 배포되는 테스트 및 검증용 샘플 웹 애플리케이션입니다. 자세한 내용은 [Amazon EKS 설명서의 Amazon EKS에서 Helm을 사용하여 애플리케이션 배포](https://docs.aws.amazon.com/eks/latest/userguide/helm.html)를 참조하세요.
+ Helm [수신 컨트롤러](https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/)에 의해 생성된 ALB로 호출을 라우팅하도록 CloudFront를 구성합니다. 자세한 내용은 Amazon EKS 설명서의 [Install AWS Load Balancer Controller with Helm](https://docs.aws.amazon.com/eks/latest/userguide/lbc-helm.html) 및 CloudFront 설명서의 [Application Load Balancer에 대한 액세스 제한을](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/restrict-access-to-load-balancer.html) 참조하세요.
+ 로컬 워크스페이스에 Terraform이 [설치](https://developer.hashicorp.com/terraform/install?product_intent=terraform) 및 구성되어 있습니다.

**제한 사항 **
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

**제품 버전**
+ Terraform 버전 1.0.0 이상
+ Terraform [AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) 버전 4.20 이상

## 아키텍처
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-architecture"></a>

다음 다이어그램은 이 패턴의 워크플로 및 구성 요소를 보여 줍니다.

![\[EventBridge 규칙을 통해 감지된 새 ALB DNS 주소로 CloudFront를 업데이트하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/03c30b18-4dd7-4dd4-b960-5a5cc58cec63/images/28854767-0902-4398-80af-b19141dd94e4.png)


이 솔루션은 다음 단계를 수행합니다.

1. Amazon EKS 수신 컨트롤러는 Helm 재시작 또는 배포가 있을 때마다 새 Application Load Balancer(ALB)를 생성합니다.

1. EventBridge는 ALB 생성 이벤트를 찾습니다.

1. ALB 생성 이벤트는 Lambda 함수를 트리거합니다.

1. Lambda 함수는 python 3.9를 기반으로 배포되었으며 boto3 API를 사용하여를 호출합니다 AWS 서비스. Lambda 함수는 로드 밸런서 생성 이벤트에서 수신되는 최신 로드 밸런서 DNS 이름으로 CloudFront 항목을 업데이트합니다.

## 도구
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-tools"></a>

**AWS 서비스**
+ [Amazon CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html)는 전 세계 데이터 센터 네트워크를 통해 웹 콘텐츠를 전송함으로써 웹 콘텐츠 배포 속도를 높여 지연 시간을 줄이고 성능을 개선합니다.
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)를 사용하면 자체 Kubernetes 컨트롤 플레인 또는 노드를 설치하거나 유지 관리할 필요 AWS 없이에서 Kubernetes를 실행할 수 있습니다.
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)는 애플리케이션을 다양한 소스의 실시간 데이터와 연결할 수 있는 서버리스 이벤트 버스 서비스입니다. 예를 들어 AWS Lambda 함수, API 대상을 사용하는 HTTP 호출 엔드포인트 또는 다른의 이벤트 버스 등이 있습니다 AWS 계정.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [AWS SDK for Python (Boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)는 Python 애플리케이션, 라이브러리 또는 스크립트를와 통합하는 데 도움이 되는 소프트웨어 개발 키트입니다 AWS 서비스.

**기타 도구**
+ [Python](https://www.python.org/)은 범용 컴퓨터 프로그래밍 언어입니다.
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [aws-cloudfront-automation-terraform-samples](https://github.com/aws-samples/aws-cloudfront-automation-terraform-samples) 리포지토리에서 사용할 수 있습니다.

## 에픽
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-epics"></a>

### 로컬 워크스테이션 설정
<a name="set-up-local-workstation"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Git CLI를 설정 및 구성합니다. | 로컬 워크스테이션에 Git 명령줄 인터페이스(CLI)를 설치하고 구성하려면 Git 설명서의 [시작하기 - Git 설치](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 지침을 따릅니다. | DevOps 엔지니어 | 
| 프로젝트 폴더를 생성하고 파일을 추가합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 엔지니어 | 

### Terraform을 사용하여 대상 아키텍처 프로비저닝
<a name="provision-the-target-architecture-using-the-terraform-configuration"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 솔루션을 배포합니다. | 대상에 리소스를 배포하려면 다음 단계를 AWS 계정사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 엔지니어 | 

### 배포 확인
<a name="verify-the-deployment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포를 검증합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 엔지니어 | 

### 인프라 정리
<a name="clean-up-infrastructure"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 인프라를 정리합니다. | 이전에 생성한 인프라를 정리하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 엔지니어 | 

## 문제 해결
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 공급자 보안 인증을 검증하는 중 오류가 발생했습니다. | 로컬 시스템에서 Terraform `apply` 또는 `destroy` 명령을 실행할 때 다음과 유사한 오류가 발생할 수 있습니다.<pre>Error: configuring Terraform AWS Provider: error validating provider <br />credentials: error calling sts:GetCallerIdentity: operation error STS: <br />GetCallerIdentity, https response error StatusCode: 403, RequestID: <br />123456a9-fbc1-40ed-b8d8-513d0133ba7f, api error InvalidClientTokenId: <br />The security token included in the request is invalid.</pre>이 오류는 로컬 시스템 구성에 사용된 보안 인증 정보의 보안 토큰이 만료되어 발생합니다.오류를 해결하려면 AWS Command Line Interface (AWS CLI) 설명서의 [구성 설정 및 보기를](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-methods) 참조하세요. | 

## 관련 리소스
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-resources"></a>

**AWS resources**
+ [Application Load Balancer에 대한 액세스 제한](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/restrict-access-to-load-balancer.html)
+ [AWS Load Balancer 컨트롤러를 사용하여 인터넷 트래픽 라우팅](https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html)

**Terraform 설명서**
+ [AWS 공급자](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
+ [Terraform 설치](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)
+ [원격 상태](https://developer.hashicorp.com/terraform/language/state/remote)

## 추가 정보
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-additional"></a>

**문제가 있는 워크플로**

![\[CloudFront에서 out-of-date ALB DNS 항목을 생성하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/03c30b18-4dd7-4dd4-b960-5a5cc58cec63/images/bb3c2c93-c749-435d-9b1d-2bbf6f0cf085.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 사용자가 애플리케이션에 액세스하면 호출은 CloudFront로 이동합니다.

1. CloudFront는 호출을 해당 Application Load Balancer(ALB)로 라우팅합니다.

1. ALB에는 애플리케이션 포드의 IP 주소인 대상 IP 주소가 포함됩니다. 여기에서 ALB는 사용자에게 예상 결과를 제공합니다.

그러나이 워크플로는 문제를 보여줍니다. 애플리케이션 배포는 차트 Helm을 통해 이루어집니다. 배포가 있거나 누군가 Helm을 다시 시작할 때마다 해당 수신도 다시 생성됩니다. 따라서 외부 로드 밸런서 컨트롤러가 ALB를 다시 생성합니다. 또한 각 재생성 중에 ALB가 다른 DNS 이름으로 다시 생성됩니다. 따라서 CloudFront는 오리진 설정에 기한 경과 항목이 있습니다. 이 기한 경과 항목으로 인해 사용자가 애플리케이션에 연결할 수 없습니다. 이 문제로 인해 사용자의 가동 중지가 발생합니다.

**대체 솔루션**

또 다른 가능한 해결 방법은 ALB에 대한 [외부 DNS](https://github.com/kubernetes-sigs/external-dns)를 생성한 다음 CloudFront의 Amazon Route 53 프라이빗 호스팅 영역 엔드포인트를 가리키는 것입니다. 그러나이 접근 방식은 애플리케이션 흐름에 또 다른 홉을 추가하여 애플리케이션 지연 시간을 유발할 수 있습니다. 이 패턴의 Lambda 함수 솔루션은 현재 흐름을 방해하지 않습니다.

# GitHub Actions를 사용하여 AWS CDK Python 애플리케이션에 대한 Amazon CodeGuru 리뷰 자동화
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications"></a>

*Vanitha Dontireddy와 Sarat Chandra Pothula, Amazon Web Services*

## 요약
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-summary"></a>

참고: 2025년 11월 7일부터 Amazon CodeGuru Reviewer에서 새 리포지토리 연결을 생성할 수 없습니다. CodeGuru Reviewer와 유사한 기능을 갖춘 서비스에 대한 자세한 내용은 [ CodeGuru Reviewer 설명서의 Amazon CodeGuru Reviewer 가용성 변경을](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/codeguru-reviewer-availability-change.html) 참조하세요. CodeGuru 

이 패턴은 GitHub Actions를 통해 오케스트레이션된 AWS Cloud Development Kit (AWS CDK) Python 애플리케이션에 대한 Amazon CodeGuru 자동 코드 검토의 통합을 보여줍니다. 이 솔루션은 AWS CDK Python에 정의된 서버리스 아키텍처를 배포합니다. 이 접근 방식은 개발 파이프라인 내에서 전문가 코드 분석을 자동화하여 AWS CDK Python 프로젝트에 대해 다음을 수행할 수 있습니다.
+ 코드 품질을 개선합니다.
+ 워크플로를 간소화합니다.
+ 서버리스 컴퓨팅의 이점을 극대화합니다.

## 사전 조건 및 제한 사항
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ AWS Command Line Interface (AWS CLI) 버전 2.9.11 이상, [설치](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) 및 [구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)됨.
+ 활성 GitHub 계정 및 읽기 및 쓰기 워크플로 권한이 있고 GitHub Actions에서 풀 요청(PR)을 생성하여 PR 워크플로가 올바르게 작동하는지 확인하는 GitHub 리포지토리입니다.
+ 에 솔루션을 배포하기 위한 GitHub Actions의 OpenID Connect(OIDC) 역할입니다 AWS 계정. IAM 콘솔을 생성하려면 [AWS CDK 구문](https://github.com/aws-samples/github-actions-oidc-cdk-construct)을 사용합니다.

**제한 사항 **
+ Amazon CodeGuru Profiler는 모든 Java 가상 머신(JVM) 언어(예: Scala 및 Kotlin), 런타임 및 Python 3.6 이상으로 작성된 [애플리케이션을 지원합니다](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/what-is-codeguru-profiler.html#what-is-language-support).
+ Amazon CodeGuru Reviewer는 Bitbucket AWS CodeCommit, GitHub, GitHub Enterprise Cloud 및 GitHub Enterprise Server 소스 공급자의 Java 및 GitHub 코드 리포지토리와의 [연결만 지원합니다](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/working-with-repositories.html). 또한 Amazon Simple Storage Service(Amazon S3) 리포지토리는 GitHub Actions를 통해서만 지원됩니다.
+ 지속적 통합 및 지속적 배포(CI/CD) 파이프라인 중에 결과를 인쇄하는 자동화된 방법은 없습니다. 대신이 패턴은 GitHub Actions를 대체 방법으로 사용하여 결과를 처리하고 표시합니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별 AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-architecture"></a>

다음 다이어그램은 이 솔루션의 아키텍처를 보여 줍니다.

![\[GitHub Actions를 사용하여 AWS CDK Python 애플리케이션에 대한 CodeGuru 코드 검토를 통합하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/c5395e3e-ff2a-41cf-bd64-c73cc928b60b/images/18f880a2-9bc3-4d71-a598-bb83b68ee383.png)


다이어그램에 표시된 대로 개발자가 검토를 위해 풀 요청(PR)을 생성하면 GitHub Actions는 다음 단계를 트리거합니다.

1. IAM 역할 가정 - 파이프라인은 GitHub 시크릿에 지정된 IAM 역할을 사용하여 배포 작업을 수행합니다.

1. 코드 분석
   + CodeGuru Reviewer는 Amazon S3 버킷에 저장된 코드를 분석합니다. 결함을 식별하고 수정 및 최적화에 대한 권장 사항을 제공합니다.
   + CodeGuru Security는 정책 위반 및 취약성을 검사합니다.

1. 조사 결과 검토
   + 파이프라인은 콘솔 출력에서 결과 대시보드에 대한 링크를 인쇄합니다.
   + 중요한 결과가 감지되면 파이프라인이 즉시 실패합니다.
   + 심각도가 높거나 정상이거나 낮은 결과의 경우 파이프라인은 다음 단계로 계속됩니다.

1. PR 승인
   + 검토자는 PR을 수동으로 승인해야 합니다.
   + PR이 거부되면 파이프라인이 실패하고 추가 배포 단계를 중지합니다.

1. CDK 배포 - PR 승인 시 CDK 배포 프로세스가 시작됩니다. 다음 AWS 서비스 및 리소스를 설정합니다.
   + CodeGuru Profiler
   + AWS Lambda 함수
   + Amazon Simple Queue Service(Amazon SQS) 대기열

1. 프로파일링 데이터 생성 - CodeGuru Profiler에 대한 충분한 프로파일링 데이터를 생성하려면:
   + 파이프라인은 Amazon SQS 대기열로 메시지를 주기적으로 전송하여 Lambda 함수를 여러 번 간접적으로 호출합니다.

## 도구
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-tools"></a>

**AWS 서비스**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)는 코드로 AWS 클라우드 인프라를 정의하고 프로비저닝하는 데 도움이 되는 소프트웨어 개발 프레임워크입니다.
+ [CDK Toolkit](https://docs.aws.amazon.com/cdk/latest/guide/cli.html)은 AWS CDK 앱과 상호 작용하는 데 도움이 되는 명령줄 클라우드 개발 키트입니다.
+ [Amazon CodeGuru Profiler](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/what-is-codeguru-profiler.html)는 라이브 애플리케이션에서 런타임 성능 데이터를 수집하고 애플리케이션 성능을 미세 조정하는 데 도움이 되는 권장 사항을 제공합니다.
+ [Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/welcome.html)는 프로그램 분석 및 기계 학습을 사용하여 개발자가 찾기 어려운 잠재적 결함을 감지합니다. 그런 다음 CodeGuru Profiler는 Java 및 Python 코드 개선을 위한 제안을 제공합니다.
+ Amazon CodeGuru Security는 기계 학습을 사용하여 보안 정책 위반 및 취약성을 탐지하는 정적 애플리케이션 보안 도구입니다. 보안 리스크를 해결하기 위한 제안을 제공하고 애플리케이션의 보안 태세를 추적할 수 있도록 지표를 생성합니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [Amazon Simple Queue Service(Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html)는 내구력 있고 가용성이 뛰어난 보안 호스팅 대기열을 제공하며 이를 통해 분산 소프트웨어 시스템과 구성 요소를 통합 및 분리할 수 있습니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.

**기타 도구**
+ [GitHub Actions](https://docs.github.com/en/actions/writing-workflows/quickstart)는 GitHub 리포지토리와 긴밀하게 통합된 지속적 통합 및 지속적 전달(CI/CD) 플랫폼입니다. GitHub Actions를 사용하여 빌드, 테스트 및 배포 파이프라인을 자동화할 수 있습니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [amazon-codeguru-suite-cdk-python](https://github.com/aws-samples/amazon-codeguru-suite-cdk-python) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-best-practices"></a>
+ [AWS CDK를 사용하여 클라우드 인프라를 개발하고 배포하기 위한 모범 사례](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html)를 따릅니다.
+ GitHub Actions 워크플로[에서를 사용할 때는 다음을 포함하여 IAM의 보안 모범 사례를](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) 따르세요. AWS 서비스 
  + 리포지토리 코드에 자격 증명을 저장하지 마세요.
  + [IAM 역할을 수임](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-workloads-use-roles)하여 임시 자격 증명을 받고 가능하면 임시 자격 증명을 사용합니다.
  + GitHub Actions 워크플로에 사용되는 IAM 역할에 [최소 권한을 부여합니다](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). GitHub Actions 워크플로에서 작업을 수행하는 데 필요한 권한만 부여합니다.
  + GitHub Actions 워크플로에 사용되는 IAM 역할의 [활동을 모니터링합니다](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#remove-credentials).
  + 사용하는 장기 자격 증명을 주기적으로 교체합니다.

## 에픽
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-epics"></a>

### 환경을 설정합니다
<a name="set-up-your-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  AWS 자격 증명을 설정합니다. | 스택을 배포하는 AWS 계정 및 AWS 리전 를 정의하는 변수를 내보내려면 다음 명령을 실행합니다.<pre>export CDK_DEFAULT_ACCOUNT=<12-digit AWS account number></pre><pre>export CDK_DEFAULT_REGION=<AWS Region></pre>의 AWS 자격 증명은 환경 변수를 통해 AWS CDK 제공됩니다. | AWS DevOps, DevOps 엔지니어 | 
| 리포지토리를 복제합니다. | 리포지토리를 로컬 시스템에 복제하려면 다음 명령을 실행하세요.<pre>git clone https://github.com/aws-samples/amazon-codeguru-suite-cdk-python.git</pre> | AWS DevOps, DevOps 엔지니어 | 
| CDK 툴킷을 설치합니다. | CDK Toolkit이 설치되었는지 확인하고 버전을 확인하려면 다음 명령을 실행합니다. <pre>cdk --version</pre>CDK 툴킷 버전이 2.27.0 이전인 경우 다음 명령을 입력하여 버전 2.27.0으로 업데이트합니다.<pre>npm install -g aws-cdk@2.27.0</pre>CDK 툴킷이 설치되지 *않은* 경우에는 다음 명령을 실행하여 설치합니다.<pre>npm install -g aws-cdk@2.27.0 --force</pre> | AWS DevOps, DevOps 엔지니어 | 
| 필요한 종속 항목을 설치합니다. | 필요한 프로젝트 종속성을 설치하려면 다음 명령을 실행합니다.<pre>python -m pip install --upgrade pip<br />pip install -r requirements.txt</pre> | AWS DevOps, DevOps 엔지니어 | 
| CDK 환경을 부트스트랩합니다. | AWS CDK 환경을 [부트스트랩](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)하려면 다음 명령을 실행합니다.<pre>npm install<br />npm run cdk bootstrap "aws://${ACCOUNT_NUMBER}/${AWS_REGION}"</pre>환경을 성공적으로 부트스트랩한 후에는 다음 출력이 표시되어야 합니다.<pre>⏳  Bootstrapping environment aws://{account}/{region}...<br />✅  Environment aws://{account}/{region} bootstrapped</pre> | AWS DevOps, DevOps 엔지니어 | 

### CDK 앱 배포
<a name="deploy-the-cdk-app"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  AWS CDK 앱을 합성합니다. |  AWS CDK 앱을 합성하려면 다음 명령을 실행합니다.<pre>cdk synth</pre>이 명령에 대한 자세한 내용은 AWS CDK 설명서의 [cdk synthesize](https://docs.aws.amazon.com/cdk/v2/guide/ref-cli-cmd-synth.html)를 참조하세요. | AWS DevOps, DevOps 엔지니어 | 
| 리소스를 배포합니다. | 리소스를 배포하려면 다음 명령을 실행합니다.<pre>cdk deploy --require-approval never</pre>`--require-approval never` 플래그는 CDK가 모든 변경 사항을 자동으로 승인하고 실행함을 의미합니다. 여기에는 CDK가 일반적으로 수동 검토가 필요한 것으로 플래그를 지정하는 변경 사항(예: IAM 정책 변경 또는 리소스 제거)이 포함됩니다. 프로덕션 환경에서 `--require-approval never` 플래그를 사용하기 전에 CDK 코드 및 CI/CD 파이프라인이 잘 테스트되고 안전한지 확인합니다. | AWS DevOps, DevOps 엔지니어 | 

### GitHub 시크릿 및 개인용 액세스 토큰 생성
<a name="create-github-secrets-and-personal-access-token"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| GitHub에서 필요한 시크릿을 생성합니다. | GitHub Actions 워크플로가 리포지토리의 코드에 민감한 정보를 노출하지 않고 AWS 리소스에 안전하게 액세스할 수 있도록 하려면 보안 암호를 생성합니다. GitHub에서 `ROLE_TO_ASSUME`, `CodeGuruReviewArtifactBucketName` 및 `AWS_ACCOUNT_ID`에 대한 보안 암호를 생성하려면 GitHub 작업 설명서의 [리포지토리에 대한 보안 암호 생성](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository)의 지침을 따릅니다.다음은 이러한 변수에 대한 자세한 정보입니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.html) | AWS DevOps, DevOps 엔지니어 | 
| GitHub 개인용 액세스 토큰을 생성합니다. | GitHub Actions 워크플로가 GitHub를 인증하고 상호 작용할 수 있는 안전한 방법을 설정하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.html) | AWS DevOps, DevOps 엔지니어 | 

### 정리
<a name="clean-up"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리소스를 정리하십시오. |  AWS CDK Python 앱을 정리하려면 다음 명령을 실행합니다.<pre>cdk destroy --all</pre> | DevOps 엔지니어 | 

## 문제 해결
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 대시보드 조사 결과에 대한 링크를 표시합니다. | CI/CD 파이프라인 중에 조사 결과를 인쇄할 수 있는 방법은 없습니다. 대신이 패턴은 GitHub Actions를 대체 방법으로 사용하여 결과를 처리하고 표시합니다. | 

## 관련 리소스
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-resources"></a>

**AWS resources**
+ [AWS 클라우드 개발 키트](https://aws.amazon.com/cdk/)
+ [Amazon CodeGuru 설명서](https://docs.aws.amazon.com/codeguru/)
+ [Amazon S3](https://aws.amazon.com/s3/)
+ [AWS Identity and Access Management](https://aws.amazon.com/iam/)
+ [Amazon Simple Queue Service](https://aws.amazon.com/sqs/)
+ [란 무엇입니까 AWS Lambda?](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)

**GitHub 설명서**
+ [Amazon Web Services에서 OpenID Connect 구성](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)
+ [GitHub Actions](https://github.com/features/actions)
+ [워크플로 재사용](https://docs.github.com/en/actions/using-workflows/reusing-workflows)
+ [워크플로 트리거](https://docs.github.com/en/actions/using-workflows/triggering-a-workflow) 

# GitHub Actions, Artifactory 및 Terraform을 사용하여 다중 리포지토리 설정에서 AWS Supply Chain 데이터 레이크 배포 자동화
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes"></a>

*Keshav Ganesh, Amazon Web Services*

## 요약
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-summary"></a>

이 패턴은 다중 리포지토리 지속적 통합 및 지속적 배포(CI/CD) 파이프라인을 사용하여 AWS Supply Chain 데이터 레이크를 배포하고 관리하기 위한 자동화된 접근 방식을 제공합니다. GitHub Actions 워크플로를 사용한 자동 배포 또는 Terraform을 직접 사용한 수동 배포라는 두 가지 배포 방법을 보여줍니다. 두 접근 방식 모두 코드형 인프라(IaC)에 Terraform을 사용하며, 자동화된 메서드는 향상된 CI/CD 기능을 위해 GitHub Actions 및 JFrog Artifactory를 추가합니다.

솔루션은 AWS Supply Chain AWS Lambda및 Amazon Simple Storage Service(Amazon S3)를 활용하여 데이터 레이크 인프라를 설정하는 동시에 두 배포 방법 중 하나를 사용하여 구성 및 리소스 생성을 자동화합니다. 이 자동화는 수동 구성 단계를 제거하고 환경 간에 일관된 배포를 보장합니다. 또한 추출, 변환 및 로드(ETL)에 대한 심층적인 전문 지식의 필요성을 AWS Supply Chain 제거하고 Amazon Quick Sight로 구동되는 인사이트와 분석을 제공할 수 있습니다.

조직은이 패턴을 구현하여 배포 시간을 줄이고, 코드형 인프라를 유지하며, 버전 관리형 자동 프로세스를 통해 공급망 데이터 레이크를 관리할 수 있습니다. 다중 리포지토리 접근 방식은 세분화된 액세스 제어를 제공하고 다양한 구성 요소의 독립적인 배포를 지원합니다. 팀은 기존 도구 및 프로세스에 가장 적합한 배포 방법을 선택할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-prereqs"></a>

**사전 조건 **

로컬 시스템에 다음이 설치되어 있는지 확인합니다.
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 버전 2
+ [GitHub CLI](https://docs.github.com/en/get-started/git-basics/set-up-git)
+ [Python](https://www.python.org/downloads/) v3.13
+ [Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) v1.12 이상

배포하기 전에 다음 사항이 있는지 확인합니다.
+ 활성. AWS 계정
+ 선택한 AWS 계정 AWS 리전 의에 두 개의 [프라이빗 서브넷](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-example-private-subnets-nat.html)이 있는 [Virtual Private Cloud(VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html)입니다.
+ 다음 서비스에 배포하는 데 사용되는 AWS Identity and Access Management (IAM) 역할에 대한 충분한 권한:
  + AWS Supply Chain - 데이터 세트 및 통합 흐름과 같은 구성 요소를 배포하고에서 액세스하는 데 전체 액세스가 선호됩니다 AWS Management Console.
  + Amazon CloudWatch Logs - CloudWatch 로그 그룹을 생성하고 관리하는 데 사용됩니다.
  + Amazon Elastic Compute Cloud(Amazon EC2) - Amazon EC2 보안 그룹 및 Amazon Virtual Private Cloud(Amazon VPC) 엔드포인트용입니다.
  + Amazon EventBridge -에서 사용합니다 AWS Supply Chain.
  + IAM - AWS Lambda 서비스 역할을 생성하는 데 사용됩니다.
  + AWS Key Management Service (AWS KMS) - Amazon S3 아티팩트 버킷 및 Amazon S3 AWS Supply Chain 스테이징 버킷에 AWS KMS keys 사용되는에 대한 액세스입니다.
  + AWS Lambda - AWS Supply Chain 구성 요소를 배포하는 Lambda 함수를 생성하는 데 사용됩니다.
  + Amazon S3 - Amazon S3 아티팩트 버킷, 서버 액세스 로깅 버킷 및 AWS Supply Chain 스테이징 버킷에 액세스할 수 있습니다. 수동 배포를 사용하는 경우 Amazon S3 Terraform 아티팩트 버킷에 대한 권한도 필요합니다.
  + Amazon VPC - VPC를 생성하고 관리하는 데 사용됩니다.

배포에 GitHub Actions 워크플로를 사용하려면 다음을 수행합니다.
+ 앞서 언급한 권한을 사용하여 IAM 역할에 대한 [OpenID Connect(OIDC)](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws#configuring-the-role-and-trust-policy)를 설정합니다.
+ 에 액세스할 수 있는 유사한 권한을 가진 IAM 역할을 생성합니다 AWS Management Console. 자세한 내용은 [IAM 설명서의 IAM 사용자에게 권한을 부여하는 역할 생성을](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html) 참조하세요.

수동 배포를 원하는 경우 다음을 수행합니다.
+ IAM 사용자를 생성하여 앞서 언급한 권한으로 IAM 역할을 수임합니다. 자세한 내용은 [IAM 설명서의 IAM 사용자에게 권한을 부여하는 역할 생성을](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html) 참조하세요.
+ 로컬 터미널에서 [역할을 수임](https://docs.aws.amazon.com/cli/v1/userguide/cli-configure-role.html)합니다.

배포에 GitHub Actions 워크플로를 사용하려면 다음을 설정합니다.
+ 호스트 이름, 로그인 사용자 이름 및 로그인 액세스 토큰을 가져오는 [JFrog Artifactory 계정](https://jfrog.com/artifactory/?utm_source=google&utm_medium=cpc_search&utm_campaign=SearchDSKBrandAPACIN202506&utm_term=jfrog%20cloud&gads_network=g&utm_content=u-bin&gads_campaign_id=22674833884&gads_adgroup_id=184501797241&gads_extension_id=233003714635&gads_target_id=aud-312135645780:kwd-1598615735032&gads_matchtype=b&gad_source=1&gad_campaignid=22674833884&gbraid=0AAAAADqV85U5B37iapTR9IIFHBvydF5AQ&gclid=CjwKCAjwiY_GBhBEEiwAFaghvqdNV-odNLZXPHjT7NAwf8lA-QuMtg666hgvDW1oCJ4nn7wvf869_xoCW4IQAvD_BwE)입니다.
+ 아티팩트를 저장하기 위한 [JFrog 프로젝트 키 및 리포지토리](https://jfrog.com/help/r/jfrog-platform-administration-documentation/step-1-set-up-a-new-project)입니다.

**제한 사항 **
+  AWS Supply Chain 인스턴스는 복잡한 데이터 변환 기술을 지원하지 않습니다.
+ AWS Supply Chain 는 내장된 분석 및 인사이트를 제공하므로 공급망 도메인에 가장 적합합니다. 다른 도메인의 경우 데이터 레이크 아키텍처의 일부로 데이터 스토어로 사용할 AWS Supply Chain 수 있습니다.
+ 프로덕션 규모 배포에서 API 재시도 및 메모리 관리를 처리하려면이 솔루션에 사용되는 Lambda 함수를 개선해야 할 수 있습니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-architecture"></a>

자동화된 GitHub Actions 워크플로를 사용하거나 Terraform을 사용하여 수동으로이 솔루션을 배포할 수 있습니다.

**GitHub Actions를 사용한 자동 배포**

다음 다이어그램은 GitHub Actions 워크플로를 사용하는 자동 배포 옵션을 보여줍니다. JFrog Artifactory는 아티팩트 관리에 사용됩니다. 다중 리포지토리 배포에 사용할 리소스 정보와 출력을 저장합니다.

![\[GitHub Actions 워크플로 및 JFrog를 사용하는 자동 배포 옵션입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/2f0b78b0-a174-4703-b533-d66b3fb005e0/images/d454a5c5-ed51-421c-a87f-ff74cfcb30be.png)


**Terraform을 사용한 수동 배포**

다음 다이어그램은 Terraform을 통한 수동 배포 옵션을 보여줍니다. Amazon S3는 JFrog Artifactory 대신 아티팩트 관리에 사용됩니다.

![\[Terraform 및 Amazon S3를 사용한 수동 배포 옵션.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/2f0b78b0-a174-4703-b533-d66b3fb005e0/images/1130e728-44d5-4ae7-9586-1e497f54352a.png)


**배포 워크플로**

이 다이어그램은 다음 워크플로를 보여 줍니다.

1. 다음 배포 방법 중 하나를 사용하여 AWS Supply Chain 서비스 데이터 세트 인프라 및 데이터베이스를 배포합니다.
   + **자동 배포** - GitHub Actions 워크플로를 사용하여 모든 배포 단계를 오케스트레이션하고 아티팩트 관리를 위해 JFrog Artifactory를 사용합니다.
   + **수동 배포** - 각 배포 단계에 대해 Terraform 명령을 직접 실행하고 Amazon S3를 아티팩트 관리에 사용합니다.

1.  AWS Supply Chain 서비스 작업에 필요한 지원 AWS 리소스를 생성합니다.
   + Amazon VPC 엔드포인트 및 보안 그룹
   + AWS KMS keys
   + CloudWatch Logs 로그 그룹

1. 다음 인프라 리소스를 생성하고 배포합니다.
   +  AWS Supply Chain 서비스 인스턴스, 네임스페이스 및 데이터 세트를 관리(생성, 업데이트 및 삭제)하는 Lambda 함수입니다.
   + AWS Supply Chain 데이터 수집을 위한 Amazon S3 버킷 스테이징

1. 스테이징 버킷과 AWS Supply Chain 데이터 세트 간의 통합 흐름을 관리하는 Lambda 함수를 배포합니다. 배포가 완료되면 나머지 워크플로 단계에서 데이터 수집 및 분석을 관리합니다.

1.  AWS Supply Chain 스테이징 Amazon S3 버킷에 대한 소스 데이터 수집을 구성합니다.

1.  AWS Supply Chain 스테이징 Amazon S3 버킷에 데이터가 추가되면 서비스는 AWS Supply Chain 데이터 세트에 대한 통합 흐름을 자동으로 트리거합니다.

1. AWS Supply Chain 는 Quick Sight Analytics와 통합되어 수집된 데이터를 기반으로 대시보드를 생성합니다.

## 도구
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-tools"></a>

**AWS 서비스**
+ [Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)를 사용하면 모든 시스템, 애플리케이션 및의 로그를 중앙 집중화 AWS 서비스 하여 모니터링하고 안전하게 보관할 수 있습니다.
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 셸의 명령을 AWS 서비스 통해와 상호 작용하는 데 도움이 되는 오픈 소스 도구입니다.
+ [Amazon Elastic Compute Cloud(Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)는 AWS 클라우드에서 확장 가능한 컴퓨팅 용량을 제공합니다. 필요한 만큼 가상 서버를 시작하고 빠르게 스케일 업하거나 스케일 다운할 수 있습니다.
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)는 애플리케이션을 다양한 소스의 실시간 데이터와 연결할 수 있는 서버리스 이벤트 버스 서비스입니다. 예를 들어 AWS Lambda 함수, API 대상을 사용하는 HTTP 호출 엔드포인트 또는 다른의 이벤트 버스가 있습니다 AWS 계정.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 액세스를 인증하고 사용할 권한이 있는 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다.
+ [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)를 사용하면 모든 AWS 계정 및 클라우드 애플리케이션에 대한 Single Sign-On(SSO) 액세스를 중앙에서 관리할 수 있습니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ 의 [Amazon Q](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/qinasc.html) AWS Supply Chain 는 AWS Supply Chain 데이터 레이크의 데이터를 분석하여 공급망을 보다 효율적으로 운영하는 데 도움이 되는 대화형 생성형 AI 어시스턴트입니다.
+ [Amazon Quick Sight](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html)는 분석, 데이터 시각화 및 보고에 사용할 수 있는 클라우드급 비즈니스 인텔리전스(BI) 서비스입니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.
+ [AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/adminguide/getting-started.html)는 공급망 도메인의 조직에서 데이터 스토어로 사용할 수 있는 클라우드 기반 관리형 애플리케이션으로, 수집된 데이터에 대한 인사이트를 생성하고 분석을 수행하는 데 사용할 수 있습니다.
+ [Amazon Virtual Private Cloud(VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)를 사용하면 정의한 가상 네트워크에서 AWS 리소스를 시작할 수 있습니다. 이 가상 네트워크는 AWS의 확장 가능한 인프라를 사용한다는 이점과 함께 고객의 자체 데이터 센터에서 운영하는 기존 네트워크와 유사합니다. [Amazon VPC 엔드포인트](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)는 인터넷 게이트웨이, NAT 디바이스, VPN 연결 또는 연결 AWS 서비스 없이 지원되는에 VPC를 비공개로 AWS Direct Connect 연결하는 데 도움이 되는 가상 디바이스입니다.

**기타 도구**
+ [GitHub Actions](https://docs.github.com/en/actions)는 GitHub 리포지토리와 긴밀하게 통합된 지속적 통합 및 지속적 전달(CI/CD) 플랫폼입니다. GitHub Actions를 사용하여 빌드, 테스트 및 배포 파이프라인을 자동화할 수 있습니다.
+ [HashiCorp Terraform](https://www.terraform.io/)은 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.
+ [JFrog Artifactory](https://jfrog.com/help/r/jfrog-artifactory-documentation/jfrog-artifactory)는 애플리케이션 전송 프로세스를 통해 바이너리 및 아티팩트의 end-to-end 자동화 및 관리를 제공합니다.
+ [Python](https://www.python.org/)은 범용 컴퓨터 프로그래밍 언어입니다. 이 패턴은 AWS 함수의 코드에 Python을 사용하여와 상호 작용합니다. AWS Supply Chain

  .

## 모범 사례
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-best-practices"></a>
+ 이 패턴을 구현할 때 최대한 보안을 유지합니다. [사전 조건에](#automate-the-deployment-of-aws-supply-chain-data-lakes-prereqs) 명시된 대로 두 개의 [프라이빗 서브넷이 있는 Virtual Private Cloud(VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html)가 AWS 리전 선택한의 AWS 계정 에 있는지 확인합니다. [https://docs.aws.amazon.com/vpc/latest/userguide/vpc-example-private-subnets-nat.html](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-example-private-subnets-nat.html) 
+ 가능하면 AWS KMS [고객 관리형 키를](https://docs.aws.amazon.com/kms/latest/cryptographic-details/basic-concepts.html) 사용하고 제한된 액세스 권한을 부여합니다.
+ 이 패턴에 대한 데이터를 수집하는 데 필요한 액세스 권한이 가장 적은 IAM 역할을 설정하려면이 패턴의 리포지토리에서 [소스 시스템에서 Amazon S3로의 데이터 수집 보안을](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main?tab=readme-ov-file#secure-data-ingestion-from-source-systems-to-amazon-s3) 참조하세요.

## 에픽
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-epics"></a>

### (두 옵션 모두) 로컬 워크스테이션 설정
<a name="both-options-set-up-local-workstation"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리포지토리를 복제합니다. | 이 패턴의 리포지토리를 복제하려면 로컬 워크스테이션에서 다음 명령을 실행합니다.<pre>git clone https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment.git<br />cd ASC-Deployment</pre> | DevOps | 
| (자동 옵션) 배포를 위한 사전 조건을 확인합니다. | 자동 배포를 위한 [사전 조건이](#automate-the-deployment-of-aws-supply-chain-data-lakes-prereqs) 완료되었는지 확인합니다. | 앱 소유자 | 
| (수동 옵션) AWS Supply Chain 데이터 세트 배포를 준비합니다. | 의 `terraform-deployment` 디렉터리로 이동하려면 다음 명령을 `ASC-Datasets`실행합니다.<pre>cd ASC-Datasets/terraform-deployment</pre>[사전 조건에서](#automate-the-deployment-of-aws-supply-chain-data-lakes-prereqs) 생성된 역할 ARN을 수임하려면 다음 명령을 실행합니다.<pre>aws sts assume-role --role-arn <enter AWS user role ARN> --role-session-name <your-session-name></pre>환경 변수를 구성하고 내보내려면 다음 명령을 실행합니다.<pre># Export Environment variables<br />export REGION=<Enter deployment region><br />export REPO_NAME=<Enter Current ASC Datasets dir name><br />export PROJECT_NAME="asc-deployment-poc"<br />export ACCOUNT_ID=<Enter deployment Account ID><br />export ENVIRONMENT="dev"<br />export LAMBDA_LAYER_TEMP_DIR_TERRAFORM="layerOutput"<br />export LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM="lambdaOutput"<br />export AWS_USER_ROLE=<Enter user role ARN for AWS Console access and deployment><br />export S3_TERRAFORM_ARTIFACTS_BUCKET_NAME="$PROJECT_NAME-$ACCOUNT_ID-$REGION-terraform-artifacts-$ENVIRONMENT"</pre> | DevOps | 
| (수동 옵션) 배포에서 AWS Supply Chain 통합 흐름을 관리할 준비를 합니다. | 의 `terraform-deployment` 디렉터리로 이동하려면 다음 명령을 `ASC-Integration-Flows`실행합니다.<pre>cd ASC-Integration-Flows/terraform-deployment</pre>이전에 생성된 역할 ARN을 수임하려면 다음 명령을 실행합니다.<pre>aws sts assume-role --role-arn <enter AWS user role ARN> --role-session-name <your-session-name></pre>환경 변수를 구성하고 내보내려면 다음 명령을 실행합니다.<pre># Export Environment variables<br />export REGION=<Enter deployment region><br />export REPO_NAME=<Enter Current ASC Integration Flows dir name><br />export ASC_DATASET_VARS_REPO=<Enter Current ASC Datasets dir name>  #Must be the same directory name used for ASC Datasets deployment<br />export PROJECT_NAME="asc-deployment-poc"<br />export ACCOUNT_ID=<Enter deployment Account ID><br />export ENVIRONMENT="dev"<br />export LAMBDA_LAYER_TEMP_DIR_TERRAFORM="layerOutput"<br />export LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM="lambdaOutput"<br />export S3_TERRAFORM_ARTIFACTS_BUCKET_NAME="$PROJECT_NAME-$ACCOUNT_ID-$REGION-terraform-artifacts-$ENVIRONMENT"</pre> | 앱 소유자 | 

### (자동 옵션) GitHub Actions 워크플로를 사용하여 AWS Supply Chain 데이터 세트 배포
<a name="automated-option-deploy-supplychain-datasets-using-github-actions-workflows"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `ASC-Datasets` 디렉터리를 복사합니다. | `ASC-Datasets` 디렉터리를 새 위치에 복사하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | DevOps | 
| `ASC-Datasets` 디렉터리를 설정합니다. | 를 조직의 독립 실행형 리포지토리`ASC-Datasets`로 설정하려면 다음 명령을 실행합니다.<pre>git init<br />git add .<br />git commit -m "Initial commit: ASC-Datasets standalone repository"<br />git remote add origin <INSERT_ASC_DATASETS_GITHUB_URL><br />git branch -M dev</pre> | DevOps | 
| .github 워크플로 파일에서 브랜치 이름을 구성합니다. | 다음 예제와 같이 [배포](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Datasets/.github/workflows/asc-datasets.yml) 워크플로 파일에서 브랜치 이름을 설정합니다.<pre>   on:<br />     workflow_dispatch:<br />     push:<br />       branches:<br />         - dev     #Change to any other branch preferred for deployment</pre> | 앱 소유자 | 
| GitHub 환경을 설정하고 환경 값을 구성합니다. | GitHub 조직에서 GitHub 환경을 설정하려면이 패턴의 리포지토리에 있는 [ GitHub 환경 설정](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Datasets#setup-github-environments)의 지침을 사용합니다.워크플로 파일에서 [환경 값을](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Datasets#setup-environment-values-in-the-workflow-files) 구성하려면이 패턴의 리포지토리[에 있는 워크플로 파일의 환경 값 설정](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Datasets#setup-environment-values-in-the-workflow-files)의 지침을 사용합니다. | 앱 소유자 | 
| 워크플로를 트리거합니다. | 변경 사항을 GitHub 조직에 푸시하고 배포 워크플로를 트리거하려면 다음 명령을 실행합니다.<pre>git push -u origin dev</pre> | DevOps | 

### (자동 옵션) GitHub Actions 워크플로를 사용하여 AWS Supply Chain 통합 흐름 배포
<a name="automated-option-deploy-supplychain-integration-flows-using-github-actions-workflows"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `ASC-Integration-Flows` 디렉터리를 복사합니다. | `ASC-Integration-Flows` 디렉터리를 새 위치에 복사하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | DevOps | 
| `ASC-Integration-Flows` 디렉터리를 설정합니다. | `ASC-Integration-Flows` 디렉터리를 조직의 독립 실행형 리포지토리로 설정하려면 다음 명령을 실행합니다.<pre>git init<br />git add .<br />git commit -m "Initial commit: ASC-Integration-Flows standalone repository"<br />git remote add origin <INSERT_ASC_Integration_Flows_GITHUB_URL><br />git branch -M dev</pre> | DevOps | 
| .github 워크플로 파일에서 브랜치 이름을 구성합니다. | 다음 예제와 같이 [배포](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Integration-Flows/.github/workflows/asc-integration-flows.yml) 워크플로 파일에서 브랜치 이름을 설정합니다.<pre>   on:<br />     workflow_dispatch:<br />     push:<br />       branches:<br />         - dev     #Change to any other branch preferred for deployment</pre> | 앱 소유자 | 
| GitHub 환경을 설정하고 환경 값을 구성합니다. | GitHub 조직에서 GitHub 환경을 설정하려면이 패턴의 리포지토리에 있는 [ GitHub 환경 설정](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Integration-Flows#setup-github-environments)의 지침을 사용합니다.워크플로 파일에서 [환경 값을](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Integration-Flows#setup-github-environments) 구성하려면이 패턴의 리포지토리[에 있는 워크플로 파일의 환경 값 설정](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Integration-Flows#setup-environment-values-in-the-workflow-files)의 지침을 사용합니다. | 앱 소유자 | 
| 워크플로를 트리거합니다. | 변경 사항을 GitHub 조직에 푸시하고 배포 워크플로를 트리거하려면 다음 명령을 실행합니다.<pre>git push -u origin dev</pre> | DevOps | 

### (수동 옵션) Terraform을 사용하여 AWS Supply Chain 데이터 세트 배포
<a name="manual-option-deploy-supplychain-datasets-using-terraform"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `terraform-deployment ` 디렉터리로 이동합니다. | 의 `terraform-deployment` 디렉터리로 이동하려면 다음 명령을 `ASC-Datasets`실행합니다.<pre>cd ASC-Datasets/terraform-deployment</pre> | DevOps | 
| Terraform 상태 Amazon S3 버킷을 설정합니다. | Terraform 상태 Amazon S3 버킷을 설정하려면 다음 스크립트를 사용합니다.<pre># Setup terraform bucket<br />chmod +x ../scripts/setup-terraform.sh<br />../scripts/setup-terraform.sh</pre> | DevOps | 
| Terraform 아티팩트 Amazon S3 버킷을 설정합니다. | Terraform 아티팩트 Amazon S3 버킷을 설정하려면 다음 스크립트를 사용합니다.<pre># Setup terraform artifacts bucket<br />chmod +x ../scripts/setup-terraform-artifacts-bucket.sh<br />../scripts/setup-terraform-artifacts-bucket.sh</pre> | DevOps | 
| Terraform 백엔드 및 공급자 구성을 설정합니다. | Terraform 백엔드 및 공급자 구성을 설정하려면 다음 스크립트를 사용합니다.<pre># Setup terraform backend and providers config if they don't exist<br />chmod +x ../scripts/generate-terraform-config.sh<br />../scripts/generate-terraform-config.sh</pre> | DevOps | 
| 배포 계획을 생성합니다. | 배포 계획을 생성하려면 다음 명령을 실행합니다.<pre># Run terraform init and validate<br />terraform init<br />terraform validate<br /><br /># Run terraform plan<br />terraform plan \<br />-var-file="tfInputs/$ENVIRONMENT.tfvars" \<br />-var="project_name=$PROJECT_NAME" \<br />-var="environment=$ENVIRONMENT" \<br />-var="user_role=$AWS_USER_ROLE" \<br />-var="lambda_temp_dir=$LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM" \<br />-var="layer_temp_dir=$LAMBDA_LAYER_TEMP_DIR_TERRAFORM" \<br />-parallelism=40 \<br />-out='tfplan.out'</pre> | DevOps | 
| 구성을 배포합니다. | 구성을 배포하려면 다음 명령을 실행합니다.<pre># Run terraform apply<br />terraform apply tfplan.out</pre> | DevOps | 
| 다른 구성을 업데이트하고 출력을 저장합니다. |  AWS KMS 키 정책을 업데이트하고 적용된 구성 출력을 Terraform 아티팩트 Amazon S3 버킷에 저장하려면 다음 명령을 실행합니다.<pre># Update AWS Supply Chain KMS Key policy with the service's requirements<br />chmod +x ../scripts/update-asc-kms-policy.sh<br />../scripts/update-asc-kms-policy.sh<br /></pre><pre># Update AWS KMS Keys' policy with IAM roles<br />chmod +x ../scripts/update-kms-policy.sh<br />../scripts/update-kms-policy.sh<br /></pre><pre># Create terraform outputs file to be used as input variables<br />terraform output -json > raw_output.json<br />jq -r 'to_entries | map(<br />  if .value.type == "string" then<br />      "\(.key) = \"\(.value.value)\""<br />  else<br />      "\(.key) = \(.value.value | tojson)"<br />  end<br />) | .[]' raw_output.json > $REPO_NAME-outputs.tfvars<br /></pre><pre># Upload reformed outputs file to Amazon S3 terraform artifacts bucket (For retrieval from other repositories)<br />aws s3 cp $REPO_NAME-outputs.tfvars s3://$S3_TERRAFORM_ARTIFACTS_BUCKET_NAME/$REPO_NAME-outputs.tfvars<br />rm -f raw_output.json<br />rm -f $REPO_NAME-outputs.tfvars<br /></pre> | DevOps | 

### (수동 옵션) Terraform을 사용하여 AWS Supply Chain 서비스 통합 흐름 배포
<a name="manual-option-deploy-supplychain-service-integration-flows-using-terraform"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `terraform-deployment` 디렉터리로 이동합니다. | 의 `terraform-deployment` 디렉터리로 이동하려면 다음 명령을 `ASC-Integration-Flows`실행합니다.<pre>cd ASC-Integration-Flows/terraform-deployment</pre> | DevOps | 
| Terraform 백엔드 및 공급자 구성을 설정합니다. | Terraform 백엔드 및 공급자 구성을 설정하려면 다음 스크립트를 사용합니다.<pre># Setup terraform backend and providers config if they don't exist<br />chmod +x ../scripts/generate-terraform-config.sh<br />../scripts/generate-terraform-config.sh</pre> | DevOps | 
| 배포 계획을 생성합니다. | 배포 계획을 생성하려면 다음 명령을 실행합니다. 이러한 명령은 Terraform 환경을 초기화하고,의 구성 변수를 기존 Terraform 구성`ASC-Datasets`과 병합하고, 배포 계획을 생성합니다.<pre># Run terraform init and validate<br />terraform init<br />terraform validate<br /></pre><pre># Download and merge ASC DATASET tfvars<br />chmod +x ../scripts/download-vars-through-s3.sh<br />../scripts/download-vars-through-s3.sh $ASC_DATASET_VARS_REPO<br /></pre><pre># Run terraform plan<br />terraform plan \<br />-var-file="tfInputs/$ENVIRONMENT.tfvars" \<br />-var="project_name=$PROJECT_NAME" \<br />-var="environment=$ENVIRONMENT" \<br />-var="lambda_temp_dir=$LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM" \<br />-var="layer_temp_dir=$LAMBDA_LAYER_TEMP_DIR_TERRAFORM" \<br />-parallelism=40 \<br />-out='tfplan.out'</pre> | DevOps | 
| 구성을 배포합니다. | 구성을 배포하려면 다음 명령을 실행합니다.<pre># Run terraform apply<br />terraform apply tfplan.out</pre> | DevOps | 
| 다른 구성을 업데이트합니다. |  AWS KMS 키 정책을 업데이트하고 적용된 구성 출력을 Terraform 아티팩트 Amazon S3 버킷에 저장하려면 다음 명령을 실행합니다.<pre># Update AWS KMS Keys' policy with IAM roles<br />chmod +x ../scripts/update-kms-policy-through-s3.sh<br />../scripts/update-kms-policy-through-s3.sh $ASC_DATASET_VARS_REPO<br /></pre><pre># Create terraform outputs file to be used as input variables<br />terraform output -json > raw_output.json<br />jq -r 'to_entries | map(<br />  if .value.type == "string" then<br />      "\(.key) = \"\(.value.value)\""<br />  else<br />      "\(.key) = \(.value.value | tojson)"<br />  end<br />) | .[]' raw_output.json > $REPO_NAME-outputs.tfvars<br /></pre><pre># Upload reformed outputs file to Amazon S3 terraform artifacts bucket (For retrieval from other repositories)<br />aws s3 cp $REPO_NAME-outputs.tfvars s3://$S3_TERRAFORM_ARTIFACTS_BUCKET_NAME/$REPO_NAME-outputs.tfvars<br />rm -f raw_output.json<br />rm -f $REPO_NAME-outputs.tfvars<br /></pre> | DevOps | 

### (두 옵션 모두) 데이터 수집
<a name="both-options-ingest-data"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 샘플 CSV 파일을 업로드합니다. | 데이터 세트에 대한 샘플 CSV 파일을 업로드하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | 데이터 엔지니어 | 

### (두 옵션 모두) AWS Supply Chain 액세스 설정
<a name="both-options-set-up-supplychain-access"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  AWS Supply Chain 액세스를 설정합니다. | 에서 AWS Supply Chain 액세스를 설정하려면 다음 단계를 AWS Management Console사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | 앱 소유자 | 

### (자동 옵션) GitHub Actions 워크플로를 사용하여 모든 리소스 정리
<a name="automated-option-clean-up-all-resources-using-github-actions-workflows"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 통합 흐름 리소스에 대한 삭제 워크플로를 트리거합니다. | GitHub 조직의 배포 브랜치`ASC-Integration-Flows`에서의 [폐기 워크플로](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Integration-Flows/.github/workflows/destroy-workflow.yml)를 트리거합니다. | DevOps | 
| 데이터 세트 리소스에 대한 삭제 워크플로를 트리거합니다. | GitHub 조직의 배포 브랜치`ASC-Datasets`에서의 [폐기 워크플로](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Datasets/.github/workflows/destroy-workflow.yml)를 트리거합니다. | DevOps | 

### (수동 옵션) Terraform을 사용하여 AWS Supply Chain 통합 흐름의 리소스 정리
<a name="manual-option-clean-up-resources-of-supplychain-integration-flows-using-terraform"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `terraform-deployment` 디렉터리로 이동합니다. | 의 `terraform-deployment` 디렉터리로 이동하려면 다음 명령을 `ASC-Integration-Flows`실행합니다.<pre>cd ASC-Integration-Flows/terraform-deployment</pre> | DevOps | 
| Terraform 백엔드 및 공급자 구성을 설정합니다. | Terraform 백엔드 및 공급자 구성을 설정하려면 다음 스크립트를 사용합니다.<pre># Setup terraform backend and providers config if they don't exist<br />chmod +x ../scripts/generate-terraform-config.sh<br />../scripts/generate-terraform-config.sh</pre> | DevOps | 
| 인프라 폐기 계획을 생성합니다. | 세부 해체 계획을 생성하여 AWS 인프라의 제어된 파괴를 준비하려면 다음 명령을 실행합니다. 이 프로세스는 Terraform을 초기화하고, AWS Supply Chain 데이터 세트 구성을 통합하고, 실행 전에 검토할 수 있는 폐기 계획을 생성합니다.<pre># Run terraform init and validate<br />terraform init<br />terraform validate<br /></pre><pre># Download and merge ASC DATASET tfvars<br />chmod +x ../scripts/download-vars-through-s3.sh<br />../scripts/download-vars-through-s3.sh $ASC_DATASET_VARS_REPO<br /></pre><pre># Run terraform plan<br />terraform plan -destroy\<br />-var-file="tfInputs/$ENVIRONMENT.tfvars" \<br />-var="project_name=$PROJECT_NAME" \<br />-var="environment=$ENVIRONMENT" \<br />-var="lambda_temp_dir=$LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM" \<br />-var="layer_temp_dir=$LAMBDA_LAYER_TEMP_DIR_TERRAFORM" \<br />-parallelism=40 \<br />-out='tfplan.out'</pre> | DevOps | 
| 인프라 폐기 계획을 실행합니다. | 인프라의 계획된 폐기를 실행하려면 다음 명령을 실행합니다.<pre># Run terraform apply<br />terraform apply tfplan.out</pre> | DevOps | 
| Amazon S3 버킷에서 Terraform 출력을 제거합니다. | 배포 중에 업로드된 출력 파일을 제거하려면 다음 명령을 `ASC-Integration-Flows`실행합니다.<pre># Delete the outputs file<br />aws s3 rm s3://$S3_TERRAFORM_ARTIFACTS_BUCKET_NAME/$REPO_NAME-outputs.tfvars</pre> | DevOps | 

### (수동 옵션) Terraform을 사용하여 AWS Supply Chain 서비스 데이터 세트의 리소스 정리
<a name="manual-option-clean-up-resources-of-supplychain-service-datasets-using-terraform"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `terraform-deployment` 디렉터리로 이동합니다. | 의 `terraform-deployment` 디렉터리로 이동하려면 다음 명령을 `ASC-Datasets`실행합니다.<pre>cd ASC-Datasets/terraform-deployment</pre> | DevOps | 
| Terraform 백엔드 및 공급자 구성을 설정합니다. | Terraform 백엔드 및 공급자 구성을 설정하려면 다음 스크립트를 사용합니다.<pre># Setup terraform backend and providers config if they don't exist<br />chmod +x ../scripts/generate-terraform-config.sh<br />../scripts/generate-terraform-config.sh</pre> | DevOps | 
| 인프라 폐기 계획을 생성합니다. |  AWS Supply Chain 데이터 세트 리소스를 삭제하기 위한 계획을 생성하려면 다음 명령을 실행합니다.<pre># Run terraform init and validate<br />terraform init<br />terraform validate<br /><br /># Run terraform plan<br />terraform plan -destroy\<br />-var-file="tfInputs/$ENVIRONMENT.tfvars" \<br />-var="project_name=$PROJECT_NAME" \<br />-var="environment=$ENVIRONMENT" \<br />-var="user_role=$AWS_USER_ROLE" \<br />-var="lambda_temp_dir=$LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM" \<br />-var="layer_temp_dir=$LAMBDA_LAYER_TEMP_DIR_TERRAFORM" \<br />-parallelism=40 \<br />-out='tfplan.out'</pre> | DevOps | 
| Amazon S3 버킷을 비웁니다. | 모든 Amazon S3 버킷(에 대해 구성된 서버 액세스 로깅 버킷 제외`force-destroy`)을 비우려면 다음 스크립트를 사용합니다.<pre># Delete S3 buckets excluding server access logging bucket<br />chmod +x ../scripts/empty-s3-buckets.sh<br />../scripts/empty-s3-buckets.sh tfplan.out</pre> | DevOps | 
| 인프라 폐기 계획을 실행합니다. | 생성된 계획을 사용하여 AWS Supply Chain 데이터 세트 인프라의 계획된 폐기를 실행하려면 다음 명령을 실행합니다.<pre># Run terraform apply<br />terraform apply tfplan.out</pre> | DevOps | 
| Amazon S3 Terraform 아티팩트 버킷에서 Terraform 출력을 제거합니다. | 정리 프로세스를 완료하려면 다음 명령을 실행`ASC-Datasets`하여 배포 중에 업로드된 출력 파일을 제거합니다.<pre># Delete the outputs file<br />aws s3 rm s3://$S3_TERRAFORM_ARTIFACTS_BUCKET_NAME/$REPO_NAME-outputs.tfvars</pre> | DevOps | 

## 문제 해결
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
|  AWS Supply Chain 내부 오류 또는 서비스 역할에 대한 IAM 권한 부족으로 인해 AWS Supply Chain 데이터 세트 또는 통합 흐름이 올바르게 배포되지 않았습니다. | 먼저 모든 리소스를 정리합니다. 그런 다음 AWS Supply Chain [데이터 세트 리소스를](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Datasets/README.md) 재배포한 다음 AWS Supply Chain [통합 흐름 리소스를](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Integration-Flows/README.md) 재배포합니다. | 
|  AWS Supply Chain 통합 흐름은 AWS Supply Chain 데이터 세트에 대해 업로드된 새 데이터 파일을 가져오지 않습니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | 

## 관련 리소스
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-resources"></a>

**AWS 설명서**
+ [AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/adminguide/getting-started.html)

**기타 리소스**
+ [GitHub 작업 워크플로 이해](https://docs.github.com/en/actions/get-started/understand-github-actions)(GitHub 설명서)

## 추가 정보
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-additional"></a>

이 솔루션은 더 많은 데이터 세트에 복제할 수 있으며와 함께 제공되는 사전 구축된 대시보드 AWS Supply Chain 또는 Amazon Quick Sight와의 사용자 지정 통합을 통해 추가 분석을 위해 쿼리할 수 있습니다. 또한 Amazon Q를 사용하여 AWS Supply Chain 인스턴스와 관련된 질문을 할 수 있습니다.

** AWS Supply Chain Analytics를 사용하여 데이터 분석**

 AWS Supply Chain 분석 설정 지침은 AWS Supply Chain 설명서의 [AWS Supply Chain 분석 설정을](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/setting_analytics.html) 참조하세요.

이 패턴은 **Calendar** 및 **Outbound\$1Order\$1Line** 데이터 세트의 생성을 보여줍니다. 이러한 데이터 세트를 사용하는 분석을 생성하려면 다음 단계를 사용합니다.

1. 데이터 세트를 분석하려면 **계절성 분석** 대시보드를 사용합니다. 대시보드를 추가하려면 AWS Supply Chain 설명서의 [사전 구축된 대시보드](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/prebuilt_dashboards.html)의 단계를 따르세요.

1. 대시보드를 선택하여 일정 데이터 및 아웃바운드 주문 라인 데이터에 대한 샘플 CSV 파일을 기반으로 하는 분석을 확인합니다.

대시보드는 데이터 세트에 대해 수집된 데이터를 기반으로 수년간 온디맨드 인사이트를 제공합니다. 분석을 위해 ProductID, CustomerID, 연도 및 기타 파라미터를 추가로 지정할 수 있습니다.

**Amazon Q를 사용하여 AWS Supply Chain 인스턴스와 관련된 질문**

[의 Amazon Q AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/qinasc.html)는 공급망을 보다 효율적으로 운영하는 데 도움이 되는 대화형 생성형 AI 어시스턴트입니다. Amazon Q는 다음을 수행할 수 있습니다.
+ 데이터 레이크의 AWS Supply Chain 데이터를 분석합니다.
+ 운영 및 재무 인사이트를 제공합니다.
+ 즉각적인 공급망 질문에 답변합니다.

Amazon Q 사용에 대한 자세한 내용은 AWS Supply Chain 설명서의 [에서 Amazon Q 활성화 AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/enabling_QinASC.html) 및 [에서 Amazon Q 사용을 AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/using_QinASC.html) 참조하세요.

# AWS 리소스 평가 자동화
<a name="automate-aws-resource-assessment"></a>

*Naveen Suthar, Arun Bagal, Manish Garg, Sandeep Gawande, Amazon Web Services*

## 요약
<a name="automate-aws-resource-assessment-summary"></a>

이 패턴은 [AWS Cloud Development Kit(AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)를 사용하여 리소스 평가 기능을 설정하는 자동화된 접근 방식을 설명합니다. 운영팀은 이 패턴을 사용하여 자동화된 방식으로 리소스 감사 세부 정보를 수집하고 단일 대시보드에서 AWS 계정에 배포된 모든 리소스의 세부 정보를 볼 수 있습니다. 이는 다음과 같은 경우에 유용합니다.
+ 코드형 인프라(IaC) 도구를 식별하고 [HashiCorp Terraform](https://www.terraform.io/), [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html), AWS CDK, 및 [AWS Command Line Interface(AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)와 같은 다양한 IaC 솔루션에서 생성된 리소스를 격리합니다.
+ 리소스 감사 정보 가져오기

또한 이 솔루션은 경영진이 단일 대시보드에서 AWS 계정의 리소스 및 활동에 대한 통찰력을 얻는 데도 도움이 됩니다.


| 
| 
| 참고: [Amazon Quick Sight](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html)는 유료 서비스입니다. 데이터를 분석하고 대시보드를 생성하기 위해 실행하기 전에 [Amazon Quick Sight 요금을](https://aws.amazon.com/quicksight/pricing/) 검토하세요. | 
| --- |

## 사전 조건 및 제한 사항
<a name="automate-aws-resource-assessment-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정.
+ AWS Identity and Access Management(IAM) 역할과 리소스 프로비저닝에 대한 액세스 권한
+ [Amazon Simple Storage Service(S3) 및 Amazon Athena에 대한 액세스 권한으로 생성된 Amazon Quick 계정](https://docs.aws.amazon.com/quicksight/latest/user/signing-up.html) [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html)
+ AWS CDK 버전 2.55.1 이상 설치 
+ [Python](https://www.python.org/downloads/release/python-390/) 버전 3.9 이상 설치

**제한 사항 **
+ 이 솔루션은 단일 AWS 계정에 배포됩니다.
+ AWS CloudTrail이 이미 설정되어 있고 S3 버킷에 데이터를 저장하지 않는 한 솔루션은 배포 전에 발생한 이벤트를 추적하지 않습니다.

**제품 버전**
+ AWS CDK 버전 2.55.1 이상
+ Python 버전 3.9 이상

## 아키텍처
<a name="automate-aws-resource-assessment-architecture"></a>

**대상 기술 스택**
+ Amazon Athena
+ AWS CloudTrail
+ Glue
+ AWS Lambda
+ Amazon Quick Sight
+ Amazon S3

**대상 아키텍처**

AWS CDK 코드는 AWS 계정에서 리소스 평가 기능을 설정하는 데 필요한 모든 리소스를 배포합니다. 다음 다이어그램은 CloudTrail 로그를 AWS Glue, Amazon Athena 및 Quick Sight로 전송하는 프로세스를 보여줍니다.

![\[6단계 프로세스로 AWS Glue, Amazon Athena 및 Amazon QuickSight를 사용한 AWS 리소스 평가.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/a504774e-db7a-4c36-a22c-ce56d252fb58/images/8f2b549d-33a8-4cbf-86fd-33244716b668.png)


1. CloudTrail은 저장을 위해 로그를 S3 버킷으로 전송합니다.

1. 이벤트 알림은 로그를 처리하고 필터링된 데이터를 생성하는 Lambda 함수를 간접 호출합니다.

1. 필터링된 데이터는 다른 S3 버킷에 저장됩니다.

1. S3 버킷의 필터링된 데이터에 AWS Glue 크롤러가 설정되어 AWS Glue 데이터 카탈로그 테이블에 스키마를 생성합니다.

1. Amazon Athena는 필터링된 데이터를 쿼리할 준비가 되었습니다.

1. 쿼리된 데이터는 Quick Sight에서 시각화를 위해 액세스합니다.

**자동화 및 규모 조정**
+ AWS Organizations에 조직 전체의 CloudTrail 트레일이 있는 경우 이 솔루션을 하나의 AWS 계정에서 여러 AWS 계정으로 규모를 조정할 수 있습니다. 조직 수준에서 CloudTrail을 배포하면 이 솔루션을 사용하여 필요한 모든 리소스에 대한 리소스 감사 세부 정보를 가져올 수도 있습니다.
+ 이 패턴은 AWS 서버리스 리소스를 사용하여 솔루션을 배포합니다.

## 도구
<a name="automate-aws-resource-assessment-tools"></a>

**서비스**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html)는 표준 SQL을 사용하여 Amazon S3에 있는 데이터를 직접 분석할 수 있는 대화형 쿼리 서비스입니다.
+ [AWS Cloud Development Kit(AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)는 AWS 클라우드 인프라를 코드로 정의하고 프로비저닝하는 데 도움이 되는 소프트웨어 개발 프레임워크입니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)을 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하며, 전체 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 Glue 크롤러와 AWS Glue 데이터 카탈로그 테이블을 사용합니다.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행할 수 있도록 도와주는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [Amazon Quick](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html)은 단일 대시보드에서 데이터를 시각화, 분석 및 보고하는 데 도움이 되는 클라우드 규모의 비즈니스 인텔리전스(BI) 서비스입니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [infrastructure-assessment-iac-automation](https://github.com/aws-samples/infrastructure-assessment-iac-automation)에서 사용할 수 있습니다.

코드 리포지토리에는 다음 파일과 폴더가 포함되어 있습니다.
+ `lib` 폴더 - AWS CDK는 AWS 리소스를 생성하는 데 사용되는 Python 파일 구성
+ `src/lambda_code` - Lambda 함수에서 실행되는 Python 코드
+ `requirements.txt` - 설치해야 하는 모든 Python 종속성 목록
+ `cdk.json` - 리소스를 스핀업하는 데 필요한 값을 제공하는 입력 파일

## 모범 사례
<a name="automate-aws-resource-assessment-best-practices"></a>

Lambda 함수에 대한 모니터링 및 알림을 설정합니다. 자세한 내용은 [Lambda 함수 모니터링 및 문제 해결](https://docs.aws.amazon.com/lambda/latest/dg/lambda-monitoring.html)을 참조하십시오. Lambda 함수를 사용할 때의 일반적인 모범 사례는 [AWS 설명서](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)를 참조하십시오.

## 에픽
<a name="automate-aws-resource-assessment-epics"></a>

### 환경을 설정합니다
<a name="set-up-your-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 로컬 머신에서 저장소를 복제합니다. | 리포지토리를 복제하려면 `git clone https://github.com/aws-samples/infrastructure-assessment-iac-automation.git` 명령을 실행합니다. | AWS DevOps, DevOps 엔지니어 | 
| Python 가상 환경을 설정하고 필요한 종속성을 설치합니다. | 다음 명령을 실행하여 Python 가상 환경을 설정합니다.<pre>cd infrastructure-assessment-iac-automation<br />python3 -m venv .venv<br />source .venv/bin/activate</pre>필요한 종속성을 설정하려면 `pip install -r requirements.txt` 명령을 실행합니다. | AWS DevOps, DevOps 엔지니어 | 
| AWS CDK 환경을 설정하고 AWS CDK 코드를 합성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps, DevOps 엔지니어 | 

### 로컬 머신에서 AWS 보안 인증 설정
<a name="set-up-aws-credentials-on-your-local-machine"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 스택이 배포될 계정 및 리전의 변수를 내보냅니다. | 환경 변수를 사용하여 AWS CDK용 AWS 보안 인증을 제공하려면 다음 명령을 실행합니다.<pre>export CDK_DEFAULT_ACCOUNT=<12 Digit AWS Account Number><br />export CDK_DEFAULT_REGION=<region></pre> | AWS DevOps, DevOps 엔지니어 | 
| AWS CLI 프로필을 설치합니다. | 계정에 대한 AWS CLI 프로필을 설정하려면 [AWS 설명서](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/keys-profiles-credentials.html)의 지침을 따르십시오. | AWS DevOps, DevOps 엔지니어 | 

### 리소스 평가 도구 구성 및 배포
<a name="configure-and-deploy-the-resource-assessment-tool"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 계정에 리소스를 배포하십시오. | AWS CDK를 사용하여 AWS 계정에 리소스를 배포하려면 다음을 수행하십시오.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | DevOps | 
| AWS Glue 크롤러를 실행하며 데이터 카탈로그 테이블을 생성합니다. | [AWS Glue 크롤러](https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html)는 데이터 스키마를 동적으로 유지하는 데 사용됩니다. 이 솔루션은 AWS Glue 크롤러 스케줄러에서 정의한 대로 정기적으로 크롤러를 실행하여 [AWS Glue 데이터 카탈로그 테이블](https://docs.aws.amazon.com/athena/latest/ug/querying-glue-catalog.html)에 파티션을 생성하고 업데이트합니다. 출력 S3 버킷에서 데이터를 사용할 수 있게 되면 다음 단계에 따라 AWS Glue 크롤러를 실행하고 테스트용 데이터 카탈로그 테이블 스키마를 생성합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html)AWS CDK 코드는 AWS Glue 크롤러가 특정 시간에 실행되도록 구성하지만 온디맨드로 실행할 수도 있습니다. | AWS DevOps, DevOps 엔지니어 | 
| Quick Sight 구문을 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps, DevOps 엔지니어 | 
| Quick Sight 대시보드를 생성합니다. | Quick Sight 대시보드 및 분석 예제를 생성하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html)자세한 내용은 [Amazon Quick Sight에서 분석 시작](https://docs.aws.amazon.com/quicksight/latest/user/creating-an-analysis.html) 및 [Amazon Quick Sight에서 시각적 객체 유형을 참조하세요](https://docs.aws.amazon.com/quicksight/latest/user/working-with-visual-types.html). | AWS DevOps, DevOps 엔지니어 | 

### 솔루션의 모든 AWS 리소스를 정리하십시오.
<a name="clean-up-all-aws-resources-in-the-solution"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS 리소스를 제거합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps, DevOps 엔지니어 | 

### AWS 리소스 평가 도구 자동화에 추가 기능 설정
<a name="set-up-additional-features-on-top-of-the-aws-resource-assessment-tool-automation"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 수동으로 생성한 리소스를 모니터링하고 정리합니다. | (선택 사항) 조직에 IaC 도구를 사용하여 리소스를 생성해야 하는 규정 준수 요구 사항이 있는 경우, AWS 리소스 평가 도구 자동화를 사용하여 수동으로 프로비저닝된 리소스를 가져옴으로써 규정 준수를 달성할 수 있습니다. 도구를 사용하여 리소스를 IaC 도구로 가져오거나 다시 생성할 수도 있습니다. 수동으로 프로비저닝된 리소스를 모니터링하려면 다음과 같은 높은 수준의 작업을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps, DevOps 엔지니어 | 

## 문제 해결
<a name="automate-aws-resource-assessment-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| AWS CDK가 오류를 반환합니다. | AWS CDK 문제에 대한 도움이 필요하면 [일반적인 AWS CDK 문제 해결](https://docs.aws.amazon.com/cdk/v2/guide/troubleshooting.html)을 참조하십시오. | 

## 관련 리소스
<a name="automate-aws-resource-assessment-resources"></a>
+ [Python을 사용하여 Lambda 함수 빌드](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html)
+ [AWS CDK로 시작하기](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
+ [Python에서 AWS CDK로 작업하기](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html)
+ [CloudTrail 로그 트레일 생성](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-and-update-a-trail.html)
+ [Amazon Quick Sight 시작하기](https://aws.amazon.com/quicksight/getting-started/)

## 추가 정보
<a name="automate-aws-resource-assessment-additional"></a>

**여러 계정**

여러 계정에 대해 AWS CLI 보안 인증을 설정하려면 AWS 프로필을 사용하십시오. 자세한 내용은 [AWS CLI 설정](https://aws.amazon.com/getting-started/guides/setup-environment/module-three/)의 *다중 프로필 구성* 섹션을 참조하십시오.

**AWS CDK 명령**

AWS CDK로 작업할 때는 다음과 같은 유용한 명령을 유념하십시오.
+ 앱의 모든 스택 나열하기

  ```
  cdk ls
  ```
+ 합성된 AWS CloudFormation 템플릿 내보내기

  ```
  cdk synth
  ```
+ 스택을 기본 AWS 계정 및 리전에 배포하기

  ```
  cdk deploy
  ```
+ 배포된 스택을 현재 상태와 비교하기

  ```
  cdk diff
  ```
+ AWS CDK 설명서 열기

  ```
  cdk docs
  ```

# 오픈소스 도구를 사용하여 SAP 시스템을 자동으로 설치
<a name="install-sap-systems-automatically-by-using-open-source-tools"></a>

*Guilherme Sesterheim, Amazon Web Services*

## 요약
<a name="install-sap-systems-automatically-by-using-open-source-tools-summary"></a>

이 패턴은 오픈소스 도구를 사용하여 다음 리소스를 생성함으로써 SAP 시스템 설치를 자동화하는 방법을 보여줍니다.
+ SAP S/4HANA 1909 데이터베이스
+ SAP ABAP Central Services(ASCS) 인스턴스
+ SAP Primary Application Server(PAS) 인스턴스

HashiCorp Terraform은 SAP 시스템의 인프라를 생성하고 Ansible은 운영 체제(OS)를 구성하며 SAP 애플리케이션을 설치합니다. Jenkins는 설치를 실행합니다.

이 설정은 SAP 시스템 설치를 반복 가능한 프로세스로 바꾸어 배포 효율성과 품질을 높이는 데 도움이 될 수 있습니다.

**참고**  
이 패턴에 제공된 예제 코드는 고가용성(HA) 시스템과 비 HA 시스템 모두에서 작동합니다.

## 사전 조건 및 제한 사항
<a name="install-sap-systems-automatically-by-using-open-source-tools-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정
+ 모든 SAP 미디어 파일이 포함된 Amazon Simple Storage Service(S3) 버킷
+ [액세스 키와 비밀 키](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)가 있는 Identity and Access Management(IAM) 보안 주체는 다음과 같은 권한을 가집니다.
  + **읽기 전용 권한:** Amazon Route 53, Key Management Service(KMS)
  + **읽기 및 쓰기 권한:** Amazon S3, Amazon Elastic Compute Cloud(Amazon EC2), Amazon Elastic File System(Amazon EFS), IAM, Amazon CloudWatch, Amazon DynamoDB
+ Route 53 [프라이빗 호스팅 영역](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)
+ Amazon Marketplace에서 [HA 및 업데이트 서비스 8.2](https://aws.amazon.com/marketplace/pp/prodview-5grz5a5thx7c2) Amazon Machine Image(AMI)가 있는 SAP용 Red Hat Enterprise Linux에 대한 구독
+ [KMS 고객 관리형 키](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html#aws-managed-customer-managed-keys)
+ [Secure Shell(SSH) 키 페어](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)
+ Jenkins를 설치하는 곳의 호스트 이름을 통해 포트 22의 SSH 연결을 허용하는 [Amazon EC2 보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)(호스트 이름은 **localhost**일 가능성이 높음)
+ HashiCorp의 [Vagrant](https://www.vagrantup.com/) 설치 및 구성
+ Oracle의 [VirtualBox](https://www.virtualbox.org/) 설치 및 구성
+ Git, Terraform, Ansible, Jenkins에 대한 익숙함

**제한 사항 **
+ SAP S/4HANA 1909가 이 특정 시나리오에 대한 완전한 테스트를 거쳤습니다. 다른 버전의 SAP HANA를 사용하는 경우 이 패턴의 예제 Ansible 코드를 수정해야 합니다.
+ 이 패턴의 예제 절차는 Mac OS 및 Linux 운영 체제에서 작동합니다. 일부 명령은 Unix 기반 터미널에서만 실행할 수 있습니다. 하지만 각기 다른 명령과 Windows OS를 사용하면 비슷한 결과를 얻을 수 있습니다.

**제품 버전**
+ SAP S/4HANA 1909
+ Red Hat Enterprise Linux (RHEL) 8.2 이상 버전

## 아키텍처
<a name="install-sap-systems-automatically-by-using-open-source-tools-architecture"></a>

다음 다이어그램은 오픈소스 도구를 사용하여 계정에서 SAP 시스템 설치를 자동화하는 예제 워크플로를 보여 줍니다.

![\[다음 다이어그램은 오픈소스 도구를 사용하여 계정에서 SAP 시스템 설치를 자동화하는 워크플로 예.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/aaf11dac-38cc-4e89-be86-51d4409cf238/images/d7902f9d-f1be-461f-b69b-cf3c663c8f2f.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. Jenkins는 Terraform 및 Ansible 코드를 실행하여 SAP 시스템 설치 실행을 오케스트레이션합니다.

1. Terraform 코드는 SAP 시스템의 인프라를 빌드합니다.

1. Ansible 코드는 OS를 구성하고 SAP 애플리케이션을 설치합니다.

1. 정의된 사전 조건을 모두 포함하는 SAP S/4HANA 1909 데이터베이스, ASCS 인스턴스 및 PAS 인스턴스가 Amazon EC2 인스턴스에 설치됩니다.

**참고**  
이 패턴의 예제 설정은 Terraform 상태 파일을 저장하기 위해 계정에 Amazon S3 버킷을 자동으로 생성합니다.

**기술 스택**
+ Terraform
+ Ansible
+ Jenkins
+ SAP S/4HANA 1909 데이터베이스
+ SAP ASCS 인스턴스
+ SAP PAS 인스턴스
+ Amazon EC2 

## 도구
<a name="install-sap-systems-automatically-by-using-open-source-tools-tools"></a>

**서비스**
+ [Amazon Elastic Compute Cloud(Amazon EC2)](https://docs.aws.amazon.com/ec2/?id=docs_gateway)는 AWS 클라우드에서 규모를 조정할 수 있는 컴퓨팅 용량을 제공합니다. 필요한 만큼 많은 가상 서버를 시작하고 빠르게 규모를 확장 또는 축소할 수 있습니다.
+ [Identity and Access Management(IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)를 사용하여 리소스에 대한 액세스를 안전하게 제어할 수 있습니다.
+ [Key Management Service(AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html)를 사용하면 암호화 키를 생성하고 제어하여 데이터를 보호할 수 있습니다.
+ [Amazon Virtual Private Cloud(VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)를 이용하면 사용자가 정의한 가상 네트워크로 AWS 리소스를 시작할 수 있습니다. 이 가상 네트워크는 사용자의 자체 데이터 센터에서 운영하는 기존 네트워크와 유사하며 AWS의 확장 가능한 인프라를 사용한다는 이점이 있습니다.

**기타 도구**
+ [HashiCorp Terraform](https://www.terraform.io/docs)은 코드를 사용하여 클라우드 인프라 및 리소스를 프로비저닝하고 관리하는 데 도움이 되는 명령줄 인터페이스 애플리케이션입니다.
+ [Ansible](https://www.ansible.com/)은 애플리케이션, 구성 및 IT 인프라를 자동화하는 데 도움이 되는 코드형 오픈소스 구성(CaC) 도구입니다.
+ [Jenkins](https://www.jenkins.io/)는 개발자가 그의 소프트웨어를 빌드, 테스트 및 배포할 수 있는 오픈 소스 자동화 서버입니다.

**코드**

이 패턴의 코드는 GitHub [aws-install-sap-with-jenkins-ansible](https://github.com/aws-samples/aws-install-sap-with-jenkins-ansible) 리포지토리에서 사용할 수 있습니다.

## 에픽
<a name="install-sap-systems-automatically-by-using-open-source-tools-epics"></a>

### 필수 구성 요소 구성
<a name="configure-the-prerequisites"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| SAP 미디어 파일을 Amazon S3 버킷에 추가합니다. | 모든 SAP 미디어 파일이 포함된[Amazon S3 버킷을 생성](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)합니다.[Launch Wizard 설명서](https://docs.aws.amazon.com/launchwizard/latest/userguide/launch-wizard-sap-software-install-details.html)의 **S/4HANA**에 대한 Launch Wizard의 폴더 계층 구조를 따라야 합니다. | 클라우드 관리자 | 
| VirtualBox를 설치합니다. | Oracle의 [VirtualBox](https://www.virtualbox.org/)를 설치하고 구성합니다. | DevOps 엔지니어 | 
| Vagrant를 설치합니다. | HashiCorp의 [Vagrant](https://www.vagrantup.com/)를 설치하고 구성합니다. | DevOps 엔지니어 | 
| 계정을 구성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html) | 일반 AWS | 

### SAP 설치의 빌드 및 실행
<a name="build-and-run-your-sap-installation"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| GitHub에서 코드 리포지토리를 복제합니다. | GitHub에서 [AWS-install-sap-with-jenkins-ansible](https://github.com/aws-samples/aws-install-sap-with-jenkins-ansible) 리포지토리를 복제합니다. | DevOps 엔지니어 | 
| Jenkins 서비스를 시작합니다. | Linux 터미널을 엽니다. 그런 다음 복제된 코드 리포지토리 폴더가 들어 있는 로컬 폴더로 이동하여 다음 명령을 실행합니다.<pre>sudo vagrant up</pre>Jenkins를 시작하는 데 약 20분이 소요됩니다. 이 명령은 성공 시 **서비스가 설정되었으며 실행 중**이라는 메시지를 반환합니다. | DevOps 엔지니어 | 
| 웹 브라우저에서 Jenkins를 열고 로그인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html) | DevOps 엔지니어 | 
| SAP 시스템 설치 파라미터를 구성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html)사용 사례를 기준으로 필요에 따라 기타 비필수 파라미터를 구성할 수 있습니다. 예를 들어 SAP 시스템에 관하여 인스턴스의 SAP 시스템 ID(SID), 기본 암호, 이름, 태그를 변경할 수 있습니다. 모든 필수 변수는 이름 앞에 **(필수)**라고 표시됩니다. | 시스템 관리자, DevOps 엔지니어 | 
| SAP 시스템 설치를 실행합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html)파이프라인 절차에 대한 정보는 AWS Blog에서 [오픈소스 도구를 활용한 SAP 설치 자동화](https://aws.amazon.com/blogs/awsforsap/automating-sap-installation-with-open-source-tools/)의 **파이프라인 절차에 대한 이해** 섹션을 참조하십시오.오류가 발생하는 경우 나타나는 빨간색 오류 상자 위로 커서를 이동하고 **로그**를 선택합니다. 오류가 발생한 파이프라인 단계의 로그가 나타납니다. 대부분의 오류는 잘못된 파라미터 설정으로 인해 발생합니다. | DevOps 엔지니어, 시스템 관리자 | 

## 관련 리소스
<a name="install-sap-systems-automatically-by-using-open-source-tools-resources"></a>
+ [SAP용 DevOps — SAP 설치: 2개월\$12시간](https://videos.itrevolution.com/watch/707351918/)(DevOps Enterprise Summit Video Library)

# AWS CDK를 사용하여 AWS Service Catalog 포트폴리오 및 제품 배포 자동화
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk"></a>

*Sandeep Gawande, Viyoma Sachdeva, RAJNEESH TYAGI, Amazon Web Services*

## 요약
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-summary"></a>

AWS Service Catalog를 사용하면 조직의 AWS 환경에서 사용하도록 승인된 IT 서비스 또는 *제품* 카탈로그를 중앙에서 관리할 수 있습니다. 제품 컬렉션을 *포트폴리오*라고 하며 포트폴리오에는 구성 정보도 포함됩니다. AWS Service Catalog를 사용하면 조직의 각 사용자 유형에 대해 사용자 지정 포트폴리오를 생성한 다음 해당 포트폴리오에 대한 액세스 권한을 부여할 수 있습니다. 그러면 해당 사용자는 포트폴리오 내에서 필요한 모든 제품을 신속하게 배포할 수 있습니다.

다중 리전 및 다중 계정 아키텍처와 같은 복잡한 네트워킹 인프라를 사용하는 경우 단일의 중앙 계정으로 Service Catalog 포트폴리오를 만들고 관리하는 것이 좋습니다. 이 패턴은 AWS Cloud Development Kit(AWS CDK)를 사용하여 중앙 계정에서 Service Catalog 포트폴리오를 자동으로 생성하고, 최종 사용자에게 포트폴리오에 대한 액세스 권한을 부여한 다음, 선택적으로 하나 이상의 대상 AWS 계정에서 제품을 프로비저닝하는 방법을 설명합니다. 바로 사용할 수 있는 이 솔루션은 소스 계정에 Service Catalog 포트폴리오를 생성합니다. 또한 선택적으로 AWS CloudFormation 스택을 사용하여 대상 계정의 제품을 프로비저닝하고 제품에 대한 TagOption을 구성하는 데 도움이 됩니다.
+ **AWS CloudFormation StackSets** - StackSet을 사용하여 여러 AWS 리전 및 계정에서 서비스 카탈로그 제품을 시작할 수 있습니다. 이 솔루션에서는 이 솔루션을 배포할 때 제품을 자동으로 프로비저닝할 수 있는 옵션이 있습니다. 자세한 내용은 [AWS CloudFormation StackSet 사용](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/using-stacksets.html)(Service Catalog 설명서) 및 [StackSet 개념](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-concepts.html)(CloudFormation 설명서)을 참조하십시오.
+ **TagOption 라이브러리** - TagOption 라이브러리를 사용하여 프로비전된 제품의 태그를 관리할 수 있습니다. *TagOption*은 AWS Service Catalog에서 관리되는 키 값 쌍입니다. AWS 태그는 아니지만, TagOption을 기반으로 AWS 태그를 만들기 위한 템플릿 역할을 합니다. 자세한 내용은 [TagOption 라이브러러리](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/tagoptions.html)(Service Catalog 설명서)를 참조하십시오.

## 사전 조건 및 제한 사항
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-prereqs"></a>

**사전 조건 **
+ Service Catalog 포트폴리오 관리를 위한 소스 계정으로 사용할 활성 AWS 계정.
+ 이 솔루션을 사용하여 하나 이상의 대상 계정에 제품을 프로비저닝하는 경우 대상 계정이 이미 존재하고 활성화되어 있어야 합니다.
+ AWS Service Catalog, AWS CloudFormation 및 AWS Identity and Access Management(IAM)에 접근하기 위한 AWS IAM 권한입니다.

**제품 버전**
+ AWS CDK 버전 2.27.0

## 아키텍처
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-architecture"></a>

**대상 기술 스택**
+ 중앙 집중식 AWS 계정의 Service Catalog 포트폴리오
+ 대상 계정에 배포된 Service Catalog 제품

**대상 아키텍처**

![\[AWS CDK를 사용하여 Service Catalog 포트폴리오 생성 및 대상 계정에 제품 프로비저닝.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/e8f217a7-aec4-4c85-8f6b-f91995506be0/images/1f027b82-14c3-485a-909b-1544e974b90a.png)


1. 포트폴리오(또는 *소스*) 계정에서 **config.json** 파일을 사용 사례에 맞는 AWS 계정, AWS 리전, IAM 역할, 포트폴리오 및 제품 정보로 업데이트합니다.

1. AWS CDK 애플리케이션을 배포합니다.

1. AWS CDK 애플리케이션은 배포 IAM 역할을 맡아 **config.json** 파일에 정의된 Service Catalog 포트폴리오 및 제품을 생성합니다.

   대상 계정에 제품을 배포하도록 StackSet를 구성한 경우 프로세스가 계속됩니다. 제품을 프로비저닝하도록 StackSets를 구성하지 않은 경우 프로세스가 완료됩니다.

1. AWS CDK 애플리케이션은** StackSet 관리자** 역할을 맡아 **config.json** 파일에 정의한 AWS CloudFormation 스택 세트를 배포합니다.

1. 대상 계정에서 StackSet는 **StackSet 실행** 역할을 맡고 제품을 프로비저닝합니다.

## 도구
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-tools"></a>

**서비스**
+ [AWS Cloud Development Kit(AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)는 AWS 클라우드 인프라를 코드로 정의하고 프로비저닝하는 데 도움이 되는 소프트웨어 개발 프레임워크입니다.
+ [AWS CDK 툴킷](https://docs.aws.amazon.com/cdk/latest/guide/cli.html)은 AWS CDK 앱과 상호 작용하는 데 도움이 되는 명령줄 클라우드 개발 키트입니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)을 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, 전체 AWS 계정 및 리전에서 수명 주기 전반에 걸쳐 관리할 수 있습니다.
+ [AWS Identity and Access Management(IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 누구에게 인증 및 사용 권한이 있는지 제어하여 AWS 리소스에 대한 액세스를 안전하게 관리할 수 있도록 도와줍니다.
+ [AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html)를 사용하면 AWS에 승인된 IT 서비스의 카탈로그를 중앙에서 관리할 수 있습니다. 최종 사용자는 조직에서 규정한 제약에 따라, 필요에 따라 승인된 IT 서비스만 신속하게 배포할 수 있습니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub의 [aws-cdk-servicecatalog-automation](https://github.com/aws-samples/aws-cdk-servicecatalog-automation.git) 리포지토리에서 사용할 수 있습니다. 코드 리포지토리에는 다음 파일과 폴더가 포함되어 있습니다.
+ **cdk-sevicecatalog-app** - 이 폴더에는 이 솔루션에 대한 AWS CDK 애플리케이션이 들어 있습니다.
+ **구성** - 이 폴더에는 Service Catalog 포트폴리오의 제품을 배포하기 위한 **config.json** 파일과 CloudFormation 템플릿이 들어 있습니다.
+ **config/config.json** - 이 파일에는 모든 구성 정보가 들어 있습니다. 이 파일을 업데이트하여 사용 사례에 맞게 이 솔루션을 사용자 지정합니다.
+ **구성 및 템플릿** - 이 폴더에는 서비스 센터 제품에 대한 CloudFormation 템플릿이 들어 있습니다.
+ **setup.sh** - 이 스크립트는 솔루션을 배포합니다.
+ **uninstall.sh** - 이 스크립트는 이 솔루션을 배포할 때 생성된 스택과 모든 AWS 리소스를 삭제합니다.

샘플 코드를 사용하려면 [에픽](#automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-epics) 섹션의 지침을 따르십시오.

## 모범 사례
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-best-practices"></a>
+ 이 솔루션을 배포하는 데 사용되는 IAM 역할은 [최소 권한 원칙](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)(IAM 설명서)을 준수해야 합니다.
+ [AWS CDK를 사용한 클라우드 애플리케이션 개발 모범 사례](https://aws.amazon.com/blogs/devops/best-practices-for-developing-cloud-applications-with-aws-cdk/)(AWS Blog 게시물)를 준수하십시오.
+ [AWS CloudFormation 모범 사례](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html)(CloudFormation 설명서)를 준수하십시오.

## 에픽
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-epics"></a>

### 환경을 설정합니다
<a name="set-up-your-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS CDK 툴킷을 설치합니다. | AWS CDK 툴킷이 설치되어 있는지 확인하십시오. 다음 명령을 입력하여 설치 여부를 확인하고 버전을 확인합니다. <pre>cdk --version</pre>AWS CDK가 설치되지 않은 경우에는 다음 명령을 실행하여 설치합니다.<pre>npm install -g aws-cdk@2.27.0</pre>AWS CDK 툴킷 버전이 2.27.0 이전인 경우 다음 명령을 입력하여 버전 2.27.0으로 업데이트하십시오.<pre>npm install -g aws-cdk@2.27.0 --force</pre> | AWS DevOps, DevOps 엔지니어 | 
| 리포지토리를 복제합니다. | 다음 명령을 입력하십시오. [추가 정보](#automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-additional) 섹션의 *리포지토리 복제*에서 리포지토리의 URL이 포함된 전체 명령을 복사할 수 있습니다. 이렇게 하면 GitHub의 [aws-cdk-servicecatalog-automation](https://github.com/aws-samples/aws-cdk-servicecatalog-automation) 리포지토리가 복제됩니다.<pre>git clone <repository-URL>.git</pre>그러면 대상 디렉터리에 `cd aws-cdk-servicecatalog-automation` 폴더가 생성됩니다. 다음 명령을 입력하여 이 폴더로 이동합니다.<pre>cd aws-cdk-servicecatalog-automation</pre> | AWS DevOps, DevOps 엔지니어 | 
| AWS 보안 인증을 설정합니다. | 다음 명령을 입력합니다. 이들은 스택을 배포하는 AWS 계정 및 리전을 정의하는 다음 변수를 내보냅니다.<pre>export CDK_DEFAULT_ACCOUNT=<12-digit AWS account number></pre><pre>export CDK_DEFAULT_REGION=<AWS Region></pre>AWS CDK용 AWS 보안 인증은 환경 변수를 통해 제공됩니다. | AWS DevOps, DevOps 엔지니어 | 
| 최종 사용자 IAM 역할에 대해 권한을 구성하십시오. | IAM 역할을 사용하여 포트폴리오와 포트폴리오에 포함된 제품에 대한 액세스 권한을 부여하려는 경우 역할에 **servicecatalog.amazonaws.com** 서비스 보안 주체가 수임할 수 있는 권한이 있어야 합니다. 이러한 권한을 부여하는 방법에 대한 지침은 [Service Catalog를 통한 신뢰할 수 있는 액세스 활성화](https://docs.aws.amazon.com/organizations/latest/userguide/services-that-can-integrate-servicecatalog.html#integrate-enable-ta-servicecatalog)(AWS Organizations 설명서)를 참조하십시오. | AWS DevOps, DevOps 엔지니어 | 
| StackSet에 필요한 IAM 역할을 구성합니다. | StackSet를 사용하여 대상 계정의 제품을 자동으로 프로비저닝하는 경우 스택 세트를 관리하고 실행하는 IAM 역할을 구성해야 합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.html) | AWS DevOps, DevOps 엔지니어 | 

### 솔루션 사용자 지정 및 배포
<a name="customize-and-deploy-the-solution"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CloudFormation 템플릿을 생성합니다. | 이 `config/templates` 폴더에서 포트폴리오에 포함하려는 모든 제품에 대한 CloudFormation 템플릿을 생성합니다. 더 자세한 내용은 [AWS CloudFormation 템플릿으로 작업하기](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)(CloudFormation 설명서)를 참조하십시오. | 앱 개발자, AWS DevOps, DevOps 엔지니어 | 
| 구성 파일을 사용자 지정합니다. | `config` 폴더에서 **config.json** 파일을 열고 사용 사례에 적합한 파라미터를 정의합니다. 달리 명시되지 않는 한 다음 파라미터가 요구됩니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.html)완성된 구성 파일의 예는 *추가 정보* 섹션의 [샘플 구성 파일](#automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-additional)을 참조하십시오. | 앱 개발자, DevOps 엔지니어, AWS DevOps | 
| 솔루션을 배포합니다. | 다음 명령을 입력하십시오. 그러면 AWS CDK 앱이 배포되고 **config.json** 파일에 지정된 대로 Service Catalog 포트폴리오 및 제품이 프로비저닝됩니다.<pre>sh +x setup.sh</pre> | 앱 개발자, DevOps 엔지니어, AWS DevOps | 
| 배포를 확인합니다. | 다음을 수행하여 배포가 성공했는지 확인하십시오.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.html) | 일반 AWS | 
| (선택 사항) 포트폴리오와 제품을 업데이트하십시오. | 이 솔루션을 사용하여 포트폴리오 또는 제품을 업데이트하거나 새 제품을 제공하려는 경우:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.html)예를 들면 포트폴리오를 추가하거나 리소스를 더 프로비저닝할 수 있습니다. AWS CDK 앱은 변경 사항만 구현합니다. 이전에 배포한 포트폴리오 또는 제품에 변경 사항이 없는 경우 재배포는 영향을 받지 않습니다. | 앱 개발자, DevOps 엔지니어, 일반 AWS | 

### 솔루션 정리
<a name="clean-up-the-solution"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| (선택 사항) 이 솔루션에서 배포한 AWS 리소스를 제거합니다. | 프로비전된 제품을 삭제하려면 [프로비저닝된 제품 삭제](https://docs.aws.amazon.com/servicecatalog/latest/userguide/enduser-delete.html)(Service Catalog 설명서)의 지침을 따르십시오.이 솔루션으로 생성된 리소스를 모두 삭제하려면 다음 명령을 입력하십시오.<pre>sh uninstall.sh</pre> | AWS DevOps, DevOps 엔지니어, 앱 개발자 | 

## 관련 리소스
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-resources"></a>
+ [AWS Service Catalog 구성 라이브러리](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_servicecatalog-readme.html)(AWS API 참조)
+ [StackSet 개념](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-concepts.html)(CloudFormation 설명서)
+ [AWS Service Catalog](https://aws.amazon.com/servicecatalog)(AWS 마케팅)
+ [AWS CDK와 함께 Service Catalog 사용](https://catalog.us-east-1.prod.workshops.aws/workshops/d40750d7-a330-49be-9945-cde864610de9/en-US/4-builders-devs/sc-cdk)(AWS 워크숍)

## 추가 정보
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-additional"></a>

**리포지토리 복제**

명령줄에 다음을 입력하여GitHub에서 리포지토리를 복제합니다.

```
git clone https://github.com/aws-samples/aws-cdk-servicecatalog-automation.git
```

**샘플 구성 파일**

다음은 예제 값이 포함된 샘플 **config.json** 파일입니다.

```
{
    "portfolios": [
        {
            "displayName": "EC2 Product Portfolio",
            "providerName": "User1",
            "description": "Test1",
            "roles": [
                "<Names of IAM roles that can access the products>"
            ],
            "users": [
                "<Names of IAM users who can access the products>"
            ],
            "groups": [
                "<Names of IAM user groups that can access the products>"
            ]
        },
        {
            "displayName": "Autoscaling Product Portfolio",
            "providerName": "User2",
            "description": "Test2",
            "roles": [
                "<Name of IAM role>"
            ]
        }
    ],
    "tagOption": [
        {
            "key": "Group",
            "value": [
                "finance",
                "engineering",
                "marketing",
                "research"
            ]
        },
        {
            "key": "CostCenter",
            "value": [
                "01",
                "02",
                "03",
                "04"
            ]
        },
        {
            "key": "Environment",
            "value": [
                "dev",
                "prod",
                "stage"
            ]
        }
    ],
    "products": [
        {
            "portfolioName": "EC2 Product Profile",
            "productName": "Ec2",
            "owner": "owner1",
            "productVersionName": "v1",
            "templatePath": "../../config/templates/template1.json"
        },
        {
            "portfolioName": "Autoscaling Product Profile",
            "productName": "autoscaling",
            "owner": "owner1",
            "productVersionName": "v1",
            "templatePath": "../../config/templates/template2.json",
            "deployWithStackSets": {
                "accounts": [
                    "012345678901",
                ],
                "regions": [
                    "us-west-2"
                ],
                "stackSetAdministrationRoleName": "AWSCloudFormationStackSetAdministrationRole",
                "stackSetExecutionRoleName": "AWSCloudFormationStackSetExecutionRole"
            }
        }
    ]
}
```

# AWS Service Catalog 및를 사용하여 Gitflow 환경에 핫픽스 솔루션을 배포하기 위한 동적 파이프라인 관리 자동화 AWS CodePipeline
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions"></a>

*Balaji Vedagiri, Faisal Shahdad, Shanmugam Shanker, Vivek Thangamuthu, Amazon Web Services*

## 요약
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-summary"></a>

**참고**  
AWS CodeCommit 는 더 이상 신규 고객이 사용할 수 없습니다. 의 기존 고객은 평소와 같이 서비스를 계속 사용할 AWS CodeCommit 수 있습니다. [자세히 알아보기](https://aws.amazon.com/blogs/devops/how-to-migrate-your-aws-codecommit-repository-to-another-git-provider)

이 패턴은 핫픽스 솔루션을 프로덕션 환경에 안전하게 배포하는 전용 동적 핫픽스 파이프라인을 관리하는 시나리오를 다룹니다. 솔루션은 AWS Service Catalog 포트폴리오와 제품을 사용하여 구현되고 관리됩니다. Amazon EventBridge 규칙은 이벤트 자동화에 사용됩니다. 개발자는 Service Catalog 포트폴리오 제약 조건 및 AWS Identity and Access Management (IAM) 역할을 사용하여 제한을 적용합니다. AWS Lambda 함수만 EventBridge 규칙에 의해 트리거되는 Service Catalog 제품을 시작할 수 있습니다. 이 패턴은 [추가 정보에](#automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-additional) 설명된 특정 Gitflow 설정이 있는 환경을 위해 설계되었습니다.

일반적으로 핫픽스는 프로덕션과 같은 라이브 환경에서 보고된 중요하거나 보안 문제를 해결하기 위해 배포됩니다. 핫픽스는 스테이징 및 프로덕션 환경에만 직접 배포해야 합니다. 스테이징 및 프로덕션 파이프라인은 정기적인 개발 요청에 광범위하게 사용됩니다. 품질 보증에 프로덕션으로 승격할 수 없는 지속적인 기능이 있으므로 이러한 파이프라인을 사용하여 핫픽스를 배포할 수 없습니다. 핫픽스를 릴리스하기 위해이 패턴은 다음과 같은 보안 기능을 갖춘 동적 단기 파이프라인을 설명합니다.
+ **자동 생성** - 리포지 AWS CodeCommit 토리에 핫픽스 브랜치가 생성될 때마다 핫픽스 파이프라인이 자동으로 생성됩니다.
+ **액세스 제한** - 개발자는 핫픽스 프로세스 외부에서이 파이프라인을 생성할 수 있는 액세스 권한이 없습니다.
+ **제어된 단계** - 파이프라인에는 특수 액세스 토큰이 있는 제어된 단계가 있으므로 풀 요청(PR)을 한 번만 생성할 수 있습니다.
+ **승인 단계** - 승인 단계는 파이프라인에 포함되어 관련 이해관계자로부터 필요한 승인을 받습니다.
+ **자동 삭제** - 핫픽스 파이프라인은 `hotfix`브랜치가 PR과 병합된 후 CodeCommit 리포지토리에서 삭제될 때마다 자동으로 삭제됩니다.

## 사전 조건 및 제한 사항
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-prereqs"></a>

**사전 조건 **
+ 다음과 같이 세 가지 활성 AWS 계정 이 필요합니다.
  + 도구 계정 - 지속적 통합 및 지속적 전달(CI/CD) 설정용입니다.
  + 단계 계정 - 사용자 수락 테스트용입니다.
  + 프로덕션 계정 - 비즈니스 최종 사용자의 경우.
  + (선택 사항) QA 계정 역할을 AWS 계정 할를 추가합니다. QA를 포함한 기본 파이프라인 설정과 테스트를 위한 핫픽스 파이프라인 솔루션을 모두 원하는 경우이 계정이 필요합니다.
+ 필요한 경우 기본 파이프라인을 사용하여 QA 계정에 배포할 선택적 조건이 있는 AWS CloudFormation 스택입니다. `hotfix` 브랜치를 생성하고 삭제하여 기본 파이프라인 설정 없이도 패턴을 테스트할 수 있습니다.
+ Service Catalog 제품을 생성하는 데 사용되는 CloudFormation 템플릿을 저장하는 Amazon Simple Storage Service(Amazon S3) 버킷입니다.
+ 규정 준수 요구 사항에 따라 CodeCommit 리포지토리에 대한 PR 승인 규칙을 생성합니다(리포지토리 생성 후).
+ 개발자 및 팀의 IAM 권한을 제한하면 파이프라인에서만 간접적으로 호출해야 하므로 [prcreation-lambda](https://github.com/aws-samples/dynamic_hotfix_codepipeline/blob/main/pre-requisites/lambdasetup.yaml#L55) Lambda 함수의 실행이 거부됩니다.

**제한 사항 **
+ CloudFormation 공급자는 배포 단계에서 사용되며 애플리케이션은 CloudFormation 변경 세트를 사용하여 배포됩니다. 다른 배포 옵션을 사용하려면 필요에 따라 CodePipeline 스택을 수정합니다.
+ 이 패턴은 AWS CodeBuild 및 기타 구성 파일을 사용하여 샘플 마이크로서비스를 배포합니다. 여러 워크로드 유형(예: 서버리스 워크로드)이 있는 경우 모든 관련 구성을 업데이트해야 합니다.
+ 이 패턴은 애플리케이션을 단일 AWS 리전 (예: 미국 동부(버지니아 북부) us-east-1)에 배포합니다 AWS 계정. 여러 리전에 배포하려면 명령 및 스택에서 리전 참조를 변경합니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별 AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-architecture"></a>

이 섹션의 다이어그램은 수명 주기 이벤트 생성 및 수명 주기 이벤트 삭제에 대한 워크플로를 제공합니다.

![\[수명 주기 이벤트를 생성하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/64311acc-8c0f-4734-aa1b-74345d86c752/images/3939f77c-4221-4c23-a3a1-3e8a294b2b32.png)


수명 주기 이벤트를 생성하기 위한 위의 다이어그램은 다음을 보여줍니다.

1. 개발자는 CodeCommit 리포지토리에 `hotfix-*`브랜치를 생성하여 핫픽스 관련 솔루션을 개발합니다.

1. `hotfix-*` 브랜치 생성 이벤트는 EventBridge 규칙을 통해 캡처됩니다. 이벤트 세부 정보에는 리포지토리 이름과 브랜치 이름이 포함됩니다.

1. EventBridge 규칙은 AWS Lambda 함수를 호출합니다`hotfix-lambda-function`. EventBridge 규칙은 이벤트 정보를 Lambda 함수에 입력으로 전달합니다.

1. Lambda 함수는 입력을 처리하여 리포지토리 이름과 브랜치 이름을 검색합니다. 처리된 입력에서 검색된 값으로 Service Catalog 제품을 시작합니다.

1. Service Catalog 제품에는 솔루션을 스테이지 및 프로덕션 환경에 배포하는 파이프라인 설정이 포함되어 있습니다. 파이프라인 블록에는 소스, 빌드 및 배포 단계가 포함됩니다. 또한 프로덕션 환경의 배포를 승격하기 위한 수동 승인 단계가 있습니다.

1. 소스 단계는 첫 번째 단계에서 생성된 리포지토리 및 `hotfix-*`브랜치에서 코드를 검색합니다. 코드는 아티팩트용 Amazon S3 버킷을 통해 빌드 단계로 전달됩니다. 빌드 단계에서는 `hotfix-*`브랜치에서 개발되어 Amazon Elastic Container Registry(Amazon ECR)로 푸시되는 핫픽스가 포함된 컨테이너 이미지가 생성됩니다.

1. 스테이지 환경에 배포 단계는 핫픽스가 포함된 최신 컨테이너 이미지로 Amazon Elastic Container Service(Amazon ECS)를 업데이트합니다. 핫픽스는 CloudFormation 변경 세트를 생성하고 실행하여 배포됩니다.

1. 스테이지 환경에서 배포에 성공하면 `prcreation-lambda` Lambda 함수가 간접적으로 호출됩니다. 이 Lambda 함수는 `hotfix-*`브랜치에서 리포지토리의 `develop` 및 `main`브랜치로 PR을 생성합니다. Lambda 함수는 `hotfix-*`브랜치에서 개발된 수정 사항이 백머지되고 후속 배포에 포함되도록 합니다.

1. 수동 승인 단계는 필요한 이해관계자가 수정 사항을 검토하고 프로덕션에 배포할 수 있는 승인을 제공하는 데 도움이 됩니다.

1. 프로덕션 환경에 배포 단계는 핫픽스가 포함된 최신 컨테이너 이미지로 Amazon ECS를 업데이트합니다. 핫픽스는 CloudFormation 변경 세트를 생성하고 실행하여 배포됩니다.

![\[수명 주기 이벤트를 삭제하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/64311acc-8c0f-4734-aa1b-74345d86c752/images/192aa897-bd9b-4a9f-804e-340371612b3b.png)


수명 주기 이벤트를 삭제하기 위한 앞의 다이어그램은 다음을 보여줍니다.

1. 개발자는 핫픽스를 프로덕션 환경에 성공적으로 배포한 후 `hotfix-*`브랜치를 삭제합니다.

1. `hotfix-*` 브랜치 삭제 이벤트는 EventBridge 규칙을 통해 캡처됩니다. 이벤트 세부 정보에는 리포지토리 이름과 브랜치 이름이 포함됩니다.

1. EventBridge 규칙은 Lambda 함수를 간접적으로 호출합니다. EventBridge 규칙은 이벤트 정보를 Lambda 함수에 입력으로 전달합니다.

1. Lambda 함수는 입력을 처리하여 리포지토리 이름과 브랜치 이름을 검색합니다. Lambda 함수는 전달된 입력에서 각 Service Catalog 제품을 확인한 다음 제품을 종료합니다.

1. Service Catalog 프로비저닝된 제품 종료는 해당 제품에서 이전에 생성된 파이프라인 및 관련 리소스를 삭제합니다.

**자동화 및 규모 조정**
+ 패턴에는 EventBridge 규칙과 여러 핫픽스 브랜치 생성 요청을 병렬로 처리할 수 있는 Lambda 함수가 포함됩니다. Lambda 함수는 일치하는 이벤트 규칙에 대해 Service Catalog 제품을 프로비저닝합니다.
+ 파이프라인 설정은 버전 관리 기능을 제공하는 Service Catalog 제품을 사용하여 처리됩니다. 또한 솔루션은 동일한 애플리케이션에 대한 여러 핫픽스 개발을 병렬로 처리하도록 자동으로 확장됩니다.
+ [prcreation-lambda](https://github.com/aws-samples/dynamic_hotfix_codepipeline/blob/main/pre-requisites/lambdasetup.yaml#L55) 함수는 이러한 핫픽스 변경 사항이 자동 풀 요청 생성을 통해 `main` 및 `develop`브랜치에 다시 병합되도록 합니다. 이 접근 방식은 `main` 및 브`develop`랜치를 모든 수정 사항과 함께 최신 상태로 유지하고 잠재적 코드 회귀를 방지하는 데 필수적입니다. 이 프로세스는 모든 수명이 긴 브랜치에 최신 수정 사항이 적용되도록 하여 브랜치 간 일관성을 유지하고 코드 회귀를 방지하는 데 도움이 됩니다.

## 도구
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-tools"></a>

**AWS 서비스**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, AWS 계정 및의 수명 주기 동안 리소스를 관리할 수 있습니다 AWS 리전.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 나만의 소스 제어 시스템을 관리할 필요 없이 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 버전 제어 서비스입니다. 신규 고객은 더 이상 AWS CodeCommit 를 사용할 수 없습니다. 의 기존 고객은 평소와 같이 서비스를 계속 사용할 AWS CodeCommit 수 있습니다. 자세한 내용은 [AWS CodeCommit 리포지토리를 다른 Git 공급자로 마이그레이션하는 방법을 참조하세요](https://aws.amazon.com/blogs/devops/how-to-migrate-your-aws-codecommit-repository-to-another-git-provider/).
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.
+ [Amazon Elastic Container Registry(Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)는 안전하고 확장 가능하고 신뢰할 수 있는 관리형 컨테이너 이미지 레지스트리 서비스입니다.
+ [Amazon Elastic Container Service(Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)는 클러스터에서 컨테이너를 실행, 중지 및 관리하는 데 도움이 되는 빠르고 확장 가능한 컨테이너 관리 서비스입니다.
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html)를 사용하면 암호화 키를 생성하고 제어하여 데이터를 보호할 수 있습니다.
+ [AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html)는 승인된 IT 서비스의 카탈로그를 중앙에서 관리할 수 있도록 지원합니다 AWS. 최종 사용자는 조직에서 규정한 제약에 따라, 필요에 따라 승인된 IT 서비스만 신속하게 배포할 수 있습니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.

**기타 도구**
+ [CloudFormation Linter(cfn-lint)](https://github.com/aws-cloudformation/cfn-lint)는 CloudFormation [리소스 사양과 비교하여 CloudFormation YAML 또는 JSON 템플릿을 확인하는 린터입니다](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html). 또한 리소스 속성의 유효한 값 확인 및 모범 사례 준수와 같은 다른 검사를 수행합니다.
+ [cfn-nag](https://github.com/stelligent/cfn_nag)는 CloudFormation 템플릿에서 패턴을 검색해 잠재적인 보안 문제를 파악하는 오픈 소스 도구입니다.
+ [Docker](https://www.docker.com/)는 운영 체제 수준의 가상화를 사용하여 컨테이너에 소프트웨어를 제공하는 서비스형 플랫폼(PaaS) 제품 세트입니다. 이 패턴은 Docker를 사용하여 로컬에서 컨테이너 이미지를 구축하고 테스트합니다.
+ [Git](https://git-scm.com/docs)은 오픈 소스 분산 버전 제어 시스템입니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [dynamic\$1hotfix\$1codepipeline](https://github.com/aws-samples/dynamic_hotfix_codepipeline) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-best-practices"></a>

환경에서 IAM 역할 및 서비스 제어 정책(SCP)을 검토하고 조정하여 액세스를 적절하게 제한하는지 확인합니다. 이는이 패턴에 포함된 보안 조치를 재정의할 수 있는 모든 작업을 방지하는 데 매우 중요합니다. 최소 권한 원칙을 따르고 작업을 수행하는 데 필요한 최소 권한을 부여하세요. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv) 및 [보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)를 참조하세요.

## 에픽
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-epics"></a>

### 작업 환경 설정
<a name="set-up-the-work-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리포지토리를 복제합니다. | 샘플 [리포지토리](https://github.com/aws-samples/dynamic_hotfix_codepipeline)를 작업 위치의 새 디렉터리에 복제하려면 다음 명령을 실행합니다.<pre>git clone git@github.com:aws-samples/dynamic_hotfix_codepipeline.git</pre> | DevOps | 
| CloudFormation 스택 배포를 위한 환경 변수를 내보냅니다. | 이 패턴에서 나중에 CloudFormation 스택에 입력으로 사용할 다음 환경 변수를 정의합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html)<pre>export BucketStartName=<BucketName></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html)<pre>export ProdAccount=<prodaccountnumber><br />export StageAccount=<stage/preprodaccountnumber><br />export QAAccount=<qaccountnumber><br />export ToolsAccount=<toolsaccountnumber><br />export DepRegion=<region></pre> | DevOps | 

### 에서 필요한 사전 조건 설정 AWS 계정
<a name="set-up-prerequisites-required-in-aws-accounts"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 도구 계정에서 CI/CD에 필요한 리소스를 생성합니다. | 도구 계정에 CloudFormation 스택을 배포하려면 다음 명령을 사용합니다. ( 설정에 QA 계정을 사용하지 않는 경우 `QAAccount` 파라미터를 제거합니다.)<pre>#InToolsAccount<br />aws cloudformation deploy \<br />    --template-file pre-requisites/pre-reqs.yaml \<br />    --stack-name prereqs \<br />    --parameter-overrides BucketStartName=${BucketStartName} \<br />    ApplicationName=${ApplicationName} ProdAccount=${ProdAccount} \<br />    StageAccount=${StageAccount} ToolsAccount=${ToolsAccount} \<br />    QAAccount=${QAAccount} \<br />    --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM --region ${DepRegion}</pre>CodeCommit 리포지토리와 Amazon ECR이 이전 스택에서 생성한 리소스를 기록해 둡니다. 이러한 파라미터는 다음 단계에서 파이프라인의 `main`브랜치를 설정하는 데 필요합니다. | DevOps | 
| 워크로드 계정에서 CI/CD에 필요한 리소스를 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | DevOps | 
| 워크로드 계정에 대한 액세스를 허용하도록 S3 아티팩트 버킷 정책을 업데이트합니다. | 도구 계정에서 CloudFormation 스택 사전 조건을 업데이트하려면 다음 명령을 사용하여 스테이지 및 프로덕션 워크로드 계정에 필요한 모든 권한을 추가합니다. ( 설정에 사용하지 않는 경우 `QAAccount` 파라미터를 제거합니다.)<pre>#InToolsAccount<br />aws cloudformation deploy \<br />    --template-file pre-requisites/pre-reqs.yaml \<br />    --stack-name prereqs \<br />    --parameter-overrides BucketStartName=${BucketStartName} \<br />    ApplicationName=${ApplicationName} ProdAccount=${ProdAccount} \<br />    StageAccount=${StageAccount} ToolsAccount=${ToolsAccount} \<br />    QAAccount=${QAAccount} PutPolicy=true \<br />    --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM --region ${DepRegion}</pre> | DevOps | 

### 도구 계정에서 Lambda 함수 및 Service Catalog 리소스 설정
<a name="set-up-lam-function-and-sc-resources-in-tools-account"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Service Catalog 포트폴리오 및 제품을 설정합니다. | Service Catalog 포트폴리오 및 제품을 설정하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | DevOps | 
| Lambda 함수를 설정합니다. | 이 솔루션은 다음 Lambda 함수를 사용하여 핫픽스 워크플로를 관리합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html)연결된 EventBridge 규칙을 통해 `hotfix `브랜치가 생성되거나 삭제될 때 Lambda 함수가 Service Catalog 제품을 프로비저닝하고 종료하도록 하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | DevOps | 

### 기본 브랜치를 위한 파이프라인 생성 및 워크로드 계정에 애플리케이션 배포
<a name="create-pipeline-for-main-branch-and-deploy-application-in-workload-accounts"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `main` 브랜치용 파이프라인을 설정합니다. | 기본 브랜치의 파이프라인을 설정하려면 도구 계정에서 다음 명령을 실행합니다. `MainProductId` 및의 파라미터를 `servicecatalogsetup` 스택 출력의 `MainProductArtifactId` 값으로 바꿉니다.<pre>#InToolsAccount<br />aws servicecatalog provision-product \<br />    --product-id <MainProductId> \<br />    --provisioning-artifact-id <MainProductArtifactId> \<br />    --provisioned-product-name "${ApplicationName}-main-pipeline" \<br />    --provisioning-parameters Key=CodeCommitRepoName,Value="${ApplicationName}-repository" Key=ECRRepository,Value="${ApplicationName}-app" \<br />    --region=${DepRegion}</pre> | DevOps | 
| `main` 브랜치를 사용하여 애플리케이션을 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | DevOps | 

### 핫픽스\$1 브랜치에 대한 파이프라인을 생성하고 핫픽스를 배포합니다.
<a name="create-the-pipeline-for-a-hotfix--branch-and-deploy-the-hotfix"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `hotfix-*` 브랜치를 생성하고 변경 사항을 커밋합니다. | `hotfix-*` 브랜치에 대한 파이프라인을 생성하고 핫픽스를 워크로드 계정에 배포하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | DevOps | 
| `hotfix-check1` 브랜치를 삭제합니다. | 이전에 생성한 `hotfix-check1`브랜치를 삭제하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | DevOps | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포된 리소스를 정리합니다. | 이전에 배포된 리소스를 정리하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html)<pre>##In Tools Account##<br />aws cloudformation delete-stack --stack-name servicecatalogsetup --region ${DepRegion}<br />aws cloudformation delete-stack --stack-name prlambdasetup --region ${DepRegion}<br />aws cloudformation delete-stack --stack-name prereqs --region ${DepRegion}</pre><pre>##In Workload Accounts##<br />aws cloudformation delete-stack --stack-name inframainstack --region ${DepRegion}</pre>자세한 내용은 Service Catalog 설명서의 [프로비저닝된 제품 삭제](https://docs.aws.amazon.com/servicecatalog/latest/userguide/enduser-delete.html)를 참조하세요. | DevOps | 

## 문제 해결
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| CodeCommit 리포지토리에 커밋한 변경 사항은 배포되지 않습니다. | CodeBuild 로그에서 Docker 구축 작업의 오류를 확인합니다. 자세한 내용은 [CodeBuild 설명서](https://docs.aws.amazon.com/codebuild/latest/userguide/troubleshooting.html)를 참조하세요. | 
| Service Catalog 제품이 프로비저닝되지 않습니다. | 관련 CloudFormation 스택에서 실패한 이벤트를 검토합니다. 자세한 내용은 [CloudFormation 설명서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)를 참조하세요. | 

## 관련 리소스
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-resources"></a>
+ [기본 Git 명령](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-basic-git.html)
+ [브랜치에 대한 푸시 및 병합을 제한하도록 IAM 정책 구성](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-conditional-branch.html#how-to-conditional-branch-create-policy)
+ [AWS CodeCommit 리포지토리에 연결](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)
+ [사용자에게 액세스 권한 부여](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/catalogs_portfolios_users.html)
+ [Amazon ECR 프라이빗 리포지토리에 도커 이미지 푸시](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)
+ [문제 해결 AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/troubleshooting.html)
+ [란 무엇입니까 AWS CodePipeline?](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)

## 추가 정보
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-additional"></a>

이 패턴은 CI/CD 프로세스의 개발 워크플로에 채택된 Gitflow 설정이 있는 환경을 위해 설계되었습니다. 파이프라인은 개발부터 시작하여 품질 보증(QA), 단계 및 프로덕션 환경을 거치는 배포 주기를 따릅니다. CI/CD 설정에는 다음과 같이 환경에 대한 프로모션 배포가 있는 두 개의 git 브랜치가 포함됩니다.
+ `develop` 브랜치는 개발 환경에 배포됩니다.
+ `main` 브랜치는 QA, 스테이지 및 프로덕션 환경에 배포됩니다.

이 설정에서는 새로운 기능의 활성 개발이 진행되는 동안 일반적인 배포 주기보다 더 빠르게 핫픽스 또는 보안 패치를 적용하는 것이 어렵습니다. 핫픽스 또는 보안 요청을 해결하여 라이브 환경이 제대로 작동하고 안전하게 유지되도록 하려면 전용 프로세스가 필요합니다.

그러나 다음과 같은 경우 전용 배포 프로세스 없이 다른 사용 가능한 옵션을 사용할 수 있습니다.
+ CI/CD 프로세스는 기능 및 엔드 투 엔드 테스트와 같은 자동화된 테스트로 잘 구성되어 있으므로 수동 테스트가 필요하지 않으며 프로덕션으로의 배포 지연을 방지할 수 있습니다. 그러나 자동 테스트가 CI/CD 프로세스에 잘 통합되지 않는 경우 프로덕션 환경에 작은 수정 사항을 푸시하면 개발자가 복잡해지고 번거로워질 수 있습니다. 이는 QA 환경에서 승인 및 승인을 위해 대기 중인 새로운 기능이 있을 수 있기 때문입니다. 핫픽스 또는 보안 수정은 간단한 방식으로 동시에 프로덕션 환경에 푸시할 수 없습니다.
+ 개발 팀은 새로운 기능을 프로덕션 환경에 지속적으로 배포하여 핫픽스 또는 보안 패치를 각 새로운 기능의 예약된 배포에 통합합니다. 즉, 프로덕션 환경에 대한 다음 기능 업데이트는 두 가지 구성 요소, 즉 새 기능 추가와 핫픽스 또는 보안 패치 포함으로 구성됩니다. 그러나 배포 주기가 연속적이지 않은 경우 QA 환경에서 이미 승인을 기다리고 있는 새로운 기능이 여러 개 있을 수 있습니다. 다른 버전을 관리하고 올바른 변경 사항이 다시 적용되도록 하면 복잡해지고 오류가 발생하기 쉽습니다.

**참고**  
`hotfix` 브랜치에 적절한 트리거가 설정된 AWS CodePipeline 의 [버전 2](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipeline-types.html#:~:text=V2%20type%20pipelines%20have%20the%20same%20structure)를 사용하는 경우에도 예정되지 않은 요청을 해결하기 위한 전용 프로세스가 필요합니다. 버전 2에서는 푸시 또는 풀 요청에 대한 트리거를 설정할 수 있습니다. 파이프라인의 이전 상태에 따라 실행이 대기열에 추가되거나 즉시 실행됩니다. 그러나 전용 파이프라인을 사용하면 수정 사항이 프로덕션 환경에 즉시 적용되므로 긴급한 문제가 지연 없이 해결됩니다.

# AWS CloudFormation 스택 및 관련 리소스의 삭제 자동화
<a name="automate-deletion-cloudformation-stacks-associated-resources"></a>

*SANDEEP SINGH 및 James Jacob, Amazon Web Services*

## 요약
<a name="automate-deletion-cloudformation-stacks-associated-resources-summary"></a>

[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)는 코드형 클라우드 인프라(IaC)를 관리하는 데 널리 사용되는 서비스입니다. CloudFormation을 사용할 경우 *스택*이라는 하나의 단위로 관련 리소스를 관리합니다. 스택을 생성, 업데이트, 삭제하여 리소스 모음을 생성, 업데이트 및 삭제합니다.

CloudFormation 스택에 리소스가 더 이상 필요하지 않은 경우가 있습니다. 리소스 및 구성에 따라 스택 및 관련 리소스를 삭제하는 것이 복잡할 수 있습니다. 실제 프로덕션 시스템에서는 CloudFormation이 재정의할 수 없는 충돌하는 조건이나 제한으로 인해 삭제가 실패하거나 시간이 오래 걸리는 경우가 있습니다. 모든 리소스가 효율적이고 일관된 방식으로 올바르게 삭제되도록 신중하게 계획하고 실행해야 할 수 있습니다. 이 패턴은 다음 복잡성과 관련된 CloudFormation 스택의 삭제를 관리하는 데 도움이 되는 프레임워크를 설정하는 방법을 설명합니다.
+ **삭제 방지 기능이 있는 리소스** - 일부 리소스에는 삭제 방지 기능이 활성화되어 있을 수 있습니다. 일반적인 예로는 [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 테이블과 [Amazon Simple Storage Service(Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 버킷이 있습니다. 삭제 방지 기능은 CloudFormation을 통한 삭제와 같은 자동 삭제를 방지합니다. 이러한 리소스를 삭제하려면 삭제 보호를 수동으로 또는 프로그래밍 방식으로 재정의하거나 일시적으로 비활성화해야 합니다. 계속하기 전에 이러한 리소스 삭제의 영향을 신중하게 고려해야 합니다.
+ **보존 정책이 있는 리소스** - AWS Key Management Service (AWS KMS) 키 및 Amazon S3 버킷과 같은 특정 리소스에는 삭제 요청 후 보존 기간을 지정하는 보존 정책이 있을 수 있습니다. 조직 정책 및 규제 요구 사항 준수를 유지하려면 정리 전략에서 이러한 정책을 고려해야 합니다.
+ **VPC에 연결된 Lambda 함수의 지연 삭제** - Virtual Private Cloud(VPC)에 연결된 [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 함수를 삭제하는 데는 프로세스와 관련된 여러 상호 연결된 종속성에 따라 5\$140분이 걸릴 수 있습니다. 스택을 삭제하기 전에 VPC에서 함수를 분리하면이 지연 시간을 1분 미만으로 줄일 수 있습니다.
+ **CloudFormation에서 직접 생성하지 않은 리소스** - 특정 애플리케이션 설계에서는 애플리케이션 자체 또는 스택을 통해 프로비저닝된 리소스에 의해 원래 CloudFormation 스택 외부에서 리소스가 생성될 수 있습니다. 다음은 두 가지 예제입니다.
  + CloudFormation은 사용자 데이터 스크립트를 실행하는 [Amazon Elastic Compute Cloud(Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 인스턴스를 프로비저닝할 수 있습니다. 그런 다음이 스크립트는 애플리케이션 관련 데이터를 저장하는 [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 파라미터를 생성할 수 있습니다. 이 파라미터는 CloudFormation을 통해 관리되지 않습니다.
  + CloudFormation은 로그 저장을 위한 [Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) 그룹을 자동으로 생성하는 Lambda 함수를 프로비저닝할 수 있습니다. 이 로그 그룹은 CloudFormation을 통해 관리되지 않습니다.

  이러한 리소스는 CloudFormation에서 직접 관리하지 않지만 스택이 삭제될 때 정리해야 하는 경우가 많습니다. 관리되지 않은 상태로 두면 고립되어 불필요한 리소스 소비가 발생할 수 있습니다.

이러한 가드레일은 복잡성을 유발할 수 있지만 의도적이고 중요합니다. CloudFormation이 모든 제약 조건을 재정의하고 리소스를 무차별적으로 삭제하도록 허용하면 많은 시나리오에서 유해하고 예상치 못한 결과가 발생할 수 있습니다. 그러나 환경 관리를 담당하는 DevOps 또는 클라우드 엔지니어는 특히 개발, 테스트 또는 스테이징 환경에서 이러한 제약 조건을 재정의해야 하는 경우가 있습니다.

**목표 비즈니스 성과**

이 프레임워크를 구현하면 다음과 같은 이점을 얻을 수 있습니다.
+ **비용 관리** - 엔드 투 엔드 또는 사용자 수락 테스트 환경과 같은 임시 환경을 주기적으로, 효율적으로 정리하면 리소스가 필요 이상으로 오래 실행되지 않도록 방지할 수 있습니다. 이렇게 하면 비용을 크게 줄일 수 있습니다.
+ **보안** - 오래된 리소스 또는 미사용 리소스를 자동으로 정리하면 공격 표면이 줄어들고 안전한 AWS 환경을 유지하는 데 도움이 됩니다.
+ **운영 효율성** - 정기적이고 자동화된 정리는 다음과 같은 운영 이점을 제공할 수 있습니다.
  + 이전 로그 그룹 또는 빈 Amazon S3 버킷을 제거하는 자동화된 스크립트는 환경을 깨끗하고 관리 가능하게 유지하여 운영 효율성을 개선할 수 있습니다.
  + 스택을 빠르게 삭제하고 다시 생성하면 설계 및 구현을 위한 빠른 반복이 지원되므로 보다 강력하고 복원력이 뛰어난 아키텍처로 이어질 수 있습니다.
  + 환경을 정기적으로 삭제하고 재구축하면 잠재적 문제를 식별하고 해결하는 데 도움이 될 수 있습니다. 이를 통해 인프라가 실제 시나리오를 견딜 수 있는지 확인할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="automate-deletion-cloudformation-stacks-associated-resources-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정
+ Python 버전 3.6 이상 [설치](https://www.python.org/downloads/)
+ 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)됨

**제한 사항 **
+ 이름 지정 규칙은 삭제해야 하는 리소스를 식별하는 데 사용됩니다. 이 패턴의 샘플 코드는 리소스 이름에 접두사를 사용하지만 고유한 이름 지정 규칙을 정의할 수 있습니다. 이 명명 규칙을 사용하지 않는 리소스는 식별되거나 이후에 삭제되지 않습니다.

## 아키텍처
<a name="automate-deletion-cloudformation-stacks-associated-resources-architecture"></a>

다음 다이어그램은이 프레임워크가 대상 CloudFormation 스택과 여기에 연결된 추가 리소스를 식별하는 방법을 보여줍니다.

![\[CloudFormation 스택 및 관련 리소스를 검색, 처리 및 삭제하는 단계입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/ab7c3b56-3476-41a3-8ece-68915605a546/images/a7fceb1c-d624-47b3-957d-f910ef2f44d7.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. **리소스 수집** - 자동화 프레임워크는 명명 규칙을 사용하여 모든 관련 CloudFormation 스택, Amazon Elastic Container Registry(Amazon ECR) 리포지토리, DynamoDB 테이블 및 Amazon S3 버킷을 반환합니다.
**참고**  
이 단계의 함수는 잘린 API 결과 집합을 반복하는 프로세스를 추상화하는 Boto3의 기능인 [페이지네이터](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html)를 사용합니다. 이렇게 하면 모든 리소스가 처리됩니다. 성능을 더욱 최적화하려면 [서버 측](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results) 필터링을 적용하거나 JMESPath를 사용하여 [클라이언트 측](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results-with-jmespath) 필터링을 수행하는 것이 좋습니다.

1. **사전 처리** - 자동화 프레임워크는 CloudFormation이 리소스를 삭제할 수 있도록 재정의해야 하는 서비스 제약 조건을 식별하고 해결합니다. 예를 들어 DynamoDB 테이블의 `DeletionProtectionEnabled` 설정을 로 변경합니다`False`. 명령줄 인터페이스에서 각 리소스에 대해 제약 조건을 재정의할지 묻는 메시지가 표시됩니다.

1. **스택 삭제** - 자동화 프레임워크가 CloudFormation 스택을 삭제합니다. 명령줄 인터페이스에서 스택을 삭제할지 묻는 프롬프트가 표시됩니다.

1. **사후 처리 -** 자동화 프레임워크는 스택의 일부로 CloudFormation을 통해 직접 프로비저닝되지 않은 모든 관련 리소스를 삭제합니다. 이러한 리소스 유형의 예로는 Systems Manager 파라미터와 CloudWatch 로그 그룹이 있습니다. 별도의 함수는 이러한 리소스를 수집하여 사전 처리한 다음 삭제합니다. 명령줄 인터페이스에서 각 리소스에 대해 리소스를 삭제할지 묻는 프롬프트가 표시됩니다.
**참고**  
이 단계의 함수는 잘린 API 결과 집합을 반복하는 프로세스를 추상화하는 Boto3의 기능인 [페이지네이터](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html)를 사용합니다. 이렇게 하면 모든 리소스가 처리됩니다. 성능을 더욱 최적화하려면 [서버 측](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results) 필터링을 적용하거나 JMESPath를 사용하여 [클라이언트 측](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results-with-jmespath) 필터링을 수행하는 것이 좋습니다.

**자동화 및 규모 조정**

CloudFormation 스택에 샘플 코드에 포함되지 않은 다른 리소스가 포함되어 있거나 스택에이 패턴에서 해결되지 않은 제약 조건이 있는 경우 사용 사례에 맞게 자동화 프레임워크를 조정할 수 있습니다. 리소스 수집, 사전 처리, 스택 삭제, 사후 처리와 같은 방법을 따릅니다.

## 도구
<a name="automate-deletion-cloudformation-stacks-associated-resources-tools"></a>

**AWS 서비스**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, AWS 계정 및의 수명 주기 동안 리소스를 관리할 수 있습니다 AWS 리전.
+ [CloudFormation 명령줄 인터페이스(CFN-CLI)](https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/what-is-cloudformation-cli.html)는 AWS 및 타사 확장을 개발 및 테스트한 다음 CloudFormation에서 사용할 수 있도록 등록하는 데 도움이 되는 오픈 소스 도구입니다.
+ [AWS SDK for Python (Boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)는 Python 애플리케이션, 라이브러리 또는 스크립트를와 통합하는 데 도움이 되는 소프트웨어 개발 키트입니다 AWS 서비스.

**기타 도구**
+ [클릭](https://click.palletsprojects.com/en/stable/)은 명령줄 인터페이스를 생성하는 데 도움이 되는 Python 도구입니다.
+ [Poetry](https://python-poetry.org/docs/)는 Python에서 종속성 관리 및 패키징을 위한 도구입니다.
+ [Pyenv](https://github.com/pyenv/pyenv)는 Python 버전을 관리하고 전환하는 데 도움이 되는 도구입니다.
+ [Python](https://www.python.org/)은 범용 컴퓨터 프로그래밍 언어입니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [cloudformation-stack-cleanup](https://github.com/aws-samples/cloudformation-stack-cleanup/) 리포지토리에 있습니다.

## 모범 사례
<a name="automate-deletion-cloudformation-stacks-associated-resources-best-practices"></a>
+ **쉽게 식별할 수 있도록 리소스에 태깅** - [태깅 전략](https://aws.amazon.com/solutions/guidance/tagging-on-aws/)을 구현하여 다양한 환경 및 목적으로 생성된 리소스를 식별합니다. 태그는 태그를 기반으로 리소스를 필터링하는 데 도움이 되므로 정리 프로세스를 간소화할 수 있습니다.
+ **리소스 수명 주기 설정** - 특정 기간 후에 리소스를 자동으로 삭제하도록 리소스 수명 주기를 정의합니다. 이 방법은 임시 환경이 영구적인 비용 부담이 되지 않도록 하는 데 도움이 됩니다.

## 에픽
<a name="automate-deletion-cloudformation-stacks-associated-resources-epics"></a>

### 도구 설치
<a name="install-tools"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리포지토리를 복제합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 엔지니어 | 
| Poetry를 설치합니다. | [지침](https://python-poetry.org/docs/)(Poetry 설명서)에 따라 대상 가상 환경에 Poetry를 설치합니다. | DevOps 엔지니어 | 
| 종속 항목 설치 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 엔지니어 | 
| (선택 사항) Pyenv를 설치합니다. | [지침](https://github.com/pyenv/pyenv#installation)(GitHub)에 따라 Pyenv를 설치합니다. | DevOps 엔지니어 | 

### (선택 사항) 프레임워크 사용자 지정
<a name="optional-customize-the-framework"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 대상 리소스를 수집, 사전 처리 및 삭제하는 함수를 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 엔지니어, Python | 

### 샘플 리소스 생성
<a name="create-sample-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CloudFormation 스택을 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps | 
| Systems Manager 파라미터를 생성합니다. | 다음 명령을 입력하여 CloudFormation을 통해 프로비저닝되지 않은 Systems Manager 파라미터를 생성합니다.<pre>aws ssm put-parameter \<br />  --name "/sampleforcleanup/database/password" \<br />  --value "your_db_password" \<br />  --type "SecureString" \<br />  --description "Database password for my app" \<br />  --tier "Standard" \<br />  --region "us-east-1"</pre> | DevOps | 
| Amazon S3 버킷을 생성합니다. | 다음 명령을 입력하여 CloudFormation을 통해 프로비저닝되지 않은 Amazon S3 버킷을 생성합니다.<pre>aws s3api create-bucket \<br />  --bucket samplesorcleanup-unmanagedbucket-<UniqueIdentifier> \<br />  --region us-east-1 \<br />  --create-bucket-configuration LocationConstraint=us-east-1</pre> | DevOps | 

### 샘플 리소스 삭제
<a name="delete-the-sample-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CloudFormation 스택을 삭제합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps | 
| 리소스 삭제를 검증합니다. | 출력에서 모든 샘플 리소스가 삭제되었는지 확인합니다. 샘플 출력은 이 패턴의 [추가 리소스](#automate-deletion-cloudformation-stacks-associated-resources-additional) 섹션을 참조하세요. | DevOps | 

## 관련 리소스
<a name="automate-deletion-cloudformation-stacks-associated-resources-resources"></a>
+ [스택 삭제](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html)(CloudFormation 설명서)
+ [CloudFormation 문제 해결](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)(CloudFormation 설명서)
+ [Lambda 함수에 Amazon VPC의 리소스에 대한 액세스 권한 부여](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)(Lambda 설명서)
+ [DELETE\$1FAILED 상태에서 멈춘 AWS CloudFormation 스택을 삭제하려면 어떻게 해야 합니까?](https://repost.aws/knowledge-center/cloudformation-stack-delete-failed) (AWS 지식 센터)

## 추가 정보
<a name="automate-deletion-cloudformation-stacks-associated-resources-additional"></a>

다음은 `cfncli` 명령의 샘플 출력입니다.

```
cfncli --region aus-east-1  dev cleanup-env --prefix-list sampleforcleanup                                                                                                                              
https://sts.us-east-1.amazonaws.com
Cleaning up: ['sampleforcleanup'] in xxxxxxxxxx:us-east-1
Do you want to proceed? [Y/n]: Y
No S3 buckets
No ECR repositories
No Lambda functions in VPC
The following DynamoDB tables will have their deletion protection removed:
sampleforcleanup-MyDynamoDBTable
Do you want to proceed with removing deletion protection from these tables? [Y/n]: Y
Deletion protection disabled for DynamoDB table 'sampleforcleanup-MyDynamoDBTable'.
The following CloudFormation stacks will be deleted:
sampleforcleanup-Stack
Do you want to proceed with deleting these CloudFormation stacks? [Y/n]: Y
Initiated deletion of CloudFormation stack: `sampleforcleanup-Stack`
Waiting for stack `sampleforcleanup-Stack` to be deleted...
CloudFormation stack `sampleforcleanup-Stack` deleted successfully.
The following ssm_params will be deleted:
/sampleforcleanup/database/password
Do you want to proceed with deleting these ssm_params? [Y/n]: Y
Deleted SSM Parameter: /sampleforcleanup/database/password
Cleaned up: ['sampleforcleanup']
```

# Terraform을 사용하여 Amazon Managed Grafana에서 Amazon MWAA 사용자 지정 지표의 수집 및 시각화 자동화
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics"></a>

*Faisal Abdullah and Satya Vajrapu, Amazon Web Services*

## 요약
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-summary"></a>

이 패턴에서는 Amazon Managed Grafana를 사용하여 Amazon Managed Workflows for Apache Airflow(Amazon MWAA)에서 수집하는 사용자 지정 지표를 생성하고 모니터링하는 방법을 설명합니다. Amazon MWAA는 Python으로 스크립팅된 방향성 비순환 그래프(DAG)를 사용하여 워크플로의 오케스트레이터 역할을 합니다. 이 패턴은 지난 한 시간 동안 실행된 총 DAG 수, 시간당 통과 및 실패한 DAG 수, 이러한 프로세스의 평균 기간을 비롯하여 사용자 지정 지표의 모니터링을 중점적으로 설명합니다. 이 분석은 Amazon Managed Grafana가 Amazon MWAA와 통합되어 이 환경 내 워크플로 오케스트레이션에 대한 포괄적인 모니터링 및 인사이트를 제공하는 방법을 보여줍니다.

## 사전 조건 및 제한 사항
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-prereqs"></a>

**사전 조건 **
+  AWS 서비스다음을 생성하고 관리하는 데 필요한 사용자 권한이 AWS 계정 있는 활성 :
  + AWS Identity and Access Management (IAM) 역할 및 정책
  + AWS Lambda
  + Amazon Managed Grafana
  + Amazon Managed Workflows for Apache Airflow(Amazon MWAA)
  + Amazon Simple Storage Service(Amazon S3)
  + Amazon Timestream
+ 로컬 시스템 또는 [AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/welcome.html)의 터미널일 수 있는 쉘 환경에 대한 액세스 권한
+ Git이 설치되고 최신 버전의 AWS Command Line Interface (AWS CLI)가 설치 및 구성된 쉘 환경입니다. 자세한 내용은 AWS CLI 설명서에서 [의 최신 버전 설치 또는 업데이트를 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 참조하세요.
+ 설치된 Terraform 버전: `required_version = ">= 1.6.1, < 2.0.0"` [tfswitch](https://tfswitch.warrensbox.com/)를 사용하여 다양한 버전의 Terraform 간에 전환할 수 있습니다.
+ 에 AWS IAM Identity Center 대해에서 구성된 자격 증명 소스입니다 AWS 계정. 자세한 내용은 IAM Identity Center 설명서의 [IAM Identity Center에서 ID 소스 확인](https://docs.aws.amazon.com/singlesignon/latest/userguide/prereq-identity-sources.html)을 참조하세요. 기본 IAM Identity Center 디렉터리, Active Directory 또는 Okta와 같은 외부 ID 제공업체(IdP) 중에서 선택할 수 있습니다. 자세한 내용은 [관련 리소스](#automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-resources) 섹션을 참조하세요.

**제한 사항 **
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) 섹션을 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

**제품 버전**
+ Terraform `required_version = ">= 1.6.1, < 2.0.0"`
+ Amazon Managed Grafana 버전 9.4 이상. 이 패턴은 버전 9.4에서 테스트되었습니다.

## 아키텍처
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-architecture"></a>

다음 아키텍처 다이어그램은 솔루션에 AWS 서비스 사용되는를 강조 표시합니다.

![\[Amazon MWAA 사용자 지정 지표 수집을 자동화하는 워크플로.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/3458d0a9-aee1-428a-bf2f-c357bb531c64/images/b43ed8d2-94ac-4438-913b-81c7eba8f3e0.png)


이전 다이어그램은 다음 워크플로를 단계별로 보여줍니다.

1. Amazon MWAA 내의 사용자 지정 지표는 환경 내에서 실행 중인 DAG에서 비롯됩니다. 지표는 CSV 파일 형식으로 Amazon S3 버킷에 업로드됩니다. 다음 DAG는 Amazon MWAA의 데이터베이스 쿼리 기능을 사용합니다.
   + `run-example-dag` - 이 DAG에는 하나 이상의 작업을 정의하는 샘플 Python 코드가 포함되어 있습니다. 이 코드는 7분마다 실행되며 날짜를 인쇄합니다. 날짜를 인쇄한 후 DAG에는 일정 기간 동안 실행을 대기하거나 일시 중지할 작업이 포함됩니다.
   + `other-sample-dag` - 이 DAG는 10분마다 실행되며 날짜를 인쇄합니다. 날짜를 인쇄한 후 DAG에는 일정 기간 동안 실행을 대기하거나 일시 중지할 작업이 포함됩니다.
   + `data-extract` - 이 DAG는 매시간 실행되며 Amazon MWAA 데이터베이스를 쿼리하고 지표를 수집합니다. 지표가 수집되면 이 DAG는 추가 처리 및 분석을 위해 Amazon S3 버킷에 기록합니다.

1. 데이터 처리를 간소화하기 위해 Amazon S3 이벤트에 의해 트리거될 때 Lambda 함수가 실행되므로 지표를 Timestream에 쉽게 로드할 수 있습니다.

1. Timestream은 Amazon MWAA의 모든 사용자 지정 지표가 저장되는 Amazon Managed Grafana 내의 데이터 소스로 통합됩니다.

1. 사용자는 데이터를 쿼리하고 사용자 지정 대시보드를 구성하여 주요 성과 지표를 시각화하고 Amazon MWAA 내 워크플로 오케스트레이션에 대한 인사이트를 얻을 수 있습니다.

## 도구
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-tools"></a>

**AWS 서비스**
+ [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)를 사용하면 모든 AWS 계정 및 클라우드 애플리케이션에 대한 Single Sign-On(SSO) 액세스를 중앙에서 관리할 수 있습니다.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다. 이 패턴에서는 Amazon S3 이벤트에 대한 응답으로 Python 코드를 AWS Lambda 실행하고 컴퓨팅 리소스를 자동으로 관리합니다.
+ [Amazon Managed Grafana](https://docs.aws.amazon.com/grafana/latest/userguide/what-is-Amazon-Managed-Service-Grafana.html)는 지표, 로그 및 트레이스를 즉시 쿼리, 상관관계 파악 및 시각화하는 데 사용할 수 있는 완전관리형 데이터 시각화 서비스입니다. 이 패턴은 Amazon Managed Grafana를 사용하여 지표 시각화 및 알림을 위한 대시보드를 생성합니다.
+ [Amazon Managed Workflows for Apache Airflow(Amazon MWAA)](https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html)는 Apache Airflow에 대한 관리형 오케스트레이션 서비스로 클라우드에서 데이터 파이프라인을 대규모로 설정하고 운영하는 데 사용할 수 있습니다. [Apache Airflow](https://airflow.apache.org/)는 워크플로라고 하는 프로세스 및 작업 시퀀스를 프로그래밍 방식으로 작성, 예약 및 모니터링하는 데 사용되는 오픈 소스 도구입니다. 이 패턴에서는 샘플 DAG와 지표 추출기 DAG가 Amazon MWAA에 배포됩니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다. 이 패턴에서 Amazon S3는 DAG, 스크립트 및 사용자 지정 지표를 CSV 형식으로 저장하는 데 사용됩니다.
+ [Amazon Timestream for LiveAnalytics](https://docs.aws.amazon.com/timestream/latest/developerguide/what-is-timestream.html)는 빠르고 확장 가능한 완전 관리형 특수 목적 시계열 데이터베이스로, 매일 수조 개의 시계열 데이터 포인트를 쉽게 저장하고 분석할 수 있습니다. 또한 Timestream for LiveAnalytics는 데이터 수집, 시각화, 기계 학습에 일반적으로 사용되는 서비스와 통합됩니다. 이 패턴에서는 생성된 Amazon MWAA 사용자 지정 지표를 수집하는 데 사용됩니다.

**기타 도구**
+ [HashiCorp Terraform](https://www.terraform.io/docs)은 코드를 사용하여 클라우드 인프라 및 리소스를 프로비저닝하고 관리하는 데 도움이 되는 코드형 인프라(IaC) 도구입니다. 이 패턴은 Terraform 모듈을 사용하여 AWS에서 인프라 프로비저닝을 자동화합니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub의 [visualize-amazon-mwaa-custom-metrics-grafana](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana) 리포지토리에서 사용할 수 있습니다. `stacks/Infra` 폴더에는 다음 항목이 포함되어 있습니다.
+ 모든 AWS 리소스에 대한 Terraform 구성 파일
+ `grafana` 폴더의 Grafana 대시보드 .json 파일
+ `mwaa/dags` 폴더의 Amazon Managed Workflows for Apache Airflow DAGs
+ .csv 파일을 구문 분석하고 `src` 폴더의 Timestream 데이터베이스에 지표를 저장하는 Lambda 코드
+ `templates` 폴더의 IAM 정책 .json 파일

## 모범 사례
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-best-practices"></a>

Terraform은 실제 리소스를 구성에 매핑할 수 있도록 관리형 인프라 및 구성에 대한 상태를 저장해야 합니다. 기본적으로 Terraform은 상태를 `terraform.tfstate`라는 파일에 로컬로 저장합니다. 인프라의 현재 상태를 유지하므로 Terraform 상태 파일의 안전과 무결성을 보장하는 것이 중요합니다. 자세한 내용은 Terraform 설명서의 [Remote State](https://developer.hashicorp.com/terraform/language/state/remote)를 참조하세요.

## 에픽
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-epics"></a>

### Terraform을 사용하여 인프라 배포
<a name="deploy-the-infrastructure-using-terraform"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 인프라를 배포합니다. | 솔루션 인프라를 배포하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | DevOps | 

### 배포된 인프라 리소스 검증
<a name="validate-the-deployed-infrastructure-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon MWAA 환경을 검증합니다. | Amazon MWAA 환경을 검증하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps, 데이터 엔지니어 | 
| DAG 일정을 확인합니다. | 각 DAG 일정을 보려면 **Airflow UI**의 **일정** 탭으로 이동합니다.다음 각 DAG에는 Amazon MWAA 환경에서 실행되고 사용자 지정 지표를 생성하는 사전 구성된 일정이 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)**실행** 열에서 각 DAG의 성공적인 실행 항목을 볼 수도 있습니다. | 데이터 엔지니어, AWS DevOps | 

### Amazon Managed Grafana 환경 구성
<a name="configure-the-gra-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon Managed Grafana 워크스페이스에 대한 액세스를 구성합니다. | Terraform 스크립트가 필요한 Amazon Managed Grafana 워크스페이스, 대시보드 및 지표 페이지를 생성했습니다. 이들 항목을 볼 수 있도록 액세스를 구성하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | DevOps | 
| Amazon Timestream 플러그인을 설치합니다. | Amazon MWAA 사용자 지정 지표가 Timestream 데이터베이스에 로드됩니다. Timestream 플러그인을 사용하여 Amazon Managed Grafana 대시보드로 이 지표를 시각화합니다.Timestream 플러그인을 설치하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)자세한 내용은 Amazon Managed Grafana 설명서의 [플러그인을 사용하여 워크스페이스 확장](https://docs.aws.amazon.com/grafana/latest/userguide/grafana-plugins.html#manage-plugins)을 참조하세요. | AWS DevOps, DevOps 엔지니어 | 

### Amazon Managed Grafana 대시보드에서 사용자 지정 지표 시각화
<a name="visualize-the-custom-metrics-in-the-gra-dashboard"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon Managed Grafana 대시보드를 봅니다. | Amazon Managed Grafana 워크스페이스에 수집된 지표를 보려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)대시보드에 다음 정보가 표시됩니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | DevOps | 
| Amazon Managed Grafana 대시보드를 사용자 지정합니다. | 향후 개선 사항을 적용할 수 있도록 대시보드를 사용자 지정하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)또는 [GitHub 리포지토리](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana/blob/main/stacks/infra/grafana/dashboard.json)의 `stacks/infra/grafana` 폴더에 있는 `dashboard.json` 파일에서 이 대시보드의 소스 코드를 사용할 수 있습니다. | DevOps | 

### AWS 리소스 정리
<a name="clean-up-aws-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon MWAA DAG 실행을 일시 중지합니다. | DAG 실행을 일시 중지하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps, 데이터 엔지니어 | 
| Amazon S3 버킷의 객체를 삭제합니다. | Amazon S3 버킷 **mwaa-events-bucket-\$1** 및 **mwaa-metrics-bucket-\$1**를 삭제하려면 Amazon S3 설명서의 [버킷 삭제](https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-bucket.html)에서 Amazon S3 콘솔 사용 지침을 따릅니다. | DevOps | 
| Terraform이 생성한 리소스를 폐기합니다. | Terraform이 생성한 리소스와 관련 로컬 Terraform 상태 파일을 삭제하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | DevOps | 

## 문제 해결
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| `null_resource.plugin_mgmt (local-exec): aws: error: argument operation: Invalid choice, valid choices are:` |  AWS CLI 를 [최신 버전으로](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 업그레이드합니다. | 
| 데이터 소스 로드 오류 - `Fetch error: 404 Not Found Instantiating…` | 이 오류는 간헐적으로 발생합니다. 몇 분 기다린 다음 데이터 소스를 새로 고쳐 나열된 Timestream 데이터 소스를 확인하세요. | 

## 관련 리소스
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-resources"></a>

**AWS 설명서**
+ [대시보드 및 시각화를 위한 Amazon Managed Grafana](https://docs.aws.amazon.com/prescriptive-guidance/latest/implementing-logging-monitoring-cloudwatch/amg-dashboarding-visualization.html)
+ [Okta를 사용하도록 Amazon Managed Grafana 구성](https://docs.aws.amazon.com/grafana/latest/userguide/AMG-SAML-providers-okta.html)
+ [Amazon Managed Grafana 워크스페이스와 AWS IAM Identity Center 함께 사용](https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG-SSO.html)
+ [Amazon MWAA에서 DAGs 작업](https://docs.aws.amazon.com/mwaa/latest/userguide/working-dags.html)

**AWS 비디오**
+ 다음 [비디오](https://www.youtube.com/watch?v=XX2Xcz-Ps9U)와 같이, 인증을 위해 Amazon Managed Grafana로 IAM Identity Center를 구성합니다.




[https://www.youtube-nocookie.com/embed/XX2Xcz-Ps9U?controls=0](https://www.youtube-nocookie.com/embed/XX2Xcz-Ps9U?controls=0)
+ IAM Identity Center를 사용할 수 없는 경우 다음 [비디오](https://www.youtube.com/watch?v=Z4JHxl2xpOg)와 같이 Okta와 같은 외부 ID 제공업체(IdP)를 사용하여 Amazon Managed Grafana 인증을 통합할 수도 있습니다.




[https://www.youtube-nocookie.com/embed/Z4JHxl2xpOg?controls=0](https://www.youtube-nocookie.com/embed/Z4JHxl2xpOg?controls=0)

## 추가 정보
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-additional"></a>

Amazon MWAA 환경에 대한 포괄적인 모니터링 및 알림 솔루션을 생성하여 잠재적 문제 또는 이상에 대한 사전 예방적 관리와 신속한 대응을 지원할 수 있습니다. Amazon Q에는 다음 기능이 포함됩니다.

**알림** - 사전 정의된 임계값 또는 조건을 기반으로 Amazon Managed Grafana에서 알림을 구성할 수 있습니다. 특정 지표가 지정된 임계값을 초과하거나 그 이하로 떨어질 경우 관련 이해 관계자에게 알리도록 이메일 알림을 설정합니다. 자세한 내용은 Amazon Managed Grafana 설명서에서 [Grafana 알림](https://docs.aws.amazon.com/grafana/latest/userguide/alerts-overview.html)을 참조하세요.

**통합** - 향상된 알림 기능을 위해 Amazon Managed Grafana를 OpsGenie, PagerDuty, Slack 등 다양한 서드 파티 도구와 통합할 수 있습니다. 예를 들어 웹후크를 설정하거나 API와 통합하여 Amazon Managed Grafana에서 생성된 알림을 기반으로 이러한 플랫폼에서 인시던트 및 알림을 트리거할 수 있습니다. 또한이 패턴은 AWS 리소스를 생성하기 위한 [GitHub 리포지토리](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana)를 제공합니다. 이 코드를 인프라 배포 워크플로와 추가로 통합할 수 있습니다.

# AWS CodePipeline 및 AWS CodeBuild를 사용하여 스택 세트 배포를 자동화하기
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild"></a>

*Thiyagarajan Mani, Mihir Borkar, Raghu Gowda, Amazon Web Services*

## 요약
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-summary"></a>

지속적 통합 및 지속적 전달(CI/CD) 프로세스에서는 기존의 모든 AWS 계정 및 Organizations의 조직에 추가한 새 계정에 애플리케이션을 자동으로 배포하고자 할 수 있습니다. 이 요구 사항에 맞게 CI/CD 솔루션을 설계할 때 AWS CloudFormation의 [위임된 스택 세트 관리자](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html) 기능은 관리 계정에 대한 액세스를 제한하여 보안 계층을 활성화하므로 유용합니다. 하지만 CodePipeline은 서비스 관리형 권한 모델을 사용하여 애플리케이션을 여러 계정 및 리전에 배포합니다. AWS CodePipeline은 위임된 스택 세트 관리자 기능을 지원하지 않으므로 AWS Organizations 관리 계정을 사용하여 스택 세트와 함께 배포해야 합니다.

이 패턴은 이러한 제한을 해결할 수 있는 방법을 설명합니다. 이 패턴은 AWS CodeBuild와 사용자 지정 스크립트를 사용하여 AWS CodePipeline으로 스택 세트 배포를 자동화합니다. 다음과 같은 애플리케이션 배포 활동을 자동화합니다.
+ 애플리케이션을 기존 조직 단위(OU)에 스택 세트로 배포하기
+ 애플리케이션 배포를 추가 OU 및 리전으로 확장하기 
+ 모든 또는 특정 OU나 리전에서 배포된 애플리케이션을 제거하기

## 사전 조건 및 제한 사항
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-prereqs"></a>

**사전 조건 **

이 패턴의 절차를 따르기 전에:
+ AWS Organizations 관리 계정에서 조직을 생성합니다. 지침은 [AWS Organizations 설명서](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_create.html)를 참조하십시오.
+ AWS Organizations와 CloudFormation 간의 신뢰할 수 있는 액세스를 활성화하여 서비스 관리형 권한을 사용합니다. 지침은 CloudFormation 설명서에서 [AWS Organizations를 활용하여 신뢰할 수 있는 액세스를 활성화하기](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-enable-trusted-access.html)를 참조하십시오.

**제한 사항 **

이 패턴과 함께 제공되는 코드에는 다음과 같은 제한이 있습니다. 
+ 애플리케이션에 대해 단일 CloudFormation 템플릿만 배포할 수 있습니다. 다중 템플릿 배포는 현재 지원되지 않습니다.
+ 현재 구현을 사용자 지정하려면 DevOps 전문 지식이 필요합니다.
+ 이 패턴은 AWS 키 관리 시스템(AWS KMS) 키를 사용하지 않습니다. 하지만 이 패턴에 포함된 CloudFormation 템플릿을 재구성하여 이 기능을 활성화할 수 있습니다.

## 아키텍처
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-architecture"></a>

![\[CI/CD 파이프라인 자동화 아키텍처\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/a5c47de7-9039-415d-a9e5-9de0d4c3a260/images/2dbca422-7f32-4f9c-a4aa-1f95b484b772.png)


이 CI/CD 배포 파이프라인 아키텍처는 다음을 처리합니다.
+ 애플리케이션 배포를 위한 스택 세트 관리자인 전용 CI/CD 계정에 스택 세트 배포 책임을 위임하여 관리 계정에 대한 직접 액세스를 제한합니다.
+ 서비스 관리형 권한 모델을 사용하여, 새 계정을 생성하고 OU에 매핑할 때마다 애플리케이션을 자동으로 배포합니다.
+ 환경 수준에서 모든 계정 전반적으로 애플리케이션 버전 일관성을 보장합니다.
+ 리포지토리 및 파이프라인 수준에서 여러 승인 단계를 사용하여 배포된 애플리케이션에 보안 및 거버넌스의 추가된 계층을 제공합니다.
+ CodeBuild에서 사용자 지정 빌드된 배포 스크립트를 사용하여 스택 세트 및 스택 인스턴스를 자동으로 배포하거나 제거함으로써 CodePipeline의 현재 한계를 극복합니다. 사용자 지정 스크립트로 구현된 API 직접 호출의 플로 제어 및 계층 구조에 대한 그림은 [추가 정보](#automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-additional) 섹션을 참조하십시오.
+ 개발, 테스팅, 프로덕션 환경을 위한 개별 스택 세트를 생성합니다. 또한 모든 단계에서 다중 OU와 리전을 결합하는 스택 세트를 생성할 수 있습니다. 예를 들어, 개발 배포 단계 내에서 샌드박스와 개발 OU를 결합할 수 있습니다.
+ 계정 또는 OU 목록의 하위 집합에 애플리케이션을 배포 또는 제외할 수 있도록 지원합니다.

**자동화 및 규모 조정**

이 패턴과 함께 제공된 코드를 사용하여 애플리케이션을 위한 AWS CodeCommit CodeCommit 리포지토리와 코드 파이프라인을 생성할 수 있습니다. 그런 다음 이를 OU 수준에서 여러 계정에 스택 세트로서 배포할 수 있습니다. 또한 이 코드는 승인자에게 알릴 Amazon Simple Notification Service(SNS) 주제, 필수 Identity and Access Management(IAM) 역할, 그리고 관리 계정에서 적용할 서비스 제어 정책(SCP)와 같은 구성요소를 자동화합니다.

## 도구
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-tools"></a>

**서비스**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)을 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, 전체 AWS 계정 및 리전에서 수명 주기 전반에 걸쳐 관리할 수 있습니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 나만의 소스 제어 시스템을 관리할 필요 없이 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 버전 제어 서비스입니다.
+ [AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)는 Amazon Elastic Compute Cloud(Amazon EC2) 또는 온프레미스 인스턴스, AWS Lambda 함수 또는 Amazon Elastic Container Service(Amazon ECS) 서비스에 대한 배포를 자동화합니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)는 각기 다른 소프트웨어 릴리스를 재빨리 모델링하고 구성할 수 있으며, 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.
+ [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)는 여러 계정을사용자가 생성하고 중앙에서 관리하는 단일 조직으로 통합할 수 있는 계정 관리 서비스입니다.
+ [Amazon Simple Notification Service(Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)를 사용하면 웹 서버 및 이메일 주소를 포함하여 게시자와 클라이언트 간의 메시지 교환을 조정하고 관리할 수 있습니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [automated-code-pipeline-stackset-deployment](https://github.com/aws-samples/automated-code-pipeline-stackset-deployment)리포지토리에서 사용할 수 있습니다. 폴더 구조 및 기타 세부 정보는 리포지토리에 대한 [readme 파일](https://github.com/aws-samples/automated-code-pipeline-stackset-deployment/blob/main/README.md)을 참조하십시오.

## 모범 사례
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-best-practices"></a>

이 패턴은 OU 수준에서 애플리케이션을 배포하는 동안 관리 계정에 대한 직접 액세스를 감독합니다. 파이프라인 및 리포지토리 프로세스에 다중 승인 단계를 추가하면 이 접근 방식을 사용하여 배포하는 애플리케이션과 구성 요소에 대한 추가적인 보안 및 거버넌스를 제공하는데 도움이 됩니다.

## 에픽
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-epics"></a>

### AWS Organizations에서 계정 구성
<a name="configure-accounts-in-aws-organizations"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 관리 계정에서 모든 기능을 활성화합니다. | [AWS Organizations 설명서](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html)의 지침에 따라 조직의 관리 계정에 있는 모든 기능을 활성화합니다. | AWS 관리자, 플랫폼 관리자 | 
| CI/CD 계정을 생성합니다. | 조직의 AWS Organizations에서 전용 CI/CD 계정을 생성하고, 계정에 대한 액세스를 소유하고 제어할 팀을 배정합니다. | AWS 관리자 | 
| 위임된 관리자를 추가합니다. | 관리 계정에서, 이전 단계에서 생성한 CI/CD 계정을 위임된 스택 세트 관리자로 등록합니다. 자세한 지침은 [AWS CloudFormation 설명서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html)를 참조하십시오. | AWS 관리자, 플랫폼 관리자 | 

### 애플리케이션 리포지토리 및 CI/CD 파이프라인 생성
<a name="create-an-application-repository-and-ci-cd-pipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 코드 리포지토리를 복제합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | AWS DevOps | 
| SNS 주제를 생성합니다. | GitHub 리포지토리에 제공된 `sns-template.yaml` 템플릿을 사용하여 SNS 주제를 생성하고 승인 요청을 위한 구독을 구성할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | AWS DevOps | 
| CI/CD 구성 요소에 대한 IAM 역할을 생성합니다. | GitHub 리포지토리에 제공된 `cicd-role-template.yaml` 템플릿을 사용하여 CI/CD 구성 요소에 필요한 IAM 역할 및 정책을 생성할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | AWS DevOps | 
| 애플리케이션을 위한 CodeCommit 리포지토리와 코드 파이프라인을 생성합니다. | GitHub 리포지토리에 제공된 `cicd-pipeline-template.yaml` 템플릿을 사용하여 애플리케이션용으로 CodeCommit 리포지토리와 코드 파이프라인을 생성할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | AWS DevOps | 

### 스택 세트 배포
<a name="deploy-a-stack-set"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 애플리케이션 리포지토리를 복제합니다. | 이전에 사용한 CI/CD 파이프라인 템플릿은 샘플 애플리케이션 리포지토리와 코드 파이프라인을 생성합니다. 리포지토리를 복제하고 확인하려면:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | 앱 개발자, 데이터 엔지니어 | 
| 애플리케이션 아티팩트를 추가합니다. | CloudFormation 템플릿을 사용하여 애플리케이션 리포지토리를 업데이트합니다.이 솔루션은 단일 CloudFormation 템플릿의 배포만 지원합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | 앱 개발자, 데이터 엔지니어 | 
| 배포 구성 파일을 업데이트합니다. | `deployment_config.json` 파일을 다음과 같이 업데이트 합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html)이 패턴은 배포 구성 파일에 제공하는 스택 세트 이름에 환경 이름을 추가하여 각 환경에 대한 개별 스택 세트를 생성합니다. | 앱 개발자, 데이터 엔지니어 | 
| 변경 사항을 커밋하고 스택 세트를 배포합니다. | 애플리케이션 템플릿에서 지정한 변경 사항을 커밋하고, 다음과 같은 방식으로 스택 세트를 여러 환경 단계에 병합 및 배포합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | 앱 개발자, 데이터 엔지니어 | 

## 문제 해결
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 다음과 같은 예외의 경우에 배포가 실패합니다.*템플릿 파라미터 파일의 이름을 <application name>-parameter-<evn>.json으로 변경합니다. 기본 이름은 허용되지 않습니다.* | CloudFormation 템플릿 파라미터 파일은 지정된 명명 규칙을 따라야 합니다. 파라미터 파일 이름을 업데이트하고 다시 시도합니다. | 
| 다음과 같은 예외의 경우에 배포가 실패합니다.*CloudFormation 템플릿의 이름을 <애플리케이션 이름>.yml으로 변경합니다. 기본 template.yml 또는 template.yaml은 허용되지 않습니다.* | CloudFormation 템플릿 이름은 지정된 명명 규칙을 따라야 합니다. 파일 이름을 업데이트하고 다시 시도합니다. | 
| 다음과 같은 예외의 경우에 배포가 실패합니다.*\$1환경 이름\$1 환경에 대한 유효한 CloudFormation 템플릿 및 그 파라미터 파일을 찾을 수 없습니다.* | 지정 환경에 대한 CloudFormation 템플릿 및 그 파라미터 파일에 관하여 파일 명명 규칙을 확인합니다. | 
| 다음과 같은 예외의 경우에 배포가 실패합니다.*배포 구성 파일에 잘못된 배포 작업이 제공되었습니다. 유효한 옵션은 '배포' 및 '삭제'입니다.* | 배포 구성 파일에서 `deployment_action` 파라미터에 대한 잘못된 값이 지정되었습니다. 파라미터에는 2개의 유효한 값(`deploy` 및 `delete`)이 있습니다. `deploy`(을)를 사용하여 스택 세트 및 관련 스택 인스턴스를 생성하고 업데이트합니다. 전체 스택 세트 및 관련 스택 인스턴스를 제거하려는 경우에만 `delete`(을)를 사용합니다. | 

## 관련 리소스
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-resources"></a>
+ GitHub [automated-code-pipeline-stackset-deployment](https://github.com/aws-samples/automated-code-pipeline-stackset-deployment) 리포지토리
+ [조직 내 모든 기능의 활성화](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html)(AWS Organizations 설명서)
+ [위임된 관리자 등록](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html) (AWS CloudFormation 설명서)
+ [서비스 관리형 스택 세트의 계정 수준 대상](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/account-level-targets.html) (AWS CloudFormation 설명서)

## 추가 정보
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-additional"></a>

**순서도**

다음 순서도는 스택 세트 배포를 자동화하기 위해 사용자 지정 스크립트로 구현되는 API 호출의 흐름 제어 및 계층 구조를 보여줍니다.

![\[Python 스크립트로 구현되는 흐름 제어 및 API 직접 호출\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/a5c47de7-9039-415d-a9e5-9de0d4c3a260/images/1898883a-62b7-40c2-8f08-9f2a9dda8404.png)


**샘플 배포 구성 파일**

**새 스택 세트 생성**

다음 배포 구성 파일은 `sample-stack-set`리전에서`us-east-1` 호출되는 새 스택 세트를 3개의 OU에 생성합니다.

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**기존 스택 세트를 다른 OU에 배포**

이전 예제에 표시된 구성을 배포하고 개발 환경에서`dev-org-unit-2` 호출되는 추가 OU에 스택 세트를 배포하려는 경우 배포 구성 파일은 다음과 같을 수 있습니다.

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1", "dev-org-unit-2"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**기존 스택 세트를 다른 리전에 배포**

이전 예제에 표시된 구성을 배포하고 두 개의 OU(`dev-org-unit-1` 및 `dev-org-unit-2`)에 대한 개발 환경에서 호출되는 추가 리전(`us-east-2`)에 스택 세트를 배포하려는 경우 배포 구성 파일은 다음처럼 보일 수 있습니다.

**참고**  
CloudFormation 템플릿의 리소스는 유효하고 리전 별로 달라야 합니다.

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1", "dev-org-unit-2"], 
                                        "regions": ["us-east-1", "us-east-2"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**OU 또는 리전에서 스택 인스턴스 제거**

이전 예제에 표시된 배포 구성이 배포되었다고 가정해 보겠습니다. 다음 구성 파일은 `dev-org-unit-2`OU의 두 리전에서 스택 인스턴스를 제거합니다.

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1"],
                                        "regions": ["us-east-1", "us-east-2"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"],
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"],
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

다음 구성 파일은 개발 환경의 두 OU에 대해`us-east-1` 리전에서 스택 인스턴스를 제거합니다.   

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1", "dev-org-unit-2"], 
                                        "regions": ["us-east-2"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**전체 스택 세트 삭제**

다음 배포 구성 파일은 전체 스택 세트 및 모든 관련 스택 인스턴스를 삭제합니다.

```
{
     "deployment_action": "delete",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1", "dev-org-unit-2"], 
                                        "regions": ["us-east-2"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

* ***배포에서 계정 제외**

 다음 배포 구성 파일은 `dev-org-unit-1`OU의 일부인 `111122223333`계정을 배포에서 제외합니다.

```
 {
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": ["111122223333"],
                                        "filter_type": "DIFFERENCE"
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**OU의 계정 하위 집합에 애플리케이션 배포**

다음 배포 구성 파일은 `dev-org-unit-1`OU의 3개 계정(`111122223333`, `444455556666`, `777788889999`)에만 애플리케이션을 배포합니다.

```
 {
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": ["111122223333", "444455556666", "777788889999"],
                                        "filter_type": "INTERSECTION"
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

# Cloud Custodian 및 AWS CDK를 사용하여 Systems Manager용 AWS 관리형 정책을 EC2 인스턴스 프로파일에 자동으로 연결
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk"></a>

*Ali Asfour, Aaron Lennon, Amazon Web Services*

## 요약
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-summary"></a>

Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 AWS Systems Manager와 통합하여 운영 작업을 자동화하고 가시성과 제어를 강화할 수 있습니다. Systems Manager와 통합하려면 EC2 인스턴스에 [AWS Systems Manager Agent(SSM Agent)](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html)가 설치되어 있고 `AmazonSSMManagedInstanceCore` AWS Identity and Access Management(IAM) 정책이 인스턴스 프로파일에 연결되어 있어야 합니다. 

하지만 모든 EC2 인스턴스 프로파일에 `AmazonSSMManagedInstanceCore` 정책이 연결되도록 하려는 경우, 인스턴스 프로파일이 없는 새 EC2 인스턴스나 인스턴스 프로파일은 있지만 `AmazonSSMManagedInstanceCore` 정책이 없는 EC2 인스턴스를 업데이트하는 데 어려움을 겪을 수 있습니다. 또한 여러 Amazon Web Services(AWS) 계정과 AWS 리전에 이 정책을 추가하는 것도 어려울 수 있습니다.

이 패턴은 AWS 계정에 세 가지 [클라우드 관리](https://cloudcustodian.io/) 정책을 배포하여 이러한 문제를 해결하는 데 도움이 됩니다.
+ 첫 번째 Cloud Custodian 정책은 인스턴스 프로파일은 있지만 `AmazonSSMManagedInstanceCore` 정책이 없는 기존 EC2 인스턴스를 확인합니다. 그러면 `AmazonSSMManagedInstanceCore` 정책이 첨부됩니다. 
+ 두 번째 Cloud Custodian 정책은 인스턴스 프로파일이 없는 기존 EC2 인스턴스를 확인하고 `AmazonSSMManagedInstanceCore` 정책이 연결된 기본 인스턴스 프로파일을 추가합니다.
+ 세 번째 클라우드 관리 정책은 계정에 [AWS Lambda 함수](https://cloudcustodian.io/docs/aws/lambda.html)를 생성하여 EC2 인스턴스 및 인스턴스 프로파일 생성을 모니터링합니다. 이렇게 하면 EC2 인스턴스가 생성될 때 `AmazonSSMManagedInstanceCore` 정책이 자동으로 연결됩니다.

이 패턴은 [AWS DevOps](https://aws.amazon.com/devops/) 도구를 사용하여 별도의 컴퓨팅 환경을 프로비저닝하지 않고도 클라우드 관리 정책을 다중 계정 환경에 지속적으로 대규모로 배포할 수 있습니다. 

## 사전 조건 및 제한 사항
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-prereqs"></a>

**사전 조건 **
+ 두 개 이상의 활성 AWS 계정. 한 계정은 *보안 계정*이고 다른 계정은 *멤버 계정*입니다.
+ 보안 계정에서 AWS 리소스를 프로비저닝할 수 있는 권한. 이 패턴은 [관리자 권한](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html)을 사용하지만 조직의 요구 사항 및 정책에 따라 권한을 부여해야 합니다.
+ 보안 계정에서 구성원 계정으로 IAM 역할을 수임하고 필요한 IAM 역할을 생성하는 기능. 자세한 내용은 IAM 설명서의 [IAM 역할을 사용한 AWS 계정 간 액세스 권한 위임](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)을 참조하십시오.
+ 
**중요**  
AWS Command Line Interface(AWS CLI), 설치 및 구성됨. 테스트 목적으로 `aws configure` 명령을 사용하거나 환경 변수를 설정하여 AWS CLI를 구성할 수 있습니다. 프로덕션 환경에서는 권장되지 않으므로 이 계정에는 최소 권한 액세스 권한만 부여하는 것이 좋습니다. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)를 참조하십시오.
+ `devops-cdk-cloudcustodian.zip` 파일(첨부)이 로컬 컴퓨터에 다운로드됩니다.
+ Python에 대해 숙지.
+ 필수 도구(Node.js, AWS Cloud Development Kit(AWS CDK) 및 Git)가 설치 및 구성됩니다. `devops-cdk-cloudcustodian.zip` 파일의 `install-prerequisites.sh` 파일을 사용하여 이러한 도구를** **설치할 수 있습니다.** **이 파일을 루트 권한으로 실행해야 합니다. 

**제한 사항 **
+ 프로덕션 환경에서도 이 패턴을 사용할 수 있지만 모든 IAM 역할 및 정책이 조직의 요구 사항 및 정책을 충족하는지 확인하십시오. 

**패키지 버전**
+ Cloud Custodian 버전 0.9 이상
+ TypeScript 버전 3.9.7 이상
+ Node.js 버전 14.15.4 이상
+ `npm` 버전 7.6.1 이상
+ AWS CDK 버전 1.96.0 이상

## 아키텍처
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-architecture"></a>

![\[AWS CodePipeline workflow with CodeCommit, CodeBuild, and deployment to member accounts.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/169a7bde-789e-4ebd-b4ca-80eb28ac9927/images/8ec0b6b4-d4b0-42e5-833d-24d1e6098fd9.png)


 

이 다이어그램은 다음 워크플로를 보여줍니다.

1. 클라우드 관리 정책은 보안 계정의 AWS CodeCommit 리포지토리로 푸시됩니다. Amazon CloudWatch Events 규칙은 AWS CodePipeline 파이프라인을 자동으로 시작합니다.

1. 파이프라인은 CodeCommit에서 가장 최신 코드를 가져와서 AWS CodeBuild에서 처리하는 지속적 통합 및 지속적 전달(CI/CD) 파이프라인의 지속적 통합 부분으로 전송합니다.

1. CodeBuild는 Cloud Custodian 정책에 대한 정책 구문 검증을 포함한 전체 DevSecOps 작업을 수행하고 이러한 정책을 `--dryrun` 모드에서 실행하여 식별된 리소스를 확인합니다.

1. 오류가 없는 경우 다음 작업에서는 관리자에게 변경 사항을 검토하고 구성원 계정에 배포를 승인하도록 알립니다.

**기술 스택**
+ AWS CDK
+ CodeBuild
+ CodeCommit
+ CodePipeline
+ IAM
+ Cloud Custodian 

**자동화 및 규모 조정**

AWS CDK Pipelines 모듈은 CodePipeline을 사용하여 CodeBuild로 소스 코드의 구축 및 테스트를 오케스트레이션하는 CI/CD 파이프라인을 제공하고, AWS CloudFormation 스택을 통한 AWS 리소스 배포도 지원합니다. 이 패턴은 조직의 모든 멤버 계정 및 리전에 사용할 수 있습니다. `Roles creation` 스택을 확장하여 멤버 계정에 다른 IAM 역할을 배포할 수도 있습니다. 

## 도구
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-tools"></a>
+ [AWS Cloud Development Kit(AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)는 코드에서 클라우드 인프라를 정의하고 AWS CloudFormation을 통해 프로비저닝하기 위한 소프트웨어 개발 프레임워크입니다.
+ [AWS Command Line Interface(AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 쉘에서 명령을 사용하여 AWS 서비스와 상호 작용할 수 있는 오픈 소스 도구입니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 클라우드상의 완전 관리형 빌드 서비스입니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 자산을 비공개로 저장하고 관리하는 데 사용할 수 있는 버전 제어 서비스입니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스에 필요한 단계를 모델링, 시각화 및 자동화하는 데 사용할 수 있는 지속적 전달 서비스입니다.
+ [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 사용자의 액세스를 안전하게 제어할 수 있게 지원하는 웹 서비스입니다.
+ [Cloud Custodian](https://cloudcustodian.io/)은 많은 조직이 퍼블릭 클라우드 계정을 관리하는 데 사용하는 도구와 스크립트를 하나의 오픈소스 도구로 통합합니다.
+ [Node.js](https://nodejs.org/en/)는Google Chrome의 V8 JavaScript 엔진에 구축된 JavaScript 런타임입니다.

**코드**

이 패턴에 사용되는 모듈, 계정 함수, 파일, 배포 명령의 자세한 목록은 `devops-cdk-cloudcustodian.zip` 파일(첨부)의 `README` 파일을 참조하십시오.

## 에픽
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-epics"></a>

### AWS CDK로 파이프라인 설정
<a name="set-up-the-pipeline-with-aws-cdk"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CodeCommit 리포지토리를 설정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html)이에 대한 자세한 내용은 AWS CodeCommit 설명서의 [CodeCommit 리포지토리 생성](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html)을 참조하십시오. | 개발자 | 
| 필수 도구를 설치합니다. | 이 `install-prerequisites.sh` 파일을 사용하여 Amazon Linux에 필요한 모든 도구를 설치할 수 있습니다. AWS CLI는 사전 설치되어 제공되므로 여기에 포함되지 않습니다.이에 대한 자세한 내용은 AWS CDK 설명서의 [AWS CDK 시작](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)의 [사전 조건](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html#getting_started_prerequisites) 섹션을 참조하십시오. | 개발자 | 
| 필수 AWS CDK 패키지를 설치합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html)다음 패키지는 AWS CDK에 필요하며 `requirements.txt` 파일에 포함되어 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html) | 개발자 | 

### 환경 구성
<a name="configure-your-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 필수 변수를 업데이트하십시오. | CodeCommit 리포지토리의 루트 폴더에서 `vars.py` 파일을 열고 다음 변수를 업데이트합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html) | 개발자 | 
| account.yml 파일을 멤버 계정 정보로 업데이트하십시오. | 여러 계정에 대해 [c7n-org Cloud Custodian](https://cloudcustodian.io/docs/tools/c7n-org.html) 도구를 실행하려면 `accounts.yml` 구성 파일을 리포지토리의 루트에 배치해야 합니다. 다음은 AWS용 Cloud Custodian 구성 파일 예제입니다.<pre>accounts:<br />- account_id: '123123123123'<br />  name: account-1<br />  regions:<br />  - us-east-1<br />  - us-west-2<br />  role: arn:aws:iam::123123123123:role/CloudCustodian<br />  vars:<br />    charge_code: xyz<br />  tags:<br />  - type:prod<br />  - division:some division<br />  - partition:us<br />  - scope:pci</pre> | 개발자 | 

### AWS 계정 부트스트랩
<a name="bootstrap-the-aws-accounts"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 보안 계정을 부트스트랩합니다. | 다음 명령을 실행하여 `cloudcustodian_stack` 애플리케이션을 통해 `deploy_account`를 부트스트랩합니다.<pre>cdk bootstrap -a 'python3 <br />cloudcustodian/cloudcustodian_stack.py</pre> | 개발자 | 
| 옵션 1 - 멤버 계정을 자동으로 부트스트랩합니다. | `vars.py`파일에서 `cdk_bootstrap_member_accounts` 변수를 `True`로 설정하면 `member_accounts` 변수에 지정된 계정이 파이프라인에 의해 자동으로 부트스트랩됩니다.필요한 경우 보안 계정에서 위임할 수 있고 AWS CDK를 부트스트랩하는 데 필요한 권한이 있는 IAM 역할로 `*cdk_bootstrap_role*`을 업데이트할 수 있습니다.`member_accounts ` 변수에 추가된 새 계정은 파이프라인에 의해 자동으로 부트스트랩되므로 필요한 역할을 배포할 수 있습니다. | 개발자 | 
| 옵션 2 - 멤버 계정을 수동으로 부트스트랩합니다. | 이 방법을 사용하는 것은 권장되지 않지만 다음 명령을 실행하여 `cdk_bootstrap_member_accounts` 값을 `False`로 설정하고 이 단계를 수동으로 수행할 수 있습니다.<pre>$ cdk bootstrap -a 'python3 cloudcustodian/member_account_roles_stack.py' \<br /><br />--trust {security_account_id} \<br /><br />--context assume-role-credentials:writeIamRoleName={role_name} \<br /><br />--context assume-role-credentials:readIamRoleName={role_name} \<br /><br />--mode=ForWriting \<br /><br />--context bootstrap=true \<br /><br />--cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess</pre>보안 계정에서 위임할 수 있고 AWS CDK를 부트스트랩하는 데 필요한 권한을 가진 IAM 역할의 이름으로 `{security_account_id}` 및 `{role_name}` 값을 업데이트해야 합니다.또한 다른 접근 방식, 예를 들어 AWS CloudFormation을 사용하여 멤버 계정을 부트스트랩할 수도 있습니다. 이에 대한 자세한 내용은 AWS CDK 설명서의 [부트스트래핑](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)을 참조하십시오. | 개발자 | 

### AWS CDK 스택 배포
<a name="deploy-the-aws-cdk-stacks"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 멤버 계정에서 IAM 역할을 생성합니다. | 다음 명령을 실행하여 `member_account_roles_stack` 스택을 배포하고 멤버 계정에 IAM 역할을 생성합니다.<pre>cdk deploy --all -a 'python3 cloudcustodian/member_account_roles_stack.py' --require-approval never</pre> | 개발자 | 
| Cloud Custodian 파이프라인 스택을 배포하십시오. | 다음 명령을 실행하여 보안 계정에 배포되는 Cloud Custodian `cloudcustodian_stack.py` 파이프라인을 생성합니다.<pre>cdk deploy -a 'python3 cloudcustodian/cloudcustodian_stack.py'</pre> | 개발자 | 

## 관련 리소스
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-resources"></a>
+ [AWS SDK 시작하기](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)

## 첨부
<a name="attachments-169a7bde-789e-4ebd-b4ca-80eb28ac9927"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/169a7bde-789e-4ebd-b4ca-80eb28ac9927/attachments/attachment.zip) 파일의 압축을 풉니다.

# AWS CDK를 사용하여 마이크로서비스용 CI/CD 파이프라인 및 Amazon ECS 클러스터 자동으로 구축
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk"></a>

*Varsha Raju, Amazon Web Services*

## 요약
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-summary"></a>

이 패턴은 Amazon Elastic Container Service(Amazon ECS)에서 마이크로서비스를 구축하고 배포하기 위한 지속적 통합 및 지속적 전송(CI/CD) 파이프라인과 기본 인프라를 자동으로 생성하는 방법을 설명합니다. 조직에 CI/CD, 마이크로서비스 및 DevOps의 이점을 보여주기 위해 개념 증명 CI/CD 파이프라인을 설정하려는 경우 이 접근 방식을 사용할 수 있습니다. 또한 이 접근 방식을 사용하여 초기 CI/CD 파이프라인을 만든 다음 조직의 요구 사항에 따라 사용자 지정하거나 변경할 수 있습니다. 

이 패턴의 접근 방식은 각각 Virtual Private Cloud(VPC)와 두 개의 가용 영역에서 실행되도록 구성된 Amazon ECS 클러스터를 포함하는 프로덕션 환경과 비프로덕션 환경을 생성합니다. 이러한 환경은 모든 마이크로서비스에서 공유되며 그런 다음 각 마이크로서비스에 대한 CI/CD 파이프라인을 생성합니다. 이러한 CI/CD 파이프라인은 AWS CodeCommit의 소스 리포지토리에서 변경 내용을 가져와서 변경 사항을 자동으로 구축한 다음 프로덕션 및 비프로덕션 환경에 배포합니다. 파이프라인이 모든 단계를 성공적으로 완료하면 URL을 사용하여 프로덕션 및 비프로덕션 환경에서 마이크로서비스에 액세스할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-prereqs"></a>

**사전 조건 **
+ 활성 Amazon Web Services(AWS) 계정
+ `starter-code.zip` 파일을 포함하는 기존 Amazon Simple Storage Service(S3) 버킷(첨부)
+ 계정에 설치 및 구성된 AWS Cloud Development Kit(AWS CDK) 이에 대한 자세한 내용은 AWS CDK 설명서의 [AWS CDK 시작](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) 섹션을 참조하십시오.
+ Python 3 및 `pip`, 설치 및 구성됨. 자세한 내용은 [Python 설명서](https://www.python.org/)를 참조하십시오.
+ AWS CodePipeline, AWS CodeBuild, CodeCommit, Amazon Elastic Container Registry (Amazon ECR), Amazon ECS, 및 AWS Fargate 숙지.
+ Docker에 대한 숙지.
+ CI/CD 및 DevOps에 대한 이해

**제한 사항 **
+ 일반 AWS 계정 한도가 적용됩니다. 자세한 내용은 AWS General Reference 설명서의 [AWS service quotas](https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html)을 참조하십시오.

**제품 버전**
+ 이 코드는 Node.js 버전 16.13.0 및 AWS CDK 버전 1.132.0을 사용하여 테스트되었습니다.

## 아키텍처
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-architecture"></a>

![\[AWS 클라우드 architecture diagram showing CI/CD pipeline and deployment to production and non-production VPCs.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/05ac2cad-408e-433f-8150-0a2b71f63cfd/images/6fa3dbef-88de-4b3f-ae41-dfa90256a058.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 애플리케이션 개발자가 CodeCommit 리포지토리에 코드를 커밋합니다.

1. 파이프라인이 시작됩니다.

1. CodeBuild는 도커 이미지를 빌드하여 Amazon ECR 리포지토리에 푸시합니다.

1. CodePipeline은 비프로덕션 Amazon ECS 클러스터의 기존 Fargate 서비스에 새 이미지를 배포합니다.

1. Amazon ECS는 Amazon ECR 리포지토리의 이미지를 비프로덕션 Fargate 서비스로 가져옵니다.

1. 테스트는 비프로덕션 URL을 사용하여 수행됩니다.

1. 릴리스 관리자가 프로덕션 배포를 승인합니다.

1. CodePipeline은 프로덕션 Amazon ECS 클러스터의 기존 Fargate 서비스에 새 이미지를 배포합니다.

1. Amazon ECS는 Amazon ECR 리포지토리의 이미지를 프로덕션 Fargate 서비스로 가져옵니다.

1. 프로덕션 사용자는 프로덕션 URL을 사용하여 기능에 액세스합니다.

**기술 스택  **
+ AWS CDK
+ CodeBuild
+ CodeCommit 
+ CodePipeline
+ Amazon ECR 
+ Amazon ECS 
+ Amazon VPC

**자동화 및 규모 조정**

이 패턴의 접근 방식을 사용하여 공유 AWS CloudFormation 스택에 배포된 마이크로서비스를 위한 파이프라인을 생성할 수 있습니다. 자동화를 통해 각 VPC에 Amazon ECS 클러스터를 한 개 이상 생성할 수 있으며 공유 Amazon ECS 클러스터에 배포된 마이크로서비스를 위한 파이프라인을 생성할 수도 있습니다. 하지만 이를 위해서는 새 리소스 정보를 파이프라인 스택에 대한 입력으로 제공해야 합니다.

## 도구
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-tools"></a>
+ [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/home.html) - AWS Cloud Development Kit(AWS CDK)는 코드로 클라우드 인프라를 정의하고 AWS CloudFormation을 통해 이를 프로비저닝하기 위한 소프트웨어 개발 프레임워크입니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) - AWS CodeBuild는 클라우드상의 완전 관리형 빌드 서비스입니다. CodeBuild는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포 준비가 완료된 아티팩트를 생성합니다.
+ [AWS CodeCommit CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) – AWS CodeCommit CodeCommit은 클라우드에 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 소스 코드 제어 서비스입니다. CodeCommit을 사용하면 자체 소스 제어 시스템을 관리하거나 인프라 규모 조정에 대해 걱정할 필요가 없습니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) - AWS CodePipeline은 소프트웨어 릴리스에 필요한 단계를 모델링, 시각화, 자동화하는 데 사용할 수 있는 지속적 전달 서비스입니다. 소프트웨어 릴리스 프로세스를 구성하는 여러 단계를 신속하게 모델링하고 구성할 수 있습니다. CodePipeline은 소프트웨어 변경 사항을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.
+ [Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) - Amazon Elastic Container Service(Amazon ECS)는 클러스터에서 컨테이너를 실행, 중지 및 관리하기 위해 사용하는 컨테이너 관리 서비스로서 확장성과 속도가 뛰어납니다. AWS Fargate에서 관리하는 서버리스 인프라에서 작업 및 서비스를 실행할 수 있습니다. 또는 인프라에 대한 더 세부적인 제어를 위해, 관리하는 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스의 클러스터에서 작업과 서비스를 실행할 수 있습니다.
+ [Docker](https://www.docker.com/) - Docker를 사용하면 개발자가 모든 애플리케이션을 가볍고 휴대가 간편하며 자급자족할 수 있는 컨테이너로 포장, 배송 및 실행할 수 있습니다.

**코드 **

이 패턴의 코드는 `cicdstarter.zip` 및 `starter-code.zip` 파일(첨부)에서 확인할 수 있습니다.

## 에픽
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-epics"></a>

### 환경을 설정합니다
<a name="set-up-your-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS CDK의 작업 디렉터리를 설정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) | AWS DevOps, 클라우드 인프라 | 

### 공유 인프라 생성
<a name="create-the-shared-infrastructure"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 공유 인프라를 만드십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) | AWS DevOps, 클라우드 인프라 | 
| AWS CloudFormation 스택을 모니터링합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) | AWS DevOps, 클라우드 인프라 | 
| AWS CloudFormation 스택을 테스트하십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html)두 VPC의 ID와 두 VPC 모두의 기본 보안 그룹에 대한 보안 그룹 ID를 모두 기록해야 합니다. | AWS DevOps, 클라우드 인프라 | 

### 마이크로서비스를 위한 CI/CD 파이프라인 생성
<a name="create-a-ci-cd-pipeline-for-a-microservice"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 마이크로서비스를 위한 인프라를 만드십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html)디렉터리의 `cdk.json` 파일을 사용하여 두 명령 모두에 값을 제공할 수도 있습니다. | AWS DevOps, 클라우드 인프라 | 
| AWS CloudFormation 스택을 모니터링합니다. | AWS CloudFormation 콘솔을 열고 `myservice1-cicd-stack` 스택의 진행 상황을 모니터링합니다. 결국 상태가 `CREATE_COMPLETE`로 변경됩니다*.* | AWS DevOps, 클라우드 인프라 | 
| AWS CloudFormation 스택을 테스트하십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) |  | 
| 파이프라인을 사용합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) | AWS DevOps, 클라우드 인프라 | 
| 각 마이크로서비스에 대해 이 에픽을 반복하십시오. | 이 에픽의 작업을 반복하여 각 마이크로서비스에 대한 CI/CD 파이프라인을 생성하십시오. | AWS DevOps, 클라우드 인프라 | 

## 관련 리소스
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-resources"></a>
+ [AWS CDK를 통해 Python 사용](https://docs.aws.amazon.com/cdk/latest/guide/work-with-cdk-python.html) 
+ [AWS CDK Python 참조](https://docs.aws.amazon.com/cdk/api/latest/python/index.html)
+ [AWS CDK를 사용하여 AWS Fargate 서비스 생성](https://docs.aws.amazon.com/cdk/latest/guide/ecs_example.html)

## 추가 정보
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-additional"></a>

**`cdk synth` 명령**

```
cdk synth --context aws_account=<aws_account_number> --context aws_region=<aws_region> --context vpc_nonprod_id=<id_of_non_production VPC> --context vpc_prod_id=<id_of_production_VPC> --context ecssg_nonprod_id=< default_security_group_id_of_non-production_VPC> --context ecssg_prod_id=<default_security_group_id_of_production_VPC> --context code_commit_s3_bucket_for_code=<S3 bucket name> --context code_commit_s3_object_key_for_code=<Object_key_of_starter_code> --context microservice_name=<name_of_microservice>
```

**`cdk deploy `명령**

```
cdk deploy --context aws_account=<aws_account_number> --context aws_region=<aws_region> --context vpc_nonprod_id=<id_of_non_production_VPC> --context vpc_prod_id=<id_of_production_VPC> --context ecssg_nonprod_id=< default_security_group_id_of_non-production_VPC> --context ecssg_prod_id=<default_security_group_id_of_production_VPC> --context code_commit_s3_bucket_for_code=<S3 bucket name> --context code_commit_s3_object_key_for_code=<Object_key_of_starter_code> --context microservice_name=<name_of_microservice> 
```

## 첨부
<a name="attachments-05ac2cad-408e-433f-8150-0a2b71f63cfd"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/05ac2cad-408e-433f-8150-0a2b71f63cfd/attachments/attachment.zip) 파일의 압축을 풉니다.

# GitHub Actions 및 Terraform을 사용하여 Docker 이미지를 빌드하고 Amazon ECR에 푸시
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform"></a>

*Ruchika Modi, Amazon Web Services*

## 요약
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-summary"></a>

이 패턴은 재사용 가능한 GitHub 워크플로를 생성하여 Dockerfile을 빌드하고 결과 이미지를 Amazon Elastic Container Registry(Amazon ECR)로 푸시하는 방법을 설명합니다. 이 패턴은 Terraform 및 GitHub Actions를 사용하여 Dockerfiles의 빌드 프로세스를 자동화합니다. 이를 통해 인적 오류의 가능성을 최소화하고 배포 시간을 크게 줄일 수 있습니다.

GitHub 리포지토리 기본 브랜치로의 GitHub 푸시 작업을 실행하면 리소스 배포가 시작됩니다. 이 워크플로는 GitHub 조직과 리포지토리 이름의 조합을 기반으로 고유한 Amazon ECR 리포지토리를 생성합니다. 그런 다음, Dockerfile 이미지를 Amazon ECR 이미지 리포지토리로 푸시합니다.

## 사전 조건 및 제한 사항
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-prereqs"></a>

**사전 조건**
+ 활성 상태의 AWS 계정.
+ 활성 GitHub 계정
+ [GitHub 리포지토리](https://docs.github.com/en/get-started/quickstart/create-a-repo)
+ Terraform 버전 1 이상 [설치 및 구성](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli).
+ [Terraform 백엔드](https://developer.hashicorp.com/terraform/language/settings/backends/s3)의 Amazon Simple Storage Service(S3) 버킷.
+ Terraform 상태 잠금 및 일관성을 위한 [Amazon DynamoDB](https://www.googleadservices.com/pagead/aclk?sa=L&ai=DChcSEwjO95K9xqCCAxW-KIMDHfOvD7IYABADGgJzZg&gclid=EAIaIQobChMIzveSvcagggMVviiDAx3zrw-yEAAYASADEgJYWfD_BwE&ohost=www.google.com&cid=CAASJuRoKjv_llGjIU3liZ4T2IRecPqw0dVHSvjZ7bee1lvcc36K_lO_&sig=AOD64_1b294pq65HiFN-T1YxQAuXmRu_hw&adurl&ved=2ahUKEwjhiY29xqCCAxUgzjgGHRu6CAIQqyQoAnoECAkQDQ) 테이블. 이 테이블에는 유형이 `String`인 `LockID`라는 파티션 키가 있어야 합니다. 이 키가 구성되지 않은 경우 상태 잠금이 비활성화됩니다.
+ Terraform용 Amazon S3 백엔드를 설정할 수 있는 권한이 있는 AWS Identity and Access Management(IAM) 역할. 구성 지침은 [Terraform 설명서](https://developer.hashicorp.com/terraform/language/settings/backends/s3#assume-role-configuration)를 참조하세요.

**제한 사항**

이 재사용 가능한 코드는 GitHub Actions에서만 테스트되었습니다.

## 아키텍처
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-architecture"></a>

**대상 기술 스택**
+ Amazon ECR 리포지토리
+ GitHub Actions
+ Terraform

**대상 아키텍처 **

![\[워크플로 - 재사용 가능한 GitHub 워크플로를 생성하여 Dockerfile을 빌드하고 이미지를 Amazon ECR로 푸시합니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/c39c110e-cbe5-459e-a0aa-de27e884fb10/images/298e0e16-3054-49b7-8695-db510e0df2df.png)


다이어그램은 다음을 보여 줍니다.

1. 사용자가 GitHub 리포지토리에 Dockerfile 및 Terraform 템플릿을 추가합니다.

2. 템플릿을 추가하면 GitHub 작업 워크플로가 시작됩니다.

3. 이 워크플로는 Amazon ECR 리포지토리가 존재하는지 확인합니다. 이 리포지토리가 없으면 GitHub 조직 및 리포지토리 이름을 기반으로 리포지토리를 생성합니다.

4. 이 워크플로는 Dockerfile을 빌드하고 이미지를 Amazon ECR 리포지토리로 푸시합니다.

## 도구
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-tools"></a>

**Amazon 서비스**
+ [Amazon Elastic Container Registry(Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)는 안전하고 확장성이 있고 신뢰할 수 있는 관리형 컨테이너 레지스트리 서비스입니다.

**기타 도구**
+ [GitHub Actions](https://docs.github.com/en/actions)는 GitHub 플랫폼에 통합되어 GitHub 리포지토리 내에서 워크플로를 생성, 공유 및 실행하도록 지원합니다. GitHub Actions를 사용하여 코드 빌드, 테스트 및 배포와 같은 작업을 자동화할 수 있습니다.
+ [Terraform](https://developer.hashicorp.com/terraform/intro)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 인프라를 생성하고 관리하는 데 도움이 됩니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [Docker ECR 작업 워크플로](https://github.com/aws-samples/docker-ecr-actions-workflow) 리포지토리에서 사용할 수 있습니다.
+ GitHub 작업을 생성하면 Docker 워크플로 파일이 이 리포지토리의 `/.github/workflows/` 폴더에 저장됩니다. 이 솔루션의 워크플로는 [workflow.yaml](https://github.com/aws-samples/docker-ecr-actions-workflow/blob/main/.github/workflows/workflow.yaml) 파일에 있습니다.
+ `e2e-test` 폴더는 참조 및 테스트를 위한 샘플 Dockerfile을 제공합니다.

## 모범 사례
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-best-practices"></a>
+ Dockerfiles 작성 모범 사례는 [Docker 설명서](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)를 참조하세요.
+ [Amazon S3용 VPC 엔드포인트](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)를 사용합니다. VPC 엔드포인트는 프라이빗 IP 주소를 통해 Amazon ECR API에 비공개로 액세스할 수 있는 기술인 AWS PrivateLink로 구동됩니다. Fargate 시작 유형을 사용하는 Amazon ECS 작업의 경우, 작업에 퍼블릭 ID 주소를 할당할 필요 없이 Amazon ECR에서 프라이빗 이미지를 가져오는 작업이 가능합니다.

## 에픽
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-epics"></a>

### OIDC 공급자 및 GitHub 리포지토리 설정
<a name="set-up-the-oidc-provider-and-github-repository"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| OpenID Connect를 구성합니다. | OpenID Connect(OIDC) 공급자를 생성합니다. 이 작업에 사용되는 IAM 역할에 대한 신뢰 정책에 있는 공급자를 사용합니다. 지침은 GitHub 설명서의 [Amazon Web Services에서 OpenID Connect 구성](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)을 참조하세요. | AWS 관리자, AWS DevOps, 일반 AWS | 
| GitHub 리포지토리를 복제합니다. | GitHub [Docker ECR 작업 워크플로](https://github.com/aws-samples/docker-ecr-actions-workflow) 리포지토리를 로컬 폴더에 복제합니다.<pre>$git clone https://github.com/aws-samples/docker-ecr-actions-workflow</pre> | DevOps 엔지니어 | 

### GitHub 재사용 가능 워크플로 사용자 지정 및 Docker 이미지 배포
<a name="customize-the-github-reusable-workflow-and-deploy-the-docker-image"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Docker 워크플로를 시작하는 이벤트를 사용자 지정합니다. | 이 솔루션의 워크플로는 [workflow.yaml](https://github.com/aws-samples/docker-ecr-actions-workflow/blob/main/.github/workflows/workflow.yaml)에 있습니다. 이 스크립트는 현재 `workflow_dispatch` 이벤트를 수신할 때 리소스를 배포하도록 구성되어 있습니다. 이벤트를 `workflow_call`로 변경하고 다른 상위 워크플로에서 워크플로를 호출하여 이 구성을 사용자 지정할 수 있습니다. | DevOps 엔지니어 | 
| 워크플로를 사용자 지정합니다. | [workflow.yaml](https://github.com/aws-samples/docker-ecr-actions-workflow/blob/main/.github/workflows/workflow.yaml) 파일은 재사용 가능한 동적 GitHub 워크플로를 생성하도록 구성됩니다. 이 파일을 편집하여 기본 구성을 사용자 지정하거나, `workflow_dispatch` 이벤트를 사용하여 수동으로 배포를 시작하는 경우 GitHub Actions 콘솔에서 입력 값을 전달할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform.html) | DevOps 엔지니어 | 
| Terraform 템플릿을 배포합니다. | 이 워크플로는 구성한 GitHub 이벤트에 따라 Amazon ECR 리포지토리를 생성하는 Terraform 템플릿을 자동으로 배포합니다. 이 템플릿은 [Github 리포지토리의 루트](https://github.com/aws-samples/docker-ecr-actions-workflow/tree/main)에서 `.tf` 파일로 사용할 수 있습니다. | AWS DevOps, DevOps 엔지니어 | 

## 문제 해결
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| Amazon S3 및 DynamoDB를 Terraform 원격 백엔드로 구성할 때 발생하는 문제 또는 오류. | [Terraform 설명서](https://developer.hashicorp.com/terraform/language/settings/backends/s3)의 지침에 따라 원격 백엔드 구성에 필요한 Amazon S3 및 DynamoDB 리소스 권한을 설정합니다. | 
| `workflow_dispatch` 이벤트로 워크플로를 실행하거나 시작할 수 없습니다. | `workflow_dispatch` 이벤트에서 배포하도록 구성된 워크플로는 해당 워크플로가 기본 브랜치에도 구성된 경우에만 작동합니다. | 

## 관련 리소스
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-resources"></a>
+ [워크플로 재사용](https://docs.github.com/en/actions/using-workflows/reusing-workflows)(GitHub 설명서)
+ [워크플로 트리거](https://docs.github.com/en/actions/using-workflows/triggering-a-workflow)(GitHub 설명서)

# AWS CodeCommit, AWS CodePipeline, AWS Device Farm을 사용하여 iOS 앱을 구축하고 테스트할 수 있습니다.
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm"></a>

*Abdullahi Olaoye, Amazon Web Services*

## 요약
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-summary"></a>

이 패턴은 AWS CodePipeline을 사용하여 AWS의 실제 디바이스에서 iOS 애플리케이션을 구축하고 테스트하는 지속적 통합 및 지속적 전송(CI/CD) 파이프라인을 생성하는 단계를 설명합니다. 이 패턴은 AWS CodeCommit을 사용하여 애플리케이션 코드를 저장하고, Jenkins 오픈 소스 도구를 사용하여 iOS 애플리케이션을 구축하며, AWS Device Farm을 사용하여 실제 디바이스에서 구축된 애플리케이션을 테스트합니다. 이 세 단계는 AWS CodePipeline을 사용하여 파이프라인에서 함께 오케스트레이션됩니다.

이 패턴은 AWS DevOps 블로그의 [AWS DevOps 및 모바일 서비스를 사용하여 iOS 및 iPadOS 앱을 구축하고 테스트](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/)하는 게시물을 기반으로 합니다. 자세한 지침은 블로그 게시물을 참조하세요.

## 사전 조건 및 제한 사항
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정
+ Apple 개발자 계정
+ 빌드 서버(macOS)
+ [Xcode](https://developer.apple.com/xcode/) 버전 11.3(빌드 서버에 설치 및 설정)
+ 워크스테이션에 [설치](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html) 및 [구성된 ](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) AWS Command Line Interface(AWS CLI)
+ [Git](https://git-scm.com/docs)에 대한 기본 지식

**제한 사항 **
+ 애플리케이션 빌드 서버는 macOS를 실행해야 합니다.
+ CodePipeline이 원격으로 연결하여 빌드를 시작할 수 있도록 빌드 서버에 퍼블릭 IP 주소가 있어야 합니다.

## 아키텍처
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-architecture"></a>

**소스 기술 스택  **
+ 물리적 기기에서 시뮬레이터 또는 수동 테스트를 사용하는 온프레미스 iOS 애플리케이션 빌드 프로세스

**‬대상 기술 스택  **
+ 애플리케이션 소스 코드를 저장하는 AWS CodeCommit 리포지토리
+ Xcode를 사용하여 애플리케이션을 빌드하기 위한 Jenkins 서버
+ 실제 디바이스에서 애플리케이션을 테스트하기 위한 AWS Device Farm 디바이스 풀

**대상 아키텍처 **

사용자가 소스 리포지토리에 변경 사항을 커밋하면 파이프라인(AWS CodePipeline)이 소스 리포지토리에서 코드를 가져와 Jenkins 빌드를 시작하고 애플리케이션 코드를 Jenkins에 전달합니다. 빌드 후 파이프라인은 빌드 아티팩트를 검색하고 AWS Device Farm 작업을 시작하여 디바이스 풀에서 애플리케이션을 테스트합니다.

 

![\[CI/CD 파이프라인은 AWS CodePipeline을 사용하여 실제 디바이스에서 iOS 애플리케이션을 구축하고 테스트합니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/06fbd82f-4aed-441c-818c-5f89f56af78e/images/0ae3d7b6-b40c-44ef-9580-8c8266c3d841.png)


## 도구
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-tools"></a>
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 빠르고 안정적인 애플리케이션 및 인프라 업데이트를 위해 릴리스 파이프라인을 자동화하는 데 사용할 수 있는 완전관리형 지속적 제공 서비스입니다. CodePipeline은 정의한 릴리스 모델을 기반으로 코드 변경이 있을 때마다 릴리스 프로세스의 구축, 테스트 및 배포 단계를 자동화합니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 안전한 Git 기반 리포지토리를 호스팅하는 완전관리형 소스 제어 서비스입니다. 이를 통해 팀은 안전하고 확장성이 뛰어난 에코시스템에서 코드 작업을 쉽게 협업할 수 있습니다. CodeCommit을 사용하면 자체 소스 제어 시스템을 운영하거나 인프라 규모 조정에 대해 걱정할 필요가 없습니다.
+ [AWS Device Farm](https://docs.aws.amazon.com/devicefarm/latest/developerguide/welcome.html)은 테스트 인프라를 프로비저닝하고 관리할 필요 없이 광범위한 데스크톱 브라우저와 실제 모바일 디바이스에서 테스트하여 웹 및 모바일 앱의 품질을 개선할 수 있는 애플리케이션 테스트 서비스입니다.
+ [Jenkins](https://www.jenkins.io/)는 개발자가 그의 소프트웨어를 빌드, 테스트 및 배포할 수 있는 오픈 소스 자동화 서버입니다.

## 에픽
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-epics"></a>

### 빌드 환경 설정
<a name="set-up-the-build-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| macOS를 실행하는 빌드 서버에 Jenkins를 설치합니다. | Jenkins가 애플리케이션을 빌드하는 데 사용되므로 먼저 빌드 서버에 Jenkins 명령을 사용해야 합니다. 이 작업과 후속 작업에 대한 자세한 지침을 보려면 [Building and testing iOS and iPadOS apps with AWS DevOps and mobile services](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/) AWS Blog 게시물과 이 패턴 끝에 있는 [관련 리소스](#build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-resources) 섹션의 기타 리소스를 참조하세요. | DevOps | 
| Jenkins를 설정합니다. | 화면에 표시되는 지시 사항에 따라 Jenkins를 구성합니다. | DevOps | 
| Jenkins용 AWS CodePipeline 플러그인을 설치합니다. | Jenkins가 AWS CodePipeline 서비스와 상호 작용하려면 Jenkins 서버에 이 플러그인을 설치해야 합니다. | DevOps | 
| Jenkins 프리스타일 프로젝트를 생성하세요. | Jenkins에서 프리스타일 프로젝트를 만드세요. 트리거 및 기타 빌드 구성 옵션을 지정하도록 프로젝트를 구성합니다. | DevOps | 

### AWS Device Farm을 구성합니다.
<a name="configure-aws-device-farm"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Device Farm 프로젝트를 생성합니다. | AWS Device Farm 콘솔을 엽니다. 테스트용 프로젝트와 디바이스 풀을 생성합니다. 지침은 블로그 게시물을 참조하세요. | 개발자 | 

### 소스 리포지토리 구성
<a name="configure-the-source-repository"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CodeCommit 리포지토리를 생성합니다. | 소스 코드를 저장할 리포지토리를 만드세요. | DevOps | 
| 리포지토리에 애플리케이션 코드를 커밋합니다. | 생성한 CodeCommit 리포지토리에 연결합니다. 로컬 시스템에서 리포지토리로 코드를 푸시합니다. | DevOps | 

### 파이프라인 구성
<a name="configure-the-pipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS CodePipeline에서 파이프라인을 생성합니다. | AWS CodePipeline 콘솔을 열고 파이프라인을 생성합니다. 파이프라인은 CI/CD 프로세스의 모든 단계를 조정합니다. 지침은 AWS Blog 게시물 [Building and testing iOS and iPadOS apps with AWS DevOps and mobile services](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/)를 참조하세요. | DevOps | 
| 파이프라인에 테스트 단계를 추가합니다. | 테스트 단계를 추가하고 이를 AWS Device Farm과 통합하려면 파이프라인을 편집합니다. | DevOps | 
| 파이프라인을 시작합니다. | 파이프라인 및 CI/CD 프로세스를 시작하려면 **릴리스 변경**을 선택합니다. | DevOps | 

### 애플리케이션 테스트 결과 보기
<a name="view-application-test-results"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 테스트 결과를 확인합니다. | AWS Device Farm 콘솔에서 생성한 프로젝트를 선택하고 테스트 결과를 검토합니다. 콘솔에는 각 테스트의 세부 정보가 표시됩니다. | 개발자 | 

## 관련 리소스
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-resources"></a>

**이 패턴에 사용되는 단계별 지침**
+ [AWS DevOps 및 모바일 서비스를 사용하여 iOS 및 iPadOS 앱을 구축하고 테스트합니다](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/)(AWS DevOps 블로그 게시물).

**AWS Device Farm 구성**
+ [AWS Device Farm 콘솔](https://console.aws.amazon.com/devicefarm)

**소스 리포지토리 구성**
+ [AWS CodeCommit 리포지토리 생성](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html)
+ [AWS CodeCommit 리포지토리에 연결](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)

**파이프라인 구성**
+ [AWS CodePipeline 콘솔](https://console.aws.amazon.com/codesuite/codepipeline/home)

**추가 리소스**
+ [AWS CodePipeline 설명서](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)
+ [AWS CodeCommit 설명서](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)
+ [AWS Device Farm 설명서](https://docs.aws.amazon.com/devicefarm/latest/developerguide/welcome.html)
+ [Jenkins 설명서](https://www.jenkins.io/doc/)
+ [macOS에 Jenkins 설치](https://www.jenkins.io/download/weekly/macos/)
+ [Jenkins용 AWS CodePipeline 플러그인](https://plugins.jenkins.io/aws-codepipeline/)
+ [Xcode 설치](https://developer.apple.com/xcode/)
+ AWS CLI [설치](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html) 및 [구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ [Git 설명서](https://git-scm.com/docs)

# Amazon EKS에서 실행되는 애플리케이션에 대한 상호 TLS 인증을 구성합니다.
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks"></a>

*Mahendra Revanasiddappa, Amazon Web Services*

## 요약
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-summary"></a>

인증서 기반 상호 전송 계층 보안(TLS)은 서버와 클라이언트 간에 양방향 피어 인증을 제공하는 선택적 TLS 구성 요소입니다. 상호 TLS를 사용하는 경우 클라이언트는 세션 협상 프로세스 중에 X.509 인증서를 제공해야 합니다. 서버는 이 인증서를 사용하여 클라이언트를 식별하고 인증합니다.

상호 TLS는 사물 인터넷(IoT) 애플리케이션을 위한 일반적인 요구 사항이며 [오픈 뱅킹](https://docs.aws.amazon.com/wellarchitected/latest/financial-services-industry-lens/open-banking.html)과 같은 B2B 애플리케이션 또는 표준에 사용할 수 있습니다.

이 패턴은 NGINX 인그레스 컨트롤러를 사용하여 Amazon Elastic Kubernetes Service(Amazon EKS) 클러스터에서 실행되는 애플리케이션의 상호 TLS를 구성하는 방법을 설명합니다. 인그레스 리소스에 주석을 달아 NGINX 인그레스 컨트롤러에 내장된 상호 TLS 기능을 활성화할 수 있습니다. NGINX 컨트롤러의 상호 TLS 주석에 대한 자세한 내용은 Kubernetes 설명서의 [클라이언트 인증서 인증](https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#client-certificate-authentication)을 참조하세요.

**중요**  
이 패턴은 자체 서명된 인증서를 사용합니다. 이 패턴은 테스트 클러스터에만 사용하고 프로덕션 환경에서는 사용하지 않는 것이 좋습니다. 프로덕션 환경에서 이 패턴을 사용하려는 경우, [AWS 프라이빗 인증 기관(AWS 프라이빗 CA)](https://docs.aws.amazon.com/privateca/latest/userguide/PcaWelcome.html) 또는 기존 공개 키 인프라(PKI) 표준을 사용하여 프라이빗 인증서를 발급할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-prereqs"></a>

**사전 조건 **
+ 활성 Amazon Web Services(AWS) 계정
+ 기존 Amazon EKS 클러스터.
+ macOS, Linux 또는 Windows에 설치 및 구성된 AWS Command Line Interface(AWS CLI) 버전 1.7 이상.
+ Amazon EKS 클러스터에 액세스하도록 설치 및 구성된 kubectl 명령줄 유틸리티. 이에 대한 자세한 내용은 Amazon EKS 설명서의 [kubectl 설치](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)를 참조하세요.
+ 애플리케이션을 테스트하는 데 사용할 기존 도메인 이름 시스템(DNS) 이름.

**제한 사항 **
+ 이 패턴은 자체 서명된 인증서를 사용합니다. 이 패턴은 테스트 클러스터에만 사용하고 프로덕션 환경에서는 사용하지 않는 것이 좋습니다.

## 아키텍처
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-architecture"></a>

![\[Amazon EKS에서 실행 중인 애플리케이션에 대한 상호 TLS 인증 구성\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/ae2761e3-7ed2-4c2a-ba54-a4ddce8a1e7e/images/cefc60f9-2f29-4052-b7ae-df4eb6395e1c.png)


**기술 스택**
+ Amazon EKS
+ Amazon Route 53
+ Kubectl

## 도구
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-tools"></a>
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)는 자체 Kubernetes 컨트롤 플레인 또는 노드를 설치하거나 유지 관리할 필요 없이 AWS에서 Kubernetes를 실행하는 데 도움이 됩니다.
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html)은 가용성과 확장성이 뛰어난 DNS 웹 서비스입니다.
+ [Kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)은 Amazon EKS 클러스터와 상호 작용하는 데 사용하는 명령줄 유틸리티입니다.

## 에픽
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-epics"></a>

### 자체 서명된 인증서 생성
<a name="generate-the-self-signed-certificates"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  CA 키 및 인증서를 생성합니다. | 다음 명령을 실행하여 인증 기관(CA) 키와 인증서를 생성합니다.<pre>openssl req -x509 -sha256 -newkey rsa:4096 -keyout ca.key -out ca.crt -days 356 -nodes -subj '/CN=Test Cert Authority'</pre> | DevOps 엔지니어 | 
| 서버 키와 인증서를 생성하고 CA 인증서로 서명합니다. | 서버 키와 인증서를 생성하고 다음 명령을 실행하여 CA 인증서로 서명합니다.<pre>openssl req -new -newkey rsa:4096 -keyout server.key -out server.csr -nodes -subj '/CN= <your_domain_name> ' && openssl x509 -req -sha256 -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt</pre>반드시 기존 도메인 이름으로 `<your_domain_name>`을 변경합니다. | DevOps 엔지니어 | 
|  클라이언트 키와 인증서를 생성하고 CA 인증서로 서명합니다. | 다음 명령을 실행하여 클라이언트 키와 인증서를 생성하고 CA 인증서로 서명합니다.<pre>openssl req -new -newkey rsa:4096 -keyout client.key -out client.csr -nodes -subj '/CN=Test' && openssl x509 -req -sha256 -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 02 -out client.crt</pre> | DevOps 엔지니어 | 

### NGINX 인그레스 컨트롤러 배포
<a name="deploy-the-nginx-ingress-controller"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon EKS 클러스터에 NGINX 인그레스 컨트롤러를 배포합니다. | 다음 명령으로 NGINX 인그레스 컨트롤러를 배포합니다.<pre>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.7.0/deploy/static/provider/aws/deploy.yaml</pre> | DevOps 엔지니어 | 
|  NGINX 인그레스 컨트롤러 서비스가 실행 중인지 확인합니다. | 다음 명령을 사용하여 NGINX 인그레스 컨트롤러 서비스가 실행 중인지 확인합니다.<pre>kubectl get svc -n ingress-nginx</pre>서비스 주소 필드에 Network Load Balancer의 도메인 이름이 포함되어 있는지 확인합니다. | DevOps 엔지니어 | 

### Amazon EKS 클러스터에 네임스페이스를 생성하여 상호 TLS를 테스트합니다.
<a name="create-a-namespace-in-the-amazon-eks-cluster-to-test-mutual-tls"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon EKS 클러스터에서 네임스페이스를 생성합니다. | 다음 명령을 실행하여 Amazon EKS 클러스터에서 `mtls`로 호출되는 네임스페이스를 생성합니다.<pre>kubectl create ns mtls</pre>그러면 샘플 애플리케이션이 배포되어 상호 TLS를 테스트할 수 있습니다. | DevOps 엔지니어 | 

### 샘플 애플리케이션의 배포 및 서비스 생성
<a name="create-the-deployment-and-service-for-the-sample-application"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| mtls 네임스페이스에서 Kubernetes 배포 및 서비스를 생성합니다. | `mtls.yaml`이라는 이름의 파일을 만듭니다. 다음 코드를 파일에 붙여 넣습니다.<pre>kind: Deployment<br />apiVersion: apps/v1<br />metadata:<br />  name: mtls-app<br />  labels:<br />    app: mtls<br />spec:<br />  replicas: 1<br />  selector:<br />    matchLabels:<br />      app: mtls<br />  template:<br />    metadata:<br />      labels:<br />        app: mtls<br />    spec:<br />      containers:<br />      - name: mtls-app<br />        image: hashicorp/http-echo<br />        args:<br />          - "-text=mTLS is working"<br /><br /><br />---<br /><br />kind: Service<br />apiVersion: v1<br />metadata:<br />  name: mtls-service<br />spec:<br />  selector:<br />    app: mtls<br />  ports:<br />    - port: 5678 # Default port for image</pre> 다음 명령을 실행하여 `mtls` 네임스페이스에서 Kubernetes 배포 및 서비스를 생성합니다.<pre>kubectl create -f mtls.yaml -n mtls</pre> | DevOps 엔지니어 | 
| Kubernetes 배포가 생성되었는지 확인합니다. | 다음 명령을 실행하여 배포가 생성되었고 사용 가능한 상태인 포드가 하나 있는지 확인합니다.<pre>kubectl get deploy -n mtls</pre> | DevOps 엔지니어 | 
| Kubernetes 서비스가 생성되었는지 확인합니다. | 다음 명령을 실행하여 Kubernetes 서비스가 생성되었는지 확인합니다.<pre>kubectl get service -n mtls</pre> | DevOps 엔지니어 | 

### mtls 네임스페이스에 보안 암호 생성
<a name="create-a-secret-in-the-mtls-namespace"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 인그레스 리소스의 보안 암호를 생성합니다. | 다음 명령어를 실행하여 이전에 생성한 인증서를 사용하여 NGINX 인그레스 컨트롤러용 보안 암호를 생성합니다.<pre>kubectl create secret generic mtls-certs --from-file=tls.crt=server.crt --from-file=tls.key=server.key --from-file=ca.crt=ca.crt -n mtls </pre>보안 암호에는 서버를 식별하는 클라이언트용 서버 인증서와 클라이언트 인증서를 확인하는 서버용 CA 인증서가 있습니다. | DevOps 엔지니어 | 

### mtls 네임스페이스에 인그레스 리소스를 생성합니다.
<a name="create-the-ingress-resource-in-the-mtls-namespace"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| mtls 네임스페이스에 인그레스 리소스를 생성합니다. | `ingress.yaml`이라는 이름의 파일을 만듭니다. 다음 코드를 파일에 붙여넣습니다(기존 도메인 이름을 `<your_domain_name>`으로 대체).<pre>apiVersion: networking.k8s.io/v1<br />kind: Ingress<br />metadata:<br />  annotations:<br />    nginx.ingress.kubernetes.io/auth-tls-verify-client: "on"<br />    nginx.ingress.kubernetes.io/auth-tls-secret: mtls/mtls-certs<br />  name: mtls-ingress<br />spec:<br />  ingressClassName: nginx<br />  rules:<br />  - host: "*.<your_domain_name>"<br />    http:<br />      paths:<br />      - path: /<br />        pathType: Prefix<br />        backend:<br />          service:<br />            name: mtls-service<br />            port:<br />              number: 5678<br />  tls:<br />  - hosts:<br />    - "*.<your_domain_name>"<br />    secretName: mtls-certs</pre>다음 명령을 실행하여 `mtls` 네임스페이스에 인그레스 리소스를 생성합니다.<pre>kubectl create -f ingress.yaml -n mtls</pre>즉, NGINX 인그레스 컨트롤러는 트래픽을 샘플 애플리케이션으로 라우팅할 수 있습니다. | DevOps 엔지니어 | 
| 인그레스 리소스가 생성되었는지 확인합니다. | 다음 명령을 실행하여 인그레스 리소스가 생성되었는지 확인합니다.<pre>kubectl get ing -n mtls</pre>인그레스 리소스의 주소에 NGINX 인그레스 컨트롤러용으로 생성된 로드 밸런서가 표시되는지 확인합니다. | DevOps 엔지니어 | 

### 호스트 이름이 로드 밸런서를 가리키도록 DNS를 구성합니다.
<a name="configure-dns-to-point-the-hostname-to-the-load-balancer"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| NGINX 인그레스 컨트롤러의 로드 밸런서를 가리키는 CNAME 레코드를 생성합니다. | AWS Management Console에 로그인하고 Amazon Route 53 콘솔을 열고 `mtls.<your_domain_name>`을 NGINX 인그레스 컨트롤러의 로드 밸런서로 가리키는 정식 이름(CNAME) 레코드를 생성합니다.자세한 내용은 Route 53 설명서의 [Route 53 콘솔을 사용하여 레코드 생성](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)을 참조하세요. | DevOps 엔지니어 | 

### 애플리케이션 테스트
<a name="test-the-application"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 인증서 없이 상호 TLS 설정을 테스트할 수 있습니다. | 다음 명령을 실행합니다.<pre>curl -k https://mtls.<your_domain_name> </pre>"400 No required SSL certificate was sent"라는 오류 응답을 받아야 합니다. | DevOps 엔지니어 | 
| 인증서를 사용하여 상호 TLS 설정을 테스트합니다. | 다음 명령을 실행합니다.<pre>curl -k https://mtls.<your_domain_name> --cert client.crt --key client.key</pre>“mTLS is working”이라는 응답을 받아야 합니다. | DevOps 엔지니어 | 

## 관련 리소스
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-resources"></a>
+ [Amazon Route 53 콘솔을 사용하여 레코드 생성](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)
+ [Amazon EKS에서 NGINX 인그레스 컨트롤러와 함께 Network Load Balancer 사용](https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/)
+ [클라이언트 인증서 인증](https://kubernetes.github.io/ingress-nginx/examples/auth/client-certs/)

# 를 사용하여 Amazon WorkSpaces 애플리케이션 리소스 생성 자동화 AWS CloudFormation
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation"></a>

*Ram Kandaswamy, Amazon Web Services*

## 요약
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-summary"></a>

이 패턴은 [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 템플릿을 AWS 클라우드 사용하여에서 [Amazon WorkSpaces 애플리케이션](https://aws.amazon.com/workspaces/applications/) 리소스 생성을 자동화하는 코드 샘플과 단계를 제공합니다. 이 패턴은 CloudFormation 스택을 사용하여 이미지 빌더, 이미지, 플릿 인스턴스 및 스택을 포함한 WorkSpaces 애플리케이션 리소스 생성을 자동화하는 방법을 보여줍니다. 데스크톱 또는 애플리케이션 전송 모드를 사용하여 HTML5-compliant 브라우저에서 최종 사용자에게 WorkSpaces 애플리케이션 애플리케이션을 스트리밍할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정
+ WorkSpaces 애플리케이션 이용 약관 수락
+ 플릿, 스택 및 [이미지 빌더](https://docs.aws.amazon.com/appstream2/latest/developerguide/managing-image-builders.html)와 같은 WorkSpaces 애플리케이션 리소스에 대한 기본 지식 [https://docs.aws.amazon.com/appstream2/latest/developerguide/managing-stacks-fleets.html](https://docs.aws.amazon.com/appstream2/latest/developerguide/managing-stacks-fleets.html) 

**제한 사항 **
+ WorkSpaces 애플리케이션 인스턴스가 생성된 후에는 해당 인스턴스와 연결된 [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) (IAM) 역할을 수정할 수 없습니다.
+ 해당 이미지 빌더가 생성된 후에는 WorkSpaces Applications 이미지 빌더 인스턴스의 속성(예: [서브넷](https://docs.aws.amazon.com/vpc/latest/userguide/configure-subnets.html#subnet-basics) 또는 [보안 그룹](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html))을 수정할 수 없습니다.

## 아키텍처
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-architecture"></a>

다음 다이어그램은 CloudFormation 템플릿을 사용하여 WorkSpaces 애플리케이션 리소스 생성을 자동화하는 방법을 보여줍니다.

![\[WorkSpaces 애플리케이션 리소스를 자동으로 생성하기 위한 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/4f0205f5-5b91-4832-9f0f-2135ae866226/images/cb578939-d9af-4f60-93c9-286881df4c3a.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 이 패턴의 [추가 정보](#automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-additional) 섹션에 있는 YAML 코드를 기반으로 CloudFormation 템플릿을 생성합니다.

1.  CloudFormation 템플릿은 CloudFormation 테스트 스택을 생성합니다.

   1. (선택 사항) WorkSpaces 애플리케이션을 사용하여 이미지 빌더 인스턴스를 생성합니다.

   1. (선택 사항) 사용자 지정 소프트웨어를 사용하여 Windows 이미지를 생성합니다.

1.  CloudFormation 스택은 WorkSpaces 애플리케이션 플릿 인스턴스 및 스택을 생성합니다.

1. WorkSpaces 애플리케이션 리소스를 HTML5-compliant 브라우저의 최종 사용자에게 배포합니다.

## 도구
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-tools"></a>
+ [Amazon WorkSpaces 애플리케이션](https://docs.aws.amazon.com/appstream2/latest/developerguide/what-is-appstream.html)은 어디서나 데스크톱 애플리케이션에 즉시 액세스할 수 있는 완전 관리형 애플리케이션 스트리밍 서비스입니다. WorkSpaces 애플리케이션은 애플리케이션을 호스팅 및 실행하는 데 필요한 AWS 리소스를 관리하고, 자동으로 확장되며, 온디맨드 방식으로 사용자에게 액세스 권한을 제공합니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 모델링 및 설정하고, 리소스를 빠르고 일관되게 프로비저닝하고, 수명 주기 동안 관리할 수 있습니다. 템플릿을 사용하여 리소스와 해당 종속성을 설명하고 리소스를 개별적으로 관리하는 대신 스택으로 함께 시작 및 구성할 수 있습니다. 여러 및에서 스택을 관리하고 프로비저닝할 수 AWS 계정 있습니다 AWS 리전.

## 모범 사례
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-best-practices"></a>
+ **이미지 빌더에 대한 네트워크 액세스를 올바르게 구성** - 아웃바운드 전용 인터넷 액세스를 위해 NAT 게이트웨이를 사용하여 적절한 인터넷 액세스가 가능한 Virtual Private Cloud(VPC) 서브넷에서 이미지 빌더를 시작합니다.

  이미지를 생성하기 전에 필요한 리소스(예: 애플리케이션 서버, 데이터베이스 및 라이선스 서버)에 대한 네트워크 연결을 테스트합니다. VPC 라우팅 테이블이 필요한 모든 네트워크 리소스에 대한 연결을 허용하는지 확인합니다. 자세한 내용은 WorkSpaces 애플리케이션 설명서의 [인터넷 액세스를](https://docs.aws.amazon.com/appstream2/latest/developerguide/internet-access.html) 참조하세요.
+ **서비스 할당량을 기준으로 플릿 용량을 사전에 모니터링** - WorkSpaces 애플리케이션 인스턴스 유형 및 크기 할당량은 당 AWS 계정, 당입니다 AWS 리전. 동일한 리전에 동일한 인스턴스 유형과 크기를 사용하는 플릿이 여러 개 있는 경우 해당 리전 내 모든 플릿의 총 인스턴스 수는 할당량보다 작거나 같아야 합니다. 자세한 내용은 WorkSpaces 애플리케이션 설명서의 [플릿 문제 해결을](https://docs.aws.amazon.com/appstream2/latest/developerguide/troubleshooting-fleets.html) 참조하세요.
+ **플릿 배포 전에 Image Builder 테스트 모드에서 애플리케이션 테스트** - 이미지를 생성하고 플릿에 배포하기 전에 항상 Image Builder 테스트 모드에서 애플리케이션을 검증합니다. 테스트 모드는 최종 사용자가 플릿 인스턴스에 대해 갖는 제한된 권한을 시뮬레이션합니다. 자세한 내용은 WorkSpaces 애플리케이션 설명서의 [이미지 빌더 문제 해결을](https://docs.aws.amazon.com/appstream2/latest/developerguide/troubleshooting-image-builder.html#troubleshooting-07) 참조하세요.

## 에픽
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-epics"></a>

### (선택 사항) WorkSpaces 애플리케이션 이미지 생성
<a name="optional-create-a-aas2-image"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 맞춤형 소프트웨어를 설치하고 이미지를 생성하세요. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.html)이미지를 추가로 잠그려면 Windows AppLocker 기능을 사용하는 것이 좋습니다. | AWS DevOps, 클라우드 아키텍트 | 

### CloudFormation 템플릿 배포
<a name="deploy-the-cfn-template"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  CloudFormation 템플릿을 업데이트합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.html) | AWS 시스템 관리자, 클라우드 관리자, 클라우드 아키텍트, 일반 AWS, AWS 관리자 | 
| 템플릿을 사용하여 CloudFormation 스택을 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.html) | 앱 소유자, AWS 시스템 관리자, Windows 엔지니어 | 

## 문제 해결
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 다양한 문제 | 자세한 내용은 WorkSpaces 애플리케이션 설명서의 [문제 해결을](https://docs.aws.amazon.com/appstream2/latest/developerguide/troubleshooting.html) 참조하세요. | 

## 관련 리소스
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-resources"></a>

**참조**
+ [Amazon WorkSpaces 애플리케이션 시작하기: 샘플 애플리케이션으로 설정](https://docs.aws.amazon.com/appstream2/latest/developerguide/getting-started.html)
+ [Amazon WorkSpaces 애플리케이션 플릿 및 스택 생성](https://docs.aws.amazon.com/appstream2/latest/developerguide/set-up-stacks-fleets.html)

**자습서 및 동영상**
+ [Amazon WorkSpaces 애플리케이션 사용자 워크플로](https://www.youtube.com/watch?v=hVGQ87-Uhrc)
+ [레거시 Windows Forms 앱을 Amazon WorkSpaces 애플리케이션으로 마이그레이션하는 방법](https://www.youtube.com/watch?v=CIImtS2iVbg)
+ [AWS re:Invent 2018: Amazon WorkSpaces 애플리케이션으로 데스크톱 애플리케이션 보안 제공(BAP201)](https://www.youtube.com/watch?v=xNIyc_inOhM)

## 추가 정보
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-additional"></a>

다음 코드는 WorkSpaces 애플리케이션 리소스를 자동으로 생성하는 데 사용할 수 있는 CloudFormation 템플릿의 예입니다.

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  SubnetIds:
    Type: 'List<AWS::EC2::Subnet::Id>'
  testSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup::Id'
  ImageName:
    Type: String
Resources:
  
  AppStreamFleet:
    Type: 'AWS::AppStream::Fleet'
    Properties:
      ComputeCapacity:
        DesiredInstances: 5
      InstanceType: stream.standard.medium
      Name: appstream-test-fleet
      DisconnectTimeoutInSeconds: 1200
      FleetType: ON_DEMAND
      IdleDisconnectTimeoutInSeconds: 1200
      ImageName: !Ref ImageName
      MaxUserDurationInSeconds: 345600
      VpcConfig:
        SecurityGroupIds:
          - !Ref testSecurityGroup
        SubnetIds: !Ref SubnetIds
  AppStreamStack:
    Type: 'AWS::AppStream::Stack'
    Properties:
      Description: AppStream stack for test
      DisplayName: AppStream test Stack
      Name: appstream-test-stack
      StorageConnectors:
        - ConnectorType: HOMEFOLDERS
      UserSettings:
        - Action: CLIPBOARD_COPY_FROM_LOCAL_DEVICE
          Permission: ENABLED
        - Action: CLIPBOARD_COPY_TO_LOCAL_DEVICE
          Permission: ENABLED
        - Action: FILE_DOWNLOAD
          Permission: ENABLED
        - Action: PRINTING_TO_LOCAL_DEVICE
          Permission: ENABLED
  AppStreamFleetAssociation:
    Type: 'AWS::AppStream::StackFleetAssociation'
    Properties:
      FleetName: appstream-test-fleet
      StackName: appstream-test-stack
    DependsOn:
      - AppStreamFleet
      - AppStreamStack
```

# Firelens 로그 라우터를 사용하여 Amazon ECS용 사용자 지정 로그 구문 분석기를 생성
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router"></a>

*Varun Sharma, Amazon Web Services*

## 요약
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-summary"></a>

Firelens는 Amazon Elastic Container Service(Amazon ECS)와 AWS Fargate를 위한 로그 라우터입니다. Firelens를 사용하여 Amazon ECS에서 Amazon CloudWatch 및 기타 대상(예: [Splunk](https://www.splunk.com/) 또는 [Sumo Logic](https://www.sumologic.com/))으로 컨테이너 로그를 라우팅할 수 있습니다. Firelens는 [Fluentd](https://www.fluentd.org/) 또는 [Fluent Bit](https://fluentbit.io/)를 로깅 에이전트로 사용하여 작동합니다. 즉, [Amazon ECS 작업 정의 파라미터](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html)를 사용하여 로그를 라우팅할 수 있습니다.

소스 수준에서 로그를 구문 분석하기로 선택하면 로깅 데이터를 분석하고 쿼리를 수행하여 운영 문제에 더 효율적이면서 효과적으로 대응할 수 있습니다. 애플리케이션마다 로깅 패턴이 다르기 때문에 로그를 구조화하고 최종 대상에서 더 쉽게 검색할 수 있는 사용자 지정 구문 분석기를 사용해야 합니다.

이 패턴은 사용자 지정 구문 분석기가 있는 Firelens 로그 라우터를 사용하여 Amazon ECS에서 실행되는 샘플 Spring Boot 애플리케이션에서 CloudWatch로 로그를 푸시합니다. 그런 다음 Amazon CloudWatch Logs Insights를 사용하여 사용자 지정 구문 분석기에서 생성한 사용자 지정 필드를 기반으로 로그를 필터링할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-prereqs"></a>

**사전 조건 **
+ 활성 Amazon Web Services(AWS) 계정.
+ 로컬 시스템에 설치 및 구성된 Command Line Interface(CLI).
+ 로컬 시스템에 설치 및 구성된 Docker.
+ Amazon Elastic Container Registry(Amazon ECR)의 기존 Spring Boot 기반 컨테이너식 애플리케이션. 

## 아키텍처
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-architecture"></a>

![\[Firelens 로그 라우터를 사용하여 Amazon ECS에서 실행되는 애플리케이션에서 CloudWatch로 로그를 푸시.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/e82b4992-c4e0-4af5-b87e-cb0b1c1ed8c9/images/ef60e087-965a-40e9-9f80-35edbda2befe.png)


**기술 스택**
+ CloudWatch
+ Amazon ECR
+ Amazon ECS
+ Fargate
+ Docker
+ Fluent Bit

## 도구
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-tools"></a>
+ [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) – Amazon Elastic Container Registry(Amazon ECR)는 안전하고 확장 가능하고 신뢰할 수 있는 AWS 관리형 컨테이너 이미지 레지스트리 서비스입니다.
+ [Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) – Amazon Elastic Container Service(Amazon ECS)는 클러스터에서 컨테이너를 손쉽게 실행, 중지 및 관리할 수 있게 하는 컨테이너 관리 서비스로서 확장성과 속도가 뛰어납니다.
+ [Identity and Access Management(IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) – IAM은 AWS 리소스에 대한 사용자의 액세스를 안전하게 제어할 수 있게 지원하는 웹 서비스입니다.
+ [CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) – Command Line Interface(CLI)는 명령줄 쉘에서 명령을 사용하여 AWS 서비스와 상호 작용할 수 있는 오픈 소스 도구입니다.
+ [Docker](https://www.docker.com/) — Docker는 애플리케이션 개발, 배송, 실행을 위한 개방형 플랫폼입니다.

**코드**

이 패턴에는 다음 파일이 연결됩니다.
+ `customFluentBit.zip` — 사용자 지정 구문 분석 및 구성을 추가하기 위한 파일이 들어 있습니다.
+ `firelens_policy.json` — IAM 정책을 생성하기 위한 정책 문서가 들어 있습니다.
+ `Task.json` — Amazon ECS의 샘플 작업 정의가 들어 있습니다.

## 에픽
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-epics"></a>

### 사용자 지정 Fluent Bit 이미지 생성
<a name="create-a-custom-fluent-bit-image"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon ECR 리포지토리를 생성합니다. | AWS Management Console에 로그인한 다음, Amazon ECR 콘솔을 열고 `fluentbit_custom`라고 불리는 리포지토리를 생성합니다.이에 대한 자세한 내용은 Amazon ECR 설명서의 [리포지토리 생성](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)을 참조하십시오. | 시스템 관리자, 개발자 | 
| customFluentBit.zip 패키지의 압축을 풉니다. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html) |  | 
| 사용자 지정 도커 이미지를 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html)자세한 내용은 Amazon ECR 설명서에서 [Docker 이미지 푸시하기](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)를 참조하십시오.  | 시스템 관리자, 개발자 | 

### Amazon ECS 클러스터를 설정
<a name="set-up-the-amazon-ecs-cluster"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon ECS 클러스터를 생성합니다. | Amazon ECS 설명서에서 [클러스터 생성](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create_cluster.html)의 *네트워킹 전용 템플릿* 섹션에 나와 있는 지침을 따라 Amazon ECS 클러스터를 생성합니다.Amazon ECS 클러스터용 새 가상 프라이빗 클라우드(VPC)를 생성하기 위해 **VPC 생성**을 선택해야 합니다. | 시스템 관리자, 개발자 | 

### Amazon ECS 작업 설정
<a name="set-up-the-amazon-ecs-task"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  Amazon ECS 태스크 실행 IAM 역할을 설정합니다. | `AmazonECSTaskExecutionRolePolicy` 관리형 정책을 사용하여 Amazon ECS 태스크 실행 IAM 역할을 생성합니다. 이에 대한 자세한 내용은 Amazon ECS 사용 설명서의 [Amazon ECS 태스크 실행 IAM 역할](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html)을 참조하십시오.IAM 역할의 Amazon 리소스 이름(ARN)을 기록해 두어야 합니다. | 시스템 관리자, 개발자 | 
|  IAM 정책을 Amazon ECS 작업 실행 IAM 역할에 연결합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html) | 시스템 관리자, 개발자 | 
| Amazon ECS 태스크 정의를 설정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html)이에 대한 자세한 내용은 Amazon ECS 설명서의 [작업 정의 생성](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition.html)을 참조하십시오. | 시스템 관리자, 개발자 | 

### Amazon ECS 태스크 실행
<a name="run-the-amazon-ecs-task"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon ECS 태스크를 실행합니다. | Amazon ECS 콘솔에서 **클러스터**를 선택하고 이전에 생성한 클러스터를 선택한 다음 독립 실행형 작업을 실행합니다.이에 대한 자세한 내용은 Amazon ECS 설명서에서 [독립 실행형 작업 실행](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_run_task.html)을 참조하십시오. | 시스템 관리자, 개발자 | 

### CloudWatch 로그 확인
<a name="verify-the-cloudwatch-logs"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 로그를 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html) | 시스템 관리자, 개발자 | 

## 관련 리소스
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-resources"></a>
+ [Amazon ECS용 도커 기본 사항](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html) 
+ [Fargate의 Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html) 
+ [기본 서비스 파라미터 구성](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/basic-service-params.html) 

## 첨부
<a name="attachments-e82b4992-c4e0-4af5-b87e-cb0b1c1ed8c9"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/e82b4992-c4e0-4af5-b87e-cb0b1c1ed8c9/attachments/attachment.zip) 파일의 압축을 풉니다.

# GitHub Actions 및 Terragrunt를 사용하여 API 기반 리소스 오케스트레이션 프레임워크 생성
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt"></a>

*Tamilselvan P, Abhigyan Dandriyal, Sandeep Gawande, Akash Kumar, Amazon Web Services*

## 요약
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-summary"></a>

이 패턴은 GitHub Actions 워크플로를 활용하여 표준화된 JSON 페이로드를 통해 리소스 프로비저닝을 자동화하므로 수동 구성이 필요하지 않습니다. 이 자동화된 파이프라인은 전체 배포 수명 주기를 관리하고 사용자 지정 UI 구성 요소에서 ServiceNow에 이르기까지 다양한 프런트엔드 시스템과 원활하게 통합할 수 있습니다. 솔루션의 유연성을 통해 사용자는 표준화된 프로세스를 유지하면서 선호하는 인터페이스를 통해 시스템과 상호 작용할 수 있습니다.

구성 가능한 파이프라인 아키텍처는 다양한 조직 요구 사항을 충족하도록 조정할 수 있습니다. 이 구현 예는 Amazon Virtual Private Cloud(Amazon VPC) 및 Amazon Simple Storage Service(Amazon S3) 프로비저닝에 중점을 둡니다. 이 패턴은 조직 전반의 요청을 표준화하고 일관된 통합 지점을 제공하여 일반적인 클라우드 리소스 관리 문제를 효과적으로 해결합니다. 이 접근 방식을 사용하면 팀이 표준화를 보장하면서 리소스를 더 쉽게 요청하고 관리할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정
+ 구성된 리포지토리에 액세스할 수 있는 활성 GitHub 계정

**제한 사항 **
+ 새 리소스는 리포지토리 구성에 `terragrunt.hcl` 파일을 수동으로 추가해야 합니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-architecture"></a>

다음 다이어그램은 이 패턴의 구성 요소 및 워크플로를 보여 줍니다.

![\[GitHub Actions 및 Terraform을 사용하여 리소스 프로비저닝을 자동화하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/bff5d70e-e8f1-454a-94bc-60e8cc16e69f/images/d4a768c8-4e11-493c-85ed-f4bf7e76ce60.png)


다이어그램은 다음 아키텍처를 보여줍니다:

1. 사용자가 GitHub Actions에 JSON 페이로드를 제출하여 자동화 파이프라인을 트리거합니다.

1. GitHub Actions 파이프라인은 페이로드 사양에 따라 Terragrunt 및 Terraform 리포지토리에서 필요한 리소스 코드를 검색합니다.

1. 파이프라인은 지정된 AWS 계정 ID를 사용하여 적절한 AWS Identity and Access Management (IAM) 역할을 수임합니다. 그런 다음 파이프라인은 리소스를 대상에 배포 AWS 계정 하고 계정별 Amazon S3 버킷 및 Amazon DynamoDB 테이블을 사용하여 Terraform 상태를 관리합니다.

각 AWS 계정 에는 보안 액세스를 위한 IAM 역할, Terraform 상태 스토리지를 위한 Amazon S3 버킷, 상태 잠금을 위한 DynamoDB 테이블이 포함되어 있습니다. 이 설계를 통해에서 제어되고 자동화된 리소스 배포가 가능합니다 AWS 계정. 배포 프로세스는 각 계정의 전용 Amazon S3 버킷 및 IAM 역할을 통해 적절한 상태 관리 및 액세스 제어를 유지합니다.

## 도구
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-tools"></a>

**AWS 서비스**
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)는 빠르고 예측 가능하고 확장 가능한 성능을 제공하는 완전 관리형 NoSQL 데이터베이스 서비스입니다.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 액세스를 인증하고 사용할 수 있는 권한을 부여받은 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다.
+ [Amazon Simple Storage Service(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의 확장 가능한 인프라를 사용한다는 이점과 함께 고객의 자체 데이터 센터에서 운영하는 기존 네트워크와 유사합니다.

**기타 도구**
+ [GitHub Actions](https://docs.github.com/en/actions)는 GitHub 리포지토리와 긴밀하게 통합된 지속적 통합 및 지속적 전달(CI/CD) 플랫폼입니다. GitHub Actions를 사용하여 빌드, 테스트 및 배포 파이프라인을 자동화할 수 있습니다.
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.
+ [Terragrunt](https://terragrunt.gruntwork.io/docs/getting-started/overview/)는 OpenTofu 및 Terraform 기능을 모두 확장하는 오케스트레이션 도구입니다. 일반 인프라 패턴이 적용되는 방식을 관리하므로 대규모 인프라 자산을 더 쉽게 확장하고 유지할 수 있습니다.

**코드 리포지토리**

이 패턴의 코드는 [aws-codepipeline-terraform-cicdsamples](https://github.com/aws-samples/sample-aws-orchestration-pipeline-terraform) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-best-practices"></a>
+ 보안 액세스를 위해 GitHub 리포지토리 보안 암호를 사용하여 AWS 자격 증명과 민감한 데이터를 저장합니다.
+ 정적 자격 증명을 사용하지 않고 IAM 역할을 수임하도록 GitHub Actions에 대한 OpenID Connect(OIDC) 공급자를 구성합니다.
+ 최소 권한 원칙을 따르고 작업을 수행하는 데 필요한 최소 권한을 부여하세요. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv) 및 [보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)를 참조하세요.

## 에픽
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-epics"></a>

### 리포지토리 생성 및 구성
<a name="create-and-configure-repository"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Git 리포지토리를 초기화합니다. | GitHub 리포지토리를 초기화하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 엔지니어 | 
| IAM 역할 및 IAM 권한을 구성하려면 | IAM 역할 및 권한을 구성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 엔지니어 | 
| GitHub 시크릿 및 변수를 설정합니다. | GitHub 리포지토리에서 리포지토리 시크릿 및 변수를 설정하는 방법에 대한 지침은 GitHub 설명서의 [리포지토리에 대한 구성 변수 생성](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-variables#creating-configuration-variables-for-a-repository)을 참조하세요. 다음 변수를 구성합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 엔지니어 | 
| 리포지토리 구조를 생성합니다. | 리포지토리 구조를 생성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 엔지니어 | 

### 파이프라인 트리거 및 결과 검증
<a name="trigger-the-pipeline-and-validate-results"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| curl을 사용하여 파이프라인을 실행합니다. | [curl](https://curl.se/)을 사용하여 파이프라인을 실행하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html)파이프라인 실행 프로세스에 대한 자세한 내용은 [추가 정보를](#create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-additional) 참조하세요. | DevOps 엔지니어 | 
| 파이프라인 실행 결과 검증 | 결과를 검증하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html)`terragrunt.hcl` 파일과 동일한 리소스 내에 있는 리포지토리에서 생성된 `output.json` 파일을 사용하여 생성된 리소스를 교차 확인할 수도 있습니다. | DevOps 엔지니어 | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 정리 요청을 제출합니다. | 더 이상 필요하지 않은 리소스를 삭제하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 엔지니어 | 

## 관련 리소스
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-resources"></a>

**AWS 블로그**
+ [IAM 역할을 사용하여 GitHub 작업을의 작업에 연결 AWS](https://aws.amazon.com/blogs/security/use-iam-roles-to-connect-github-actions-to-actions-in-aws/)

**AWS 서비스 설명서**
+ [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)
+ [Amazon CloudWatch Logs를 사용하여 CloudTrail 로그 파일 모니터링](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html)
+ [Amazon S3의 보안 모범 사례](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-best-practices.html)

GitHub 리소스 사용
+ [리포지토리 디스패치 이벤트 생성](https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#create-a-repository-dispatch-event)
+ [웹후크 생성](https://docs.github.com/en/webhooks/using-webhooks/creating-webhooks#payload)
+ [GitHub 리포지토리에서 강력한 액세스 제어 구현](https://docs.github.com/en/get-started/learning-about-github/access-permissions-on-github)
+ [리포지토리 액세스를 정기적으로 감사](https://docs.github.com/en/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization)
+ [CI/CD 파이프라인의 보안 검사](https://github.com/marketplace/actions/checkov-github-action)
+ [GitHub 계정에 다중 인증 사용](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa/configuring-two-factor-authentication)

## 추가 정보
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-additional"></a>

**파이프라인 실행 프로세스**

파이프라인 실행 단계는 다음과 같습니다.

1. **JSON 페이로드 형식 검증** - 수신 JSON 구성이 올바르게 구성되고 필요한 모든 파라미터가 포함되어 있는지 확인합니다.

1. **지정된 IAM 역할 수임** - AWS 작업에 필요한 IAM 역할을 인증하고 수임합니다.

1. **필요한 Terraform 및 Terragrunt 코드 다운로드** - 지정된 버전의 리소스 코드 및 종속성을 검색합니다.

1. **리소스 배포 실행** - 구성을 적용하여 대상 환경에서 AWS 리소스를 배포하거나 업데이트합니다.

**VPC 생성에 사용되는 샘플 페이로드**

다음은 Terraform 백엔드 상태 버킷 생성을 위한 예시 코드입니다.

```
state_bucket_name = "${local.payload.ApplicationName}-${local.payload.EnvironmentId}-tfstate"
```

```
lock_table_name = "${local.payload.ApplicationName}-${local.payload.EnvironmentId}-tfstate-lock"
```

다음은 Amazon VPC를 사용하여 VPC를 생성하기 위한 예제 페이로드입니다. 여기서 `vpc_cidr`은 VPC에 대한 [CIDR 블록](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-cidr-blocks.html) 사양을 정의합니다. Terraform 상태 버킷은 `terraform` 파일에 정의된 변수에 매핑됩니다. `ref` 파라미터에는 실행할 코드의 브랜치 이름이 포함됩니다.

```
{
    "ref": "main",
    "inputs": {
        "RequestParameters": {
            "RequestId": "1111111",
            "RequestType": "create",
            "ResourceType": "vpc",
            "AccountId": "1234567890",
            "AccountAlias": "account-alias",
            "RegionId": "us-west-2",
            "ApplicationName": "myapp",
            "DivisionName": "division-name",
            "EnvironmentId": "dev",
            "Suffix": "poc"
        },
        "ResourceParameters": [
            {
                "VPC": {
                    "vpc_cidr": "10.0.0.0/16"
                }
            }
        ]
    }
}
```

`RequestParameters`는 파이프라인 섹션에서 요청 상태를 추적하는 데 사용되며이 정보를 기반으로 `tfstate` 생성됩니다. 파라미터에는 다음 정보가 포함되어 있습니다.
+ `RequestId` – 요청에 대한 고유 식별자입니다.
+ `RequestType` - 작업 유형(생성, 업데이트 또는 삭제)
+ `ResourceType` - 프로비저닝할 리소스 유형
+ `AccountId` - 배포 AWS 계정 대상
+ `AccountAlias` -의 표시 이름 AWS 계정
+ `RegionId` - 리소스 배포 AWS 리전 용
+ `ApplicationName`애플리케이션의 명칭.
+ `DivisionName` - 조직 부서
+ `EnvironmentId` – 환경(예: dev 및 prod)
+ `Suffix` - 리소스의 추가 식별자

`ResourceParameters` 에는 Terraform 파일에 정의된 변수에 매핑되는 리소스별 구성이 포함되어 있습니다. Terraform 모듈로 전달해야 하는 모든 사용자 지정 변수는에 포함되어야 합니다`ResourceParameters`. Amazon VPC의 경우 파라미터`vpc_cidr`는 필수입니다.

# GitHub Actions를 사용하여 Terraform 관리형 AWS 인프라에 대한 자동 풀 요청 생성
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure"></a>

*Matt Padgett, Ashish Bhatt, Ashwin Divakaran, Sandip Gangapadhyay, Prafful Gupta, Amazon Web Services*

## 요약
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-summary"></a>

이 패턴은 여러 Terraform 리포지토리에서 변경 사항을 관리하는 데 수반되는 수동적이고 반복적인 작업을 제거하도록 설계된 자동화 유틸리티를 제공합니다. 많은 조직에서 Terraform 리포지토리를 사용하여 코드형 인프라(IaC)를 관리합니다. 종종 수백 개의 개별 리포지토리가 서로 다른 환경, 서비스 또는 팀을 나타냅니다. 이러한 리포지토리를 대규모로 관리하면 상당한 운영 문제가 발생합니다. 파라미터 업데이트, 모듈 버전 업그레이드 또는 구성 변경 적용과 같은 일상적인 작업을 수행하려면 하루에 여러 번 여러 리포지토리에서 풀 요청(PRs 생성하고 관리해야 하는 경우가 많습니다.

간단한 변경의 경우에도이 반복적이고 수동적인 프로세스는 시간이 많이 걸리고 오류가 발생하기 쉽습니다. 엔지니어는 모든 대상 리포지토리에 동일한 변경 사항을 일관되게 적용하고 의미 있는 PR 제목과 설명을 만들어야 합니다. 또한 문제 추적 참조를 가져오거나 포함하려면 Jira와 같은 외부 도구와 상호 작용해야 하는 경우가 많습니다. 이러한 작업은 필요하더라도 중요한 엔지니어링 시간을 소비하고 전반적인 효율성을 떨어뜨리는 차별화되지 않은 과중한 작업입니다. 이 워크플로의 자동화가 부족하면 마찰이 발생하고 전송 속도가 느려지며 대규모 Terraform 인프라를 유지 관리하는 팀의 인지 부담이 증가합니다.

**솔루션 개요**

이 문제를 해결하기 위해이 패턴은 완전한 구성 기반 유틸리티를 제공하므로 사용자는 구조화된 구성 파일에서 원하는 변경 사항을 정의할 수 있습니다. 이 파일은 명확하게 정의된 스키마를 사용하여 대상 리포지토리, 모듈, 파라미터 및 값을 지정합니다.

구성되면 유틸리티는 다음과 같은 자동 단계를 수행합니다.

1. **사용자 정의 구성을 읽어** 변경 사항의 범위와 특성을 결정합니다.

1. 필요한 업데이트가 적용된 각 대상 리포지토리에 **새 브랜치를 생성합니다**.

1. 각 변경에 대한 **PR을 생성**하여 모든 리포지토리의 일관성을 보장합니다.

1. **Slack 알림(선택 사항)을 전송**하여 생성된 PRs

유틸리티는 이러한 반복 작업을 자동화하여 대규모 인프라 업데이트 관리와 관련된 시간, 노력 및 리스크를 크게 줄입니다. 이를 통해 팀은 변경 사항이 일관되게 적용되고 모든 리포지토리에서 추적할 수 있도록 지원하면서 고부가가치 엔지니어링 작업에 집중할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ Python 버전 3.8 이상.
+ GitHub 개인 액세스 토큰 자세한 내용은 GitHub 설명서의 [개인 액세스 토큰 생성(클래식)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic)을 참조하세요.
+ GitHub PAT는 유틸리티가 브랜치 및 풀 요청 생성과 같은 작업을 수행할 수 있도록 대상 리포지토리에 액세스할 수 있습니다. 자세한 내용은이 패턴의 GitHub [코드 리포지토리](https://github.com/aws-samples/sample-terraform-pr-automation-utility?tab=readme-ov-file#repository-access-verification)를 참조하세요.

**제한 사항 **
+ **구성 복잡성**은 주요 과제입니다. 자동화의 효과는 구성 파일의 기능에 의해 제한됩니다. 시스템이 표준 변경 사항을 효율적으로 처리하지만 복잡한 인프라 수정에는 수동 개입이 필요할 수 있으며 특정 엣지 케이스는 자동 처리 범위를 벗어납니다.
+ **보안 및 액세스**는 특히 GitHub 액세스 토큰 및 API 속도 제한을 관리할 때 상당한 고려 사항을 제공합니다. 조직은 운영 효율성을 유지하면서 적절한 액세스 제어를 보장하면서 안전한 자격 증명 스토리지 및 관리와 자동화의 필요성을 신중하게 균형을 맞춰야 합니다.
+ 자동 시스템에는 비즈니스 로직 및 환경별 요구 사항을 검증할 수 있는 기능이 제한되어 있기 때문에 **검증 제약** 조건은 또 다른 주목할 만한 제한을 제기합니다. 자동화된 검증이 모든 상황별 뉘앙스와 비즈니스 규칙을 완전히 포착할 수 없기 때문에 복잡한 종속성과 교차 서비스 상호 작용에는 사람의 감독이 필요한 경우가 많습니다.
+ 대규모 인프라 변경을 처리할 때 **규모 및 성능** 문제가 발생합니다. 시스템은 여러 리포지토리를 동시에 관리하면서 GitHub API 제한 내에서 작동해야 합니다. 광범위한 인프라에서 리소스 집약적인 작업을 수행하면 신중한 관리가 필요한 성능 병목 현상이 발생할 수 있습니다.
+ **통합 경계**는 주로 GitHub 및 Slack과 같은 특정 도구와 함께 작동하도록 설계되었기 때문에 시스템의 유연성을 제한합니다. 다른 도구를 사용하는 조직은 사용자 지정 솔루션이 필요할 수 있으며이 패턴의 워크플로 사용자 지정 옵션은 지원되는 통합 지점으로 제한됩니다.

## 아키텍처
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-architecture"></a>

다음 다이어그램은 이 애플리케이션에 대한 구성 요소 및 워크플로우를 보여줍니다.

![\[GitHub Actions를 사용하여 자동 풀 요청을 생성하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/e211359a-03b1-4e69-b152-eb7c09bdb01a/images/6cee0660-5b44-4abe-970c-c0a3c830a9aa.png)


워크플로우는 다음 단계로 구성됩니다.

1. 개발자는 Terraform 리포지토리를 지정하여 GitHub Actions를 트리거합니다.

1. 자동화 유틸리티는 정의된 구성을 읽습니다.

1. 자동화 유틸리티는 제공된 Terraform 리포지토리도 가져옵니다.

1. 자동화 유틸리티는 새 브랜치를 생성하고 로컬에서 Terraform 템플릿을 업데이트합니다.

1. 자동화 유틸리티는 새 브랜치를 리포지토리로 푸시하고 새 PR을 생성합니다.

1. 자동화 유틸리티는 PR 링크가 포함된 Slack 알림을 사용하여 개발자에게 알리고 AWS 클라우드 배포를 위해 Terraform 템플릿을 활성화합니다.

## 도구
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-tools"></a>
+ [GitHub](https://docs.github.com/)는 개발자가 코드를 생성, 저장, 관리 및 공유하는 데 사용할 수 있는 개발자 플랫폼입니다.
+ [GitHub Actions](https://docs.github.com/en/actions)는 GitHub 리포지토리와 긴밀하게 통합된 지속적 통합 및 지속적 전달(CI/CD) 플랫폼입니다. GitHub Actions를 사용하여 빌드, 테스트 및 배포 파이프라인을 자동화할 수 있습니다.
+ [HashiCorp Terraform](https://www.terraform.io/)은 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.
+ Salesforce 제품인 [Slack](https://slack.com/help/articles/115004071768-What-is-Slack-)은 채팅 및 비디오 협업을 제공하고, 코드 없이 프로세스를 자동화하고, 정보 공유를 지원하는 AI 기반 대화형 플랫폼입니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [Actions 리포지토리를 사용하는 GitHub Automated Terraform Infrastructure Update Workflow](https://github.com/aws-samples/sample-terraform-pr-automation-utility?tab=readme-ov-file)에서 사용할 수 있습니다.

## 모범 사례
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-best-practices"></a>
+ 효과적인 **변경 관리**는 성공적인 구현에 매우 중요합니다. 조직은 대규모 변경을 위한 점진적인 롤아웃 전략을 채택해야 합니다. 일관된 브랜치 이름 지정 규칙 및 PR 설명을 유지하고 모든 변경 사항을 포괄적으로 문서화합니다.
+ 최소 권한 액세스 원칙과 보안 자격 증명 관리에 중점을 두고 **보안 제어를** 엄격하게 구현해야 합니다. 무단 변경을 방지하기 위해 브랜치 보호 규칙을 활성화합니다. 정기적인 보안 감사를 수행하여 시스템 무결성을 유지합니다.
+ 강력한 **테스트 프로토콜**에는 지속적 통합 및 지속적 배포(CI/CD) 파이프라인에서의 자동 `terraform plan` 실행이 포함되어야 합니다. 프로토콜에는 커밋 전 검증 검사 및 중요한 변경 사항에 대한 전용 검토 환경도 포함되어야 합니다. 이 다중 계층 테스트 접근 방식은 문제를 조기에 포착하고 인프라 안정성을 보장하는 데 도움이 됩니다.
+ **모니터링 전략**에는 포괄적인 알림 메커니즘, 자세한 성공/실패 지표 추적, 실패한 작업에 대한 자동 재시도 메커니즘이 포함되어야 합니다. 이 전략은 운영 가시성을 보장하고 발생하는 모든 문제에 신속하게 대응할 수 있도록 지원합니다.
+ **구성 표준**은 모든 구성에 대한 버전 관리를 강조하여 재사용성 및 확장성을 위한 모듈성을 유지해야 합니다. 스키마 및 예를 명확하게 문서화하면 팀이 자동화 시스템을 효과적으로 이해하고 사용하는 데 도움이 됩니다.

## 에픽
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-epics"></a>

### 설치 및 설정
<a name="installation-and-setup"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 코드 리포지토리 설정 | 리포지토리를 복제하려면 다음 명령을 실행합니다.<pre># Clone the automation tool repository<br />git clone https://github.com/aws-samples/sample-terraform-pr-automation-utility<br />cd sample-terraform-pr-automation-utility<br /><br /># Copy example configuration<br />cp config.example.yaml config.yaml<br /></pre> | DevOps | 
| 종속 항목 설치 | 필요한 종속성을 설치하려면 다음 명령을 실행합니다.<pre># Install Python dependencies<br />pip3 install -r requirements.txt<br /><br /># Verify installation<br />python3 -c "import github; import hcl2; import yaml; import requests; print('All packages installed successfully')"<br /></pre> | DevOps | 
| GitHub 토큰을 구성합니다. | GitHub 토큰을 구성한 다음 작동하는지 확인하려면 다음 명령을 실행합니다.<pre># Set GitHub token environment variable<br />export GITHUB_TOKEN="your_github_token_here"<br /><br /># Verify token works<br />curl -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user<br /></pre> | DevOps | 

### Terraform 변경 사항에 대한 구성 파일 설정
<a name="set-up-configuration-file-for-terraform-changes"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `config.yaml` 파일을 설정하려면 | 대상 리포지토리와 원하는 변경 사항을 정의하려면 다음과 같이 `config.yam`l 파일을 편집합니다.<pre>repositories:<br />  - owner: "your-org"<br />    repo: "your-terraform-repo"<br />    files:<br />      - path: "variables.tf"<br />        changes:<br />          variables:<br />            - app_version:<br />                default:<br />                  update:<br />                    - from: ["1.0.0"]<br />                      to: "1.1.0"<br /><br />settings:<br />  pr_title_template: "Infrastructure Update - {{timestamp}}"<br />  slack:<br />    username: "Terraform Bot"<br />    icon_emoji: ":terraform:"<br />    notify_on_success: true<br />    notify_on_error: true<br />    notify_batch_summary: true<br /></pre> | DevOps | 

### 테스트 및 검증
<a name="test-and-validate"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 사전 테스트를 수행합니다. | 프로덕션 리포지토리에서 실행하기 전에 항상 구성을 테스트합니다. 다음 명령을 사용합니다.<pre># 1. Test configuration syntax<br />python3 -c "from main import get_config_content; get_config_content()"<br /><br /># 2. Run in dry-run mode first<br />DRY_RUN=true python3 main.py<br /><br /># 3. Test with minimal configuration<br /># Use a simple config.yaml with just one repository and one change</pre> | DevOps | 
| 리포지토리 액세스를 확인합니다. | GitHub 토큰이 리포지토리에 액세스할 수 있는지 확인하려면 다음 명령을 실행합니다.<pre># Test GitHub token access<br />curl -H "Authorization: token $GITHUB_TOKEN" \<br />  https://api.github.com/repos/owner/repo-name<br /><br /># Should return repository information, not 404</pre> | DevOps | 

### 자동화 유틸리티 실행
<a name="run-the-automation-utility"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| GitHub Actions UI를 사용하여 자동화 유틸리티를 실행합니다. | GitHub Actions UI를 사용하여 자동화 유틸리티를 실행하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-automated-pull-requests-for-terraform-managed-aws-infrastructure.html) | DevOps | 
| (또는) 명령줄에서 자동화 유틸리티를 실행합니다. | 원하는 경우 GitHub Actions UI를 사용하는 대신 명령줄에서 자동화 유틸리티를 실행할 수 있습니다. 다음 명령을 사용합니다.<pre># Run actual automation<br />python3 main.py</pre> | DevOps | 

### PRs 및 변경 사항 검증
<a name="validate-prs-and-changes"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 생성된 PRs 및 변경 사항을 검토합니다. | GitHub 워크플로 실행 결과를 모니터링하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-automated-pull-requests-for-terraform-managed-aws-infrastructure.html) | DevOps | 

### 정리
<a name="clean-up"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| (선택 사항) 정리. | 중단되거나 불필요한 PRs 닫습니다. | DevOps | 

## 관련 리소스
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-resources"></a>

**AWS 권장 가이드**
+ [Terraform을의 IaC 도구로 사용 AWS 클라우드](https://docs.aws.amazon.com/prescriptive-guidance/latest/choose-iac-tool/terraform.html)

**GitHub 설명서**
+ [풀 요청 정보](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests)
+ 개인용 액세스 토큰 관리
+ [GitHub 작업 이해](https://docs.github.com/en/actions/get-started/understand-github-actions)
+ [GitHub 작업을 위한 빠른 시작](https://docs.github.com/en/actions/get-started/quickstart)

# Java 및 Python 프로젝트를 위한 동적 CI 파이프라인을 자동으로 생성
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically"></a>

*Aromal Raj Jayarajan, Vijesh Vijayakumaran Nair, MAHESH RAGHUNANDANAN, Amarnath Reddy, Amazon Web Services*

## 요약
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-summary"></a>

이 패턴은 AWS 개발자 도구를 사용하여 Java 및 Python 프로젝트를 위한 동적 지속적 통합(CI) 파이프라인을 자동으로 생성하는 법을 보여줍니다.

기술 스택이 다양해지고 개발 활동이 증가하면 조직 전체에서 일관된 CI 파이프라인을 만들고 유지 관리하기가 어려워질 수 있습니다. AWS Step Functions에서 프로세스를 자동화하면 CI 파이프라인의 사용 및 접근 방식이 일관되도록 할 수 있습니다.

동적 CI 파이프라인 생성을 자동화하기 위해 이 패턴은 다음과 같은 변수 입력을 사용합니다.
+ 프로그래밍 언어(Java 또는 Python만 해당)
+ 파이프라인 이름
+ 필수 파이프라인 단계

**참고**  
Step Functions는 여러 AWS 서비스를 사용하여 파이프라인 생성을 오케스트레이션합니다. 이 솔루션에서 사용되는 AWS 서비스에 대한 자세한 내용은 이 패턴의 **도구** 섹션을 참조하십시오.

## 사전 조건 및 제한 사항
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정
+ 이 솔루션이 배포되는 동일한 AWS 리전에 있는 Amazon S3 버킷
+ 이 솔루션에 필요한 리소스를 생성하는 데 필요한 AWS CloudFormation 권한을 가진 AWS Identity and Access Management(IAM) [보안 주체](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html)

**제한 사항 **
+ 이 패턴은 Java 및 Python 프로젝트만 지원합니다.
+ 이 패턴에 프로비저닝된 IAM 역할은 최소 권한 원칙을 따릅니다. IAM 역할의 권한은 CI 파이프라인이 생성해야 하는 특정 리소스를 기반으로 업데이트되어야 합니다.

## 아키텍처
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-architecture"></a>

**대상 기술 스택**
+ AWS CloudFormation
+ AWS CodeBuild
+ AWS CodeCommit
+ AWS CodePipeline
+ IAM
+ Amazon Simple Storage Service(S3)
+ AWS Systems Manager
+ AWS Step Functions
+ AWS Lambda
+ Amazon DynamoDB

**대상 아키텍처·**

다음 다이어그램은 AWS 개발자 도구를 사용하여 Java 및 Python 프로젝트용 동적 CI 파이프라인을 자동으로 생성하는 예제 워크플로를 보여줍니다.

![\[AWS 도구를 사용하여 Java 및 Python 프로젝트를 위한 동적 CI 파이프라인을 자동으로 생성하는 워크플로.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/bef2ccb8-68b3-4c0f-9ee7-4b93e9422d9c/images/b5ed003f-cf16-4130-8bfb-2bc2cb9a0d33.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. AWS 사용자는 CI 파이프라인 생성을 위한 입력 파라미터를 JSON 형식으로 제공합니다. 이 입력은 AWS 개발자 도구를 사용하여 CI 파이프라인을 생성하는 Step Functions 워크플로(*상태 머신*)를 시작합니다.

1. Lambda 함수는 Amazon S3 버킷에 저장된 **input-reference**라는 이름의 폴더를 읽은 다음 **buildspec.yml** 파일을 생성합니다. 이렇게 생성된 파일은 CI 파이프라인 단계를 정의하며 파라미터 참조를 저장하는 동일한 Amazon S3 버킷에 다시 저장됩니다.

1. Step Functions는 CI 파이프라인 생성 워크플로의 종속성에 변경 사항이 있는지 확인하고 필요에 따라 종속성 스택을 업데이트합니다.

1. Step Functions는 CodeCommit 리포지토리, CodeBuild 프로젝트, CodePipeline 파이프라인을 비롯한 CI 파이프라인 리소스를 CloudFormation 스택에 생성합니다.

1. CloudFormation 스택은 선택된 기술 스택(Java 또는 Python)의 샘플 소스 코드와 **buildspec.yml** 파일을 CodeCommit 리포지토리에 복사합니다.

1. CI 파이프라인 런타임 세부 정보는 DynamoDB 테이블에 저장됩니다.

**자동화 및 규모 조정**
+ 이 패턴은 단일 개발 환경에서만 사용할 수 있습니다. 여러 개발 환경에서 사용하려면 구성을 변경해야 합니다.
+ 한 개 이상의 CloudFormation 스택에 대한 지원을 추가하기 위해 CloudFormation 템플릿을 추가로 생성할 수 있습니다. 자세한 내용은 CloudFormation 설명서의 [AWS CloudFormation로 시작하기](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/GettingStarted.html) 항목을 참조하십시오.

## 도구
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-tools"></a>

**도구**
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)은 Lambda 함수와 기타 AWS 서비스를 결합할 수 있는 서버리스 오케스트레이션 서비스로, 비즈니스 크리티컬 애플리케이션을 구축합니다.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행할 수 있도록 도와주는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 나만의 소스 제어 시스템을 관리할 필요 없이 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 버전 제어 서비스입니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.
+ [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)를 사용하면 암호화 키를 생성하고 제어하여 데이터를 보호할 수 있습니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)을 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, 전체 AWS 계정 및 리전에서 수명 주기 전반에 걸쳐 관리할 수 있습니다.
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)는 빠르고 예측 가능하고 확장 가능한 성능을 제공하는 완전 관리형 NoSQL 데이터베이스 서비스입니다.
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)는 구성 데이터 관리 및 암호 관리를 위한 안전한 계층적 스토리지를 제공합니다.

**코드**

이 패턴의 코드는 GitHub [automated-ci-pipeline-creation](https://github.com/aws-samples/automated-ci-pipeline-creation) 리포지토리에서 사용할 수 있습니다. 리포지토리에는 이 패턴에 설명된 대상 아키텍처를 생성하는 데 필요한 CloudFormation 템플릿이 포함되어 있습니다.

## 모범 사례
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-best-practices"></a>
+ 토큰이나 암호와 같은 보안 인증(*보안 암호*)을 CloudFormation 템플릿 또는 단계 함수 작업 구성에 직접 입력하지 마십시오. 그러면 DynamoDB 로그에 정보가 표시됩니다. 대신 AWS Secrets Manager를 사용하여 보안 정보를 설정하고 저장하십시오. 그런 다음 필요에 따라 CloudFormation 템플릿 및 Step Functions 작업 구성 내에서 Secrets Manager에 저장된 보안 정보를 참조할 수 있습니다. 자세한 내용은 AWS Secrets Manager 사용 설명서의 [AWS Secrets Manager란 무엇입니까?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)를 참조하십시오.
+ Amazon S3에 저장된 CodePipeline 아티팩트에 대해 서버 측 암호화를 구성하십시오. 자세한 내용은 CodePipeline 설명서에서 [CodePipeline용 Amazon S3에 저장된 아티팩트에 대한 서버 측 암호화 구성](https://docs.aws.amazon.com/codepipeline/latest/userguide/S3-artifact-encryption.html)을 참조하십시오.
+ IAM 역할을 구성할 때 최소 권한을 적용합니다. 자세한 내용은 IAM 설명서의 [최소 권한 적용](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)을 참조하십시오.
+ Amazon S3 버킷에 공개적으로 액세스할 수 없어야 합니다. 자세한 내용은 Amazon S3 설명서의 [S3 버킷에 대한 퍼블릭 액세스 차단 설정 구성](https://docs.aws.amazon.com/AmazonS3/latest/userguide/configuring-block-public-access-bucket.html)을 참조하십시오.
+ Amazon S3 버킷에 대한 버전 관리를 활성화해야 합니다. 자세한 내용은 Amazon S3 버킷 설명서의 [S3 버킷에서 버전 관리 사용](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html)을 참조하십시오.
+ IAM 정책을 구성할 때는 IAM Access Analyzer를 사용하십시오. 이 도구는 안전하고 기능적인 IAM 정책을 작성하는 데 도움이 되는 실행 가능한 권장 사항을 제공합니다. 자세한 내용은 IAM 설명서의 [AWS Identity 및 Access Management Access Analyzer 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html)을 참조하십시오.
+ 가능하면 IAM 정책을 구성할 때 특정 액세스 조건을 정의하십시오.
+ 모니터링 및 감사 목적으로 Amazon CloudWatch 로깅을 활성화하십시오. 자세한 내용은 CloudWatch 사용 설명서에서 [Amazon CloudWatch Logs란 무엇입니까?](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)를 참조하십시오.

## 에픽
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-epics"></a>

### 필수 구성 요소 구성
<a name="configure-the-prerequisites"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon S3 버킷을 생성합니다. | Amazon S3 버킷을 생성(또는 기존 버킷 사용) 하여 솔루션에 필요한 CloudFormation 템플릿, 소스 코드 및 입력 파일을 저장합니다.자세한 내용은 Amazon S3 설명서의 [1단계: 첫 S3 버킷 생성](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-bucket.html)을 참조하십시오.Amazon S3 버킷은 솔루션을 배포하는것과 동일한 AWS 리전에 있어야 합니다. | DevOps | 
| GitHub 리포지토리를 복제합니다. | 터미널 창에 다음 명령을 실행하여 GitHub [automated-ci-pipeline-creation](https://github.com/aws-samples/automated-ci-pipeline-creation) 리포지토리를 복제합니다.<pre>git clone https://github.com/aws-samples/automated-ci-pipeline-creation.git</pre>자세한 내용은 GitHub 설명서의 [리포지토리 복제](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)를 참조하십시오. | AWS DevOps | 
| 복제된 GitHub 리포지토리의 솔루션 템플릿 폴더를 Amazon S3 버킷으로 업로드합니다. | 복제된 **솔루션-템플릿** 폴더에서 콘텐츠를 복사하여 생성한 Amazon S3 버킷에 업로드합니다.자세한 내용은 Amazon S3 설명서의 [객체 업로드](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)를 참조하십시오.**Solution-Templates** 폴더의 콘텐츠만 업로드해야 합니다. Amazon S3 버킷의 루트 수준에서만 파일을 업로드할 수 있습니다. | AWS DevOps | 

### 솔루션 배포
<a name="deploy-the-solution"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 복제된 GitHub 리포지토리의 template.yml 파일을 사용하여 솔루션을 배포할 CloudFormation 스택을 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html)스택이 생성되는 동안 [**스택(Stacks)**] 페이지에 **CREATE\$1IN\$1PROGRESS** 상태로 나열됩니다. 이 패턴의 나머지 단계를 완료하기 전에 스택 상태가 **CREATE\$1COMPLETE**로 변경될 때까지 기다려야 합니다. | AWS 관리자, AWS DevOps | 

### 설정 테스트
<a name="test-the-setup"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 생성한 Step Function을 실행합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html)**JSON 형식**<pre>{<br />  "details": {<br />    "tech_stack": "Name of the Tech Stack (python/java)",<br />    "project_name": "Name of the Project that you want to create with",<br />    "pre_build": "Choose the step if it required in the buildspec.yml file i.e., yes/no",<br />    "build": "Choose the step if it required in the buildspec.yml file i.e., yes/no",<br />    "post_build": "Choose the step if it required in the buildspec.yml file i.e., yes/no",<br />    "reports": "Choose the step if it required in the buildspec.yml file i.e., yes/no",<br />  }<br />}</pre>**Java JSON 입력 예제**<pre>{<br />  "details": {<br />    "tech_stack": "java",<br />    "project_name": "pipeline-java-pjt",<br />    "pre_build": "yes",<br />    "build": "yes",<br />    "post_build": "yes",<br />    "reports": "yes"<br />  }<br />}</pre>**Python JSON 입력 예제**<pre>{<br />  "details": {<br />    "tech_stack": "python",<br />    "project_name": "pipeline-python-pjt",<br />    "pre_build": "yes",<br />    "build": "yes",<br />    "post_build": "yes",<br />    "reports": "yes"<br />  }<br />}</pre> | AWS 관리자, AWS DevOps | 
| CI 파이프라인의 CodeCommit 리포지토리가 생성되었는지 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 
| CodeBuild 프로젝트 리소스를 확인하십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 
| CodePipeline 단계를 검증합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 
| CI 파이프라인이 성공적으로 실행되었는지 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 

### 리소스 정리
<a name="clean-up-your-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CloudFormation에서 리소스 스택을 삭제합니다. | CloudFormation에서 CI 파이프라인의 리소스 스택을 삭제합니다.자세한 내용은 CloudFormation 설명서의 [AWS CloudFormation 콘솔에서 스택 삭제](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html)를 참조하십시오.**<project\$1name>-stack**이라는 이름의 스택을 삭제해야 합니다. | DevOps | 
| Amazon S3와 CloudFormation에서 CI 파이프라인의 종속성을 삭제합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html)**pipeline-creation-dependencies-stack** 이름의 스택을 삭제해야 합니다. | DevOps | 
| Amazon S3 탬플릿 버킷을 삭제하십시오. | 이 솔루션의 템플릿을 저장하는 해당 패턴의 **사전 조건 구성** 섹션에서 생성한 Amazon S3 버킷을 삭제합니다.자세한 내용은 Amazon S3 설명서의 [버킷 삭제](https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-bucket.html)를 참조하십시오. | AWS DevOps | 

## 관련 리소스
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-resources"></a>
+ [Lambda를 사용하는 Step Functions 상태 시스템 생성](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-creating-lambda-state-machine.html)(AWS Step Functions 설명서)
+ [AWS Step Functions WorkFlow Studio](https://docs.aws.amazon.com/step-functions/latest/dg/workflow-studio.html)(AWS Step Functions 설명서)
+ [DevOps 및 AWS](https://aws.amazon.com/devops/)
+ [AWS CloudFormation 작동 방식](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-howdoesitwork.html) (AWS CloudFormation 설명서)
+ [Complete CI/CD with AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline](https://aws.amazon.com/blogs/devops/complete-ci-cd-with-aws-codecommit-aws-codebuild-aws-codedeploy-and-aws-codepipeline/)(AWS Blog 게시물)
+ [IAM 및 AWS STS 할당량, 이름 요구 사항 및 문자 제한](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)(IAM 설명서)

# Terraform을 사용하여 CloudWatch Synthetics canary 배포
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform"></a>

*Dhrubajyoti Mukherjee, Jean-Francois Landreau, Amazon Web Services*

## 요약
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-summary"></a>

고객 관점에서 시스템 상태를 검증하고 고객이 연결할 수 있는지 확인하는 것이 중요합니다. 고객이 엔드포인트에 계속 직접 호출하지 않을 때는 더 어려워집니다. [Amazon CloudWatch Synthetics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)는 퍼블릭 엔드포인트와 프라이빗 엔드포인트를 모두 테스트할 수 있는 canary 생성을 지원합니다. Canary를 사용하면 사용 중이 아닌 경우에도 시스템 상태를 알 수 있습니다. 이 canary는 Node.js Puppeteer 스크립트 또는 Python Selenium 스크립트입니다.

이 패턴은 HashiCorp Terraform을 사용하여 프라이빗 엔드포인트를 테스트하는 canary를 배포하는 방법을 설명합니다. 여기에는 URL이 `200-OK`를 반환되는지 여부를 테스트하는 Puppeteer 스크립트가 포함되어 있습니다. 그런 다음 Terraform 스크립트를 프라이빗 엔드포인트를 배포하는 스크립트와 통합할 수 있습니다. 또한 퍼블릭 엔드포인트를 모니터링하도록 솔루션을 수정할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-prereqs"></a>

**사전 조건**
+ Virtual Private Cloud(VPC)와 프라이빗 서브넷이 있는 활성 Amazon Web Services(AWS) 계정
+ 프라이빗 서브넷에서 연결할 수 있는 엔드포인트의 URL
+ 배포 환경에 Terraform 설치

**제한 사항**

현재 솔루션은 다음과 같은 CloudWatch Synthetics 런타임 버전에서 작동합니다.
+ syn-nodejs-puppeteer-3.4
+ syn-nodejs-puppeteer-3.5
+ syn-nodejs-puppeteer-3.6
+ syn-nodejs-puppeteer-3.7

새 런타임 버전이 출시되면 현재 솔루션을 업데이트해야 할 수 있습니다. 또한 보안 업데이트에 뒤쳐지지 않도록 솔루션을 수정해야 합니다.

**제품 버전**
+ Terraform 1.3.0

## 아키텍처
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-architecture"></a>

Amazon CloudWatch Synthetics는 CloudWatch, Lambda 및 Amazon Simple Storage Service(S3)를 기반으로 합니다. Amazon CloudWatch는 canary를 생성하는 마법사와 canary 실행 상태를 표시하는 대시보드를 제공합니다. Lambda 함수는 스크립트를 실행합니다. Amazon S3는 canary 실행의 로그와 스크린샷을 저장합니다.

이 패턴은 대상 서브넷에 배포된 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 통해 프라이빗 엔드포인트를 시뮬레이션합니다. Lambda 함수를 사용하려면 프라이빗 엔드포인트가 배포된 VPC에 탄력적 네트워크 인터페이스가 필요합니다.

![\[설명은 다이어그램을 따릅니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/73ed0103-ec45-4653-bb29-f402a88f0c64/images/39aaed0f-f259-4f2a-98fb-8e3a340d0b02.png)


이 다이어그램은 다음을 보여 줍니다.

1. Synthetics canary는 canary Lambda 함수를 시작합니다.

1. Canary Lambda 함수는 탄력적 네트워크 인터페이스에 연결됩니다.

1. Canary Lambda 함수는 엔드포인트의 상태를 모니터링합니다.

1. Synthetics canary는 실행 데이터를 S3 버킷 및 CloudWatch 지표로 푸시합니다.

1. CloudWatch 경보는 지표를 기반으로 시작됩니다.

1. CloudWatch 경보는 Amazon Simple Notification Service(SNS) 주제를 시작합니다.

## 도구
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-tools"></a>

**서비스**
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)는 AWS 리소스와 AWS에서 실시간으로 실행되는 애플리케이션의 지표를 모니터링하는 데 도움이 됩니다.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행할 수 있도록 도와주는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [Amazon Simple Notification Service(Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)를 사용하면 웹 서버 및 이메일 주소를 포함하여 게시자와 클라이언트 간의 메시지 교환을 조정하고 관리할 수 있습니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.
+ [Amazon Virtual Private Cloud(VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)를 사용하면 사용자가 정의한 가상 네트워크로 AWS 리소스를 시작할 수 있습니다. 이 가상 네트워크는 사용자의 자체 데이터 센터에서 운영하는 기존 네트워크와 유사하며 AWS의 확장 가능한 인프라를 사용한다는 이점이 있습니다. 이 패턴은 VPC 엔드포인트와 탄력적 네트워크 인터페이스를 사용합니다.

**기타 서비스**
+ [HashiCorp Terraform](https://www.terraform.io/docs)은 코드를 사용하여 클라우드 인프라 및 리소스를 프로비저닝하고 관리하는 데 도움이 되는 오픈 소스 코드형 인프라(IaC) 도구입니다. 이 패턴은 Terraform을 사용하여 인프라를 배포합니다.
+ [Puppeteer](https://pptr.dev/)는 Node.js 라이브러리입니다. CloudWatch Synthetics 런타임은 Puppeteer 프레임워크를 사용합니다.

**코드**

이 솔루션은 GitHub [cloud watch-synthetics-canary-terraform](https://github.com/aws-samples/cloudwatch-synthetics-canary-terraform) 리포지토리에서 사용할 수 있습니다. 자세한 내용은 *추가 정보* 섹션을 참조하세요.

## 에픽
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-epics"></a>

### 프라이빗 URL 모니터링 솔루션 구현
<a name="implement-the-solution-for-monitoring-a-private-url"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 프라이빗 URL 모니터링을 위한 요구 사항을 수집하십시오. | 전체 URL 정의(도메인, 파라미터, 헤더)를 수집하십시오. Amazon S3 및 Amazon CloudWatch와 비공개로 통신하려면 VPC 엔드포인트를 사용하십시오. 엔드포인트에서 VPC와 서브넷에 어떻게 액세스할 수 있는지 확인하십시오. Canary 실행 빈도를 생각해 보십시오. | 클라우드 아키텍트, 네트워크 관리자 | 
| 기존 솔루션을 수정하여 프라이빗 URL을 모니터링하십시오. | `terraform.tfvars` 파일을 수정합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-cloudwatch-synthetics-canaries-by-using-terraform.html) | 클라우드 아키텍트 | 
| 솔루션을 배포 및 운영합니다. | 솔루션을 배포하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-cloudwatch-synthetics-canaries-by-using-terraform.html) | 클라우드 아키텍트, DevOps 엔지니어 | 

## 문제 해결
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 프로비저닝된 리소스 삭제가 중단됩니다. | Canary Lambda 함수, 해당하는 탄력적 네트워크 인터페이스 및 보안 그룹을 순서대로 수동으로 삭제합니다. | 

## 관련 리소스
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-resources"></a>
+ [Synthetics 모니터링 사용](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)
+ [Amazon CloudWatch Synthetics를 사용하여 API Gateway 엔드포인트 모니터링](https://aws.amazon.com/blogs/mt/monitor-api-gateway-endpoints-with-amazon-cloudwatch-synthetics/)(블로그 게시물)

## 추가 정보
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-additional"></a>

**리포지토리 아티팩트**

리포지토리 아티팩트의 구조는 다음과 같습니다.

```
.
├── README.md
├── main.tf
├── modules
│   ├── canary
│   └── canary-infra
├── terraform.tfvars
├── tf.plan
└── variable.tf
```

`main.tf` 파일은 코어 모듈을 포함하며 두 개의 하위 모듈을 배포합니다.
+ `canary-infra`는 canary에 필요한 인프라를 배포합니다.
+ `canary`는 canary를 배포합니다.

솔루션의 입력 파라미터는 `terraform.tfvars` 파일에 있습니다. 다음 코드 예제를 사용하여 canary 하나를 생성할 수 있습니다.

```
module "canary" {
    source = "./modules/canary"
    name   = var.name
    runtime_version = var.runtime_version
    take_screenshot = var.take_screenshot
    api_hostname = var.api_hostname
    api_path = var.api_path
    reports-bucket = module.canary_infra.reports-bucket
    role = module.canary_infra.role
    security_group_id = module.canary_infra.security_group_id
    subnet_ids = var.subnet_ids
    frequency = var.frequency
    alert_sns_topic = var.alert_sns_topic
}
```

해당.var 파일은 다음과 같습니다.

```
name   = "my-canary"
runtime_version = "syn-nodejs-puppeteer-3.7"
take_screenshot = false
api_hostname = "mydomain.internal"
api_path = "/path?param=value"
vpc_id = "vpc_id"
subnet_ids = ["subnet_id1"]
frequency = 5
alert_sns_topic = "arn:aws:sns:eu-central-1:111111111111:yyyyy"
```

**솔루션 정리하기**

개발 환경에서 테스트하는 경우 솔루션을 정리하여 비용이 발생하지 않도록 할 수 있습니다.

1. AWS Management Console에서 Amazon S3 콘솔로 이동합니다. 솔루션에서 생성한 Amazon S3 버킷을 비웁니다. 필요한 경우 데이터를 백업해야 합니다.

1. 개발 환경의 `cloudwatch-synthetics-canary-terraform` 디렉터리에서 `destroy` 명령을 실행합니다.

   ```
   terraform destroy
   ```

# 채팅 애플리케이션에서 Amazon Q Developer 사용자 지정 작업 및를 사용하여 SAST 스캔 결과를 관리하는 ChatOps 솔루션 배포 CloudFormation
<a name="deploy-chatops-solution-to-manage-sast-scan-results"></a>

*Anand Bukkapatnam Tirumala, Amazon Web Services*

## 요약
<a name="deploy-chatops-solution-to-manage-sast-scan-results-summary"></a>

이 패턴은 채팅 애플리케이션에서 Amazon Q Developer를 사용하여 SonarQube를 통해 보고된 정적 애플리케이션 보안 테스트(SAST) 스캔 실패 관리를 간소화하는 포괄적인 솔루션을 제공합니다. 이 혁신적인 접근 방식은 사용자 지정 작업과 알림을 대화형 인터페이스에 통합하여 개발 팀 내에서 효율적인 협업과 의사 결정 프로세스를 지원합니다.

오늘날의 빠른 속도의 소프트웨어 개발 환경에서 코드 품질과 보안을 유지하려면 SAST 스캔 결과를 효율적으로 관리하는 것이 중요합니다. 그러나 많은 조직이 다음과 같은 중요한 문제에 직면하고 있습니다.
+ 비효율적인 알림 시스템으로 인한 중요한 취약성에 대한 인식 지연
+ 연결 해제된 승인 워크플로로 인한 느린 의사 결정 프로세스
+ SAST 스캔 실패에 대한 즉각적이고 실행 가능한 응답 부족
+ 보안 조사 결과에 대한 세분화된 커뮤니케이션 및 협업
+ 보안 도구를 위한 시간이 많이 걸리고 오류가 발생하기 쉬운 수동 인프라 설정

이러한 문제로 인해 보안 리스크가 증가하고 릴리스가 지연되며 팀 생산성이 저하되는 경우가 많습니다. 이러한 문제를 효과적으로 해결하려면 SAST 결과 관리를 간소화하고 팀 협업을 개선하며 인프라 프로비저닝을 자동화할 수 있는 솔루션이 필요합니다.

솔루션의 주요 기능은 다음과 같습니다.
+ **사용자 지정 알림** - 실시간 알림 및 알림이 팀 채팅 채널로 직접 전송되므로 SAST 스캔 취약성 또는 장애에 대한 즉각적인 인식 및 조치를 보장할 수 있습니다.
+ **대화 승인** - 이해관계자는 채팅 인터페이스 내에서 SAST 스캔 결과에 대한 승인 워크플로를 원활하게 시작하고 완료하여 의사 결정 프로세스를 가속화할 수 있습니다.
+ **사용자 지정 작업** - 팀은 품질 게이트 장애에 대한 이메일 메시지 자동 트리거, 보안 문제에 대한 응답성 향상과 같은 SAST 스캔 결과를 기반으로 사용자 지정 작업을 정의하고 실행할 수 있습니다.
+ **중앙 집중식 협업** - 모든 SAST 스캔 관련 논의, 결정 및 조치는 통합된 채팅 환경 내에 유지되므로 팀원 간의 협업 및 지식 공유가 향상됩니다.
+ **코드형 인프라(IaC)** - 전체 솔루션은 AWS CloudFormation 템플릿으로 래핑되어 수동 설정 오류를 줄이면서 더 빠르고 안정적인 인프라 프로비저닝을 지원합니다.

## 사전 조건 및 제한 사항
<a name="deploy-chatops-solution-to-manage-sast-scan-results-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ [도구](#deploy-chatops-solution-to-manage-sast-scan-results-tools)에 AWS 서비스 나열된와 연결된 리소스를 생성하고 관리할 수 있는 권한이 있는 AWS Identity and Access Management (IAM) 역할입니다.
+ Slack 작업 영역
+ 채팅 애플리케이션의 Amazon Q Developer가 필요한 Slack 워크스페이스에 플러그인으로 추가되었습니다. 자세한 내용은 [Slack의 앱 설명서](https://slack.com/intl/en-in/help/articles/202035138-Add-apps-to-your-Slack-workspace)를 참조하세요. 등록에 성공한 AWS Management Console 후에 표시된 대로 Slack 워크스페이스 ID를 기록해 둡니다.
+  CloudFormation 콘솔에서 입력할 수 있는 워크스페이스 ID를 사용하여 채팅 애플리케이션 클라이언트에 구성된 Amazon Q Developer입니다. 지침은 *채팅 애플리케이션의 Amazon Q Developer 관리자 안내서의* [Slack 클라이언트 구성을](https://docs.aws.amazon.com/chatbot/latest/adminguide/slack-setup.html#slack-client-setup) 참조하세요.
+ 승인 이메일 메시지를 보내기 위해 Amazon Simple Email Service(Amazon SES)에서 생성 및 확인된 소스 이메일 계정입니다. 설정 지침은 *Amazon Simple Email Service 개발자 안내서*의 [이메일 자격 증명 생성 및 확인을 참조하세요](https://docs.aws.amazon.com/ses/latest/dg/creating-identities.html#verify-email-addresses-procedure).
+ 승인 알림을 수신할 대상 이메일 주소입니다. 이 주소는 공유 받은 편지함 또는 특정 팀 배포 목록일 수 있습니다.
+ 에서 액세스할 수 있는 운영 SonarQube 인스턴스입니다 AWS 계정. 자세한 내용은 [Karpenter 설치 지침](https://docs.sonarsource.com/sonarqube/latest/setup-and-upgrade/install-the-server/introduction/)을 참조하세요.
+ 파이프라인을 통해 프로젝트를 트리거하고 생성할 수 있는 권한이 있는 SonarQube[user 토큰](https://docs.sonarsource.com/sonarqube-server/latest/user-guide/managing-tokens/)입니다.

**제한 사항 **
+ 사용자 지정 작업 버튼 생성은이 솔루션의 수동 프로세스입니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) 섹션을 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="deploy-chatops-solution-to-manage-sast-scan-results-architecture"></a>

다음 다이어그램은 이 패턴의 워크플로 및 구성 요소를 보여 줍니다.

![\[Amazon Q Developer를 사용하여 릴리스 관리를 위한 자동화된 코드 품질 보증을 배포하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/198312ed-e379-49a7-b706-8e79e2142f21/images/a977924c-957e-4f91-99d6-ed790e343ea6.png)


다이어그램은 자동화된 코드 품질 보증 워크플로를 보여줍니다.

1. 코드 준비 및 업로드:
   + 개발자는 코드베이스를 .zip 파일로 압축합니다.
   + 개발자는 .zip 파일을 지정된 Amazon Simple Storage Service(Amazon S3) 버킷에 수동으로 업로드합니다.

1. Amazon S3 이벤트 트리거 및 AWS Step Functions 오케스트레이션:
   + Amazon S3 업로드 이벤트는 Step Functions 워크플로를 트리거합니다.
   + Step Functions는 SonarQube를 사용하여 SAST 스캔을 오케스트레이션합니다.
   + 워크플로는 AWS CodeBuild 작업 상태를 모니터링하여 다음 작업을 결정합니다. CodeBuild가 성공하면(품질 게이트 패스) 워크플로가 종료됩니다. CodeBuild가 실패하면 진단을 위해 AWS Lambda 함수가 호출됩니다. 자세한 내용은이 섹션 뒷부분의 **AWS Step Functions 로직**을 참조하세요.

1. AWS CodeBuild 실행:
   + CodeBuild 작업은 업로드된 코드베이스에서 SonarQube 스캔을 실행합니다.
   + 스캔 아티팩트는 감사 및 분석을 위해 별도의 Amazon S3 버킷에 저장됩니다.

1. 실패 분석(Lambda 함수):
   + CodeBuild 실패 시 `CheckBuildStatus` Lambda 함수가 트리거됩니다.
   + CodeBuild 성공 시 프로세스가 종료되고 추가 작업이 필요하지 않습니다.

1. Lambda 함수는 장애 원인(품질 게이트 장애 또는 기타 문제)을 분석합니다.
   + `CheckBuildStatus` 함수는 자세한 실패 정보가 포함된 사용자 지정 페이로드를 생성합니다.
   + `CheckBuildStatus` 함수는 사용자 지정 페이로드를 Amazon Simple Notification Service(Amazon SNS) 주제에 게시합니다.

1.  이메일 알림
   + Amazon SNS는 Slack 통합을 위한 채팅 애플리케이션에서 Amazon Q Developer에 페이로드를 전달합니다.

1.  Slack 통합
   + 채팅 애플리케이션의 Amazon Q Developer는 지정된 Slack 채널에 알림을 게시합니다.

1. 승인 프로세스:
   + 승인자는 Slack 알림의 실패 세부 정보를 검토합니다.
   + 승인자는 Slack의 **승인** 버튼을 사용하여 승인을 시작할 수 있습니다.

1. 승인 핸들러:
   + 승인 Lambda 함수는 Slack의 승인 작업을 처리합니다.
   + 승인 함수는 사용자 지정 메시지를 Amazon SES에 게시합니다.

1. 메시지 생성
   + Approval 함수는 개발자 알림을 위한 사용자 지정 메시지를 생성합니다.

1. 개발자 알림:
   + Amazon SES는 다음 단계 또는 필요한 작업이 포함된 이메일 메시지를 개발자에게 보냅니다.

이 워크플로는 수동 코드 업로드와 자동화된 품질 검사를 결합하고, Slack을 통해 즉각적인 피드백을 제공하고, 필요한 경우 사람의 개입을 허용하여 강력하고 유연한 코드 검토 프로세스를 보장합니다.

**AWS Step Functions  ** 로직

이전 아키텍처 다이어그램에서 볼 수 있듯이 SonarQube에서 품질 게이트 전달이 실패하면 워크플로가 `CheckBuildStatus` Lambda 함수로 이동합니다. `CheckBuildStatus` 함수는 Slack 채널에서 알림을 트리거합니다. 각 알림에는 제안된 다음 단계가 포함된 정보가 포함됩니다. 다음 트래픽 유형은 기록되지 않습니다.
+ **애플리케이션이 코드 보안 스캔에 실패했습니다 **- 업로드된 코드가 SonarQube 보안 스캔을 통과하지 못한 경우 사용자가이 알림을 받습니다. 사용자는 **승인을** 선택하여 빌드를 수락할 수 있습니다. 그러나 이 알림은 사용자에게 코드 품질 저하 및 보안 리스크 발생 가능성을 주의하도록 조언합니다. 이 알림에는 다음 정보가 포함됩니다.
  + 다음 단계: 오류: 품질 게이트 상태: 실패 - 제공된 URL에서 세부 정보를 봅니다.
  + 문서에 언급된 대로 제공된 URL에서 취약성을 분류합니다.
  + CodeBuild 세부 정보는 제공된 URL의 위치에서 확인할 수 있습니다.
+ **다른 이유로 인해 애플리케이션 스캔 파이프라인이 실패함** - 사용자가 코드 보안 스캔 실패 이외의 다른 이유로 파이프라인이 실패하면이 알림을 받습니다. 이 알림에는 다음 정보가 포함됩니다.
  + 다음 단계는 추가 문제 해결을 위해 제공된 링크로 이동합니다.

Slack 채널에 표시되는 알림의 스크린샷을 보려면 GitHub chatops-slack 리포지토리의 [자산 폴더](https://github.com/aws-samples/chatops-slack/tree/main/assets)로 이동합니다.

다음 다이어그램은 품질 게이트 통과가 실패한 후 Step Functions 단계 상태의 예를 보여줍니다.

![\[품질 게이트 통과가 실패한 후 AWS Step Functions 단계 상태의 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/198312ed-e379-49a7-b706-8e79e2142f21/images/40b7ebf0-2518-4413-9717-0bfb7559adde.png)


## 도구
<a name="deploy-chatops-solution-to-manage-sast-scan-results-tools"></a>

**AWS 서비스**
+ [채팅 애플리케이션의 Amazon Q Developer](https://docs.aws.amazon.com/chatbot/latest/adminguide/what-is.html)를 사용하면 Amazon Chime, Microsoft Teams 및 Slack 채팅 채널을 사용하여 AWS 애플리케이션의 운영 이벤트를 모니터링하고 대응할 수 있습니다. *지원 종료 공지:* 2026년 2월 20일에 AWS 는 Amazon Chime 서비스에 대한 지원을 종료합니다. 2026년 2월 20일 이후에는 Amazon Chime 콘솔 또는 Amazon Chime 애플리케이션 리소스에 더 이상 액세스할 수 없습니다. 자세한 내용은 이 [블로그 게시물](https://aws.amazon.com/blogs/messaging-and-targeting/update-on-support-for-amazon-chime/)을 참조하세요. 이는 [Amazon Chime SDK 서비스의](https://aws.amazon.com/chime/chime-sdk/) 가용성에 영향을 주지 않습니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, AWS 계정 및의 수명 주기 동안 리소스를 관리할 수 있습니다 AWS 리전.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [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)를 사용하면 암호화 키를 생성하고 제어하여 데이터를 보호할 수 있습니다.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)를 이용하면 코드의 시크릿을 포함해 하드 코딩된 보안 인증을 Secrets Manager에서 프로그래밍 방식으로 시크릿을 검색하도록 하는 API 호출로 바꿀 수 있습니다.
+ [Amazon Simple Email Service(Amazon SES)](https://docs.aws.amazon.com/ses/latest/dg/Welcome.html)를 사용하면 자신의 이메일 주소와 도메인을 사용하여 이메일을 보내고 받을 수 있습니다.
+ [Amazon Simple Notification Service(Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)를 사용하면 웹 서버 및 이메일 주소를 포함하여 게시자와 클라이언트 간의 메시지 교환을 조정하고 관리할 수 있습니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)는 AWS Lambda 함수 및 기타를 결합하여 비즈니스 크리티컬 애플리케이션을 구축하는 AWS 서비스 데 도움이 되는 서버리스 오케스트레이션 서비스입니다.

**기타 도구**
+ Salesforce 제품인 [Slack](https://slack.com/help/articles/115004071768-What-is-Slack-)은 채팅 및 비디오 협업을 제공하고, 코드 없이 프로세스를 자동화하고, 정보 공유를 지원하는 AI 기반 대화형 플랫폼입니다.
+ [SonarQube](https://docs.sonarsource.com/sonarqube/latest/user-guide/user-account/generating-and-using-tokens/)는 30개 이상의 언어, 프레임워크 및 IaC 플랫폼에서 코딩 문제를 감지하도록 설계된 온프레미스 분석 도구입니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [unloaddb2](https://github.com/aws-samples/chatops-slack) 리포지토리에서 확인할 수 있습니다.

## 모범 사례
<a name="deploy-chatops-solution-to-manage-sast-scan-results-best-practices"></a>
+ **CloudFormation 스택 관리** - CloudFormation 스택 실행 중에 오류가 발생하면 실패한 스택을 삭제하는 것이 좋습니다. 그런 다음 올바른 파라미터 값으로 다시 생성합니다. 이 접근 방식은 깨끗한 배포를 지원하며 잠재적 충돌이나 부분적인 구현을 방지하는 데 도움이 됩니다.
+ **공유 받은 편지함 이메일 구성** - `SharedInboxEmail` 파라미터를 구성할 때 모든 관련 개발자가 액세스할 수 있는 공통 배포 목록을 사용합니다. 이 접근 방식은 투명성을 높이고 중요한 알림이 관련 팀원에게 도달하는 데 도움이 됩니다.
+ **프로덕션 승인 워크플로** - 프로덕션 환경의 경우 빌드 승인에 사용되는 Slack 채널에 대한 액세스를 제한합니다. 지정된 승인자만이 채널의 구성원이어야 합니다. 이 관행은 명확한 책임 체인을 유지하고 중요한 변경 사항을 승인할 수 있는 사용자를 제한하여 보안을 강화합니다.
+ 최소 권한 원칙을 준수하고 작업을 수행하는 데 필요한 최소 권한을 부여하세요. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv) 및 [보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPracticesAndUseCases.html)를 참조하세요.

## 에픽
<a name="deploy-chatops-solution-to-manage-sast-scan-results-epics"></a>

### 초기 설정을 수행합니다.
<a name="perform-initial-setup"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리포지토리를 복제합니다. | 이 패턴에 대한 [chatops-slack](https://github.com/aws-samples/chatops-slack) 리포지토리를 복제하려면 다음 명령을 사용합니다.`git clone "git@github.com:aws-samples/chatops-slack.git"` | AWS DevOps,빌드 리드, DevOps 엔지니어, 클라우드 관리자 | 
| Lambda 코드(index.py)를 포함한 .zip 파일 | `CheckBuildStatus` 및 `ApprovalEmail` 기능에 대한 AWS Lambda 함수 코드의 .zip 파일을 생성합니다. 다음과 같은 명령들을 사용하여 작업을 생성합니다.<pre>cd chatops-slack/src</pre><pre>chmod -R 775 *</pre><pre>zip -r approval.zip approval</pre><pre>zip -r notification.zip notification</pre> | AWS DevOps,빌드 리드, DevOps 엔지니어, 클라우드 관리자 | 

### pre-requisite.yml 스택 파일 배포
<a name="deploy-the-pre-requisite-yml-stack-file"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `pre-requisite.yml` 스택 파일을 실행합니다. | `pre-requisite.yml` CloudFormation 스택 파일은 `app-security.yml` 스택 파일을 실행하기 전에 필요한 초기 리소스를 배포합니다. `pre-requisite.yml` 파일을 편집하여 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | AWS DevOps, AWS 시스템 관리자, DevOps 엔지니어 | 
| 덤프 파일을 Amazon S3 버킷에 업로드합니다. | 이전에 생성한 `notification.zip` 및 `approval.zip` 파일을 라는 Amazon S3 버킷에 업로드합니다`S3LambdaBucket`. `app-security.yml` CloudFormation 스택 파일은 `S3LambdaBucket`를 사용하여 Lambda 함수를 프로비저닝합니다. | AWS DevOps, AWS 시스템 관리자, DevOps 엔지니어 | 

### app-security.yml 스택 파일 실행
<a name="execute-the-app-security-yml-stack-file"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `app-security.yml` 스택 파일을 실행합니다. | `app-security.yml` 스택 파일은 알림 및 승인 시스템을 위해 나머지 인프라를 배포합니다. `app-security.yml` 파일을 편집하여 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | AWS DevOps, AWS 시스템 관리자, DevOps 엔지니어 | 
| 알림 테스트 | Notifications(알림) 섹션에서 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html)테스트 메시지가 성공적으로 전송되면 Slack 채널에 알림이 표시됩니다. 자세한 내용은 채팅 애플리케이션의 Amazon Q Developer 관리자 안내서의 [에서 Slack AWS 서비스 으로 알림 테스트를](https://docs.aws.amazon.com/chatbot/latest/adminguide/slack-setup.html#test-notifications-slack) 참조하세요. **  | AWS DevOps, AWS 시스템 관리자, DevOps 엔지니어 | 

### 승인 흐름 설정
<a name="set-up-approval-flow"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 사용자 지정 Lambda 작업을 구성합니다. | 사용자 지정 AWS Lambda 작업을 설정하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | AWS 관리자, AWS DevOps, 빌드 책임자, DevOps 엔지니어, Slack Admin | 
| 승인 흐름을 검증합니다. | 승인 흐름이 예상대로 작동하는지 확인하려면 Slack에서 **승인** 버튼을 선택합니다.Slackbot은 확인 문자열 **Approval Email이 성공적으로** 전송된 메시지 스레드에 대한 알림을 보내야 합니다. | AWS DevOps, AWS 시스템 관리자, DevOps 엔지니어 | 

## 문제 해결
<a name="deploy-chatops-solution-to-manage-sast-scan-results-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| Slack 구성 오류 | Slack 구성 오류와 관련된 문제 해결에 대한 자세한 내용은 *채팅 애플리케이션 관리자 안내서의 Amazon Q Developer에서 Amazon Q Developer* 문제 해결을 참조하세요. | 
| 다른 이유로 인해 스캔에 실패했습니다. | 이 오류는 코드 빌드 작업이 실패했음을 의미합니다. 문제를 해결하려면 메시지에 있는 링크로 이동합니다. 코드 빌드 작업이 실패하면 다음과 같은 원인이 있을 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | 

## 관련 리소스
<a name="deploy-chatops-solution-to-manage-sast-scan-results-resources"></a>

**AWS 설명서**
+ [Slack 클라이언트 구성](https://docs.aws.amazon.com/chatbot/latest/adminguide/slack-setup.html#slack-client-setup)
+ [사용자 지정 작업 생성](https://docs.aws.amazon.com/chatbot/latest/adminguide/custom-actions.html#creating-custom-actions)
+ 이메일 주소 자격 증명 생성
+ [자습서: Slack 시작하기](https://docs.aws.amazon.com/chatbot/latest/adminguide/slack-setup.html)

**기타 리소스**
+ [Slack 워크스페이스에 앱 추가](https://slack.com/intl/en-in/help/articles/202035138-Add-apps-to-your-Slack-workspace)(Slack 설명서)
+ [토큰 생성 및 사용](https://docs.sonarsource.com/sonarqube/latest/user-guide/user-account/generating-and-using-tokens/)(SonarQube 설명서)
+ [서버 설치 소개](https://docs.sonarsource.com/sonarqube/latest/setup-and-upgrade/install-the-server/introduction/)(SonarQube 설명서)

## 추가 정보
<a name="deploy-chatops-solution-to-manage-sast-scan-results-additional"></a>

이 솔루션은 릴리스 관리를 위한 채팅 애플리케이션의 Amazon Q Developer 사용자 지정 작업을 강조합니다. 그러나 특정 사용 사례에 맞게 Lambda 코드를 수정하고 그 위에 구축하여 솔루션을 재사용할 수 있습니다.

**CloudFormation 스택 파일의 파라미터**

다음 표에는 CloudFormation 스택 파일에 대한 파라미터와 설명이 나와 있습니다`pre-requisite.yml`.


| 
| 
| **Key(키)** | **설명** | 
| --- |--- |
| `StackName` | CloudFormation 스택 이름을 로 설정합니다. | 
| `S3LambdaBucket` | Lambda 소스 코드를 업로드한 기존 S3 버킷의 이름. 이름은 전역적으로 고유해야 합니다. | 
| `SonarToken` | 사전 조건에 설명된 SonarQube 사용자 토큰입니다. [사전 조건 및 제한 사항](#deploy-chatops-solution-to-manage-sast-scan-results-prereqs)  | 

다음 표에는 CloudFormation 스택 파일에 대한 파라미터와 설명이 나와 있습니다`app-security.yml`.


| 
| 
| **Key(키)** | **설명** | 
| --- |--- |
| `CKMSKeyArn` | 이 스택에서 생성된 IAM 역할 및 Lambda 함수에 사용되는 AWS KMS key Amazon 리소스 이름(ARN)입니다. | 
| `CKMSKeyId` | 이 스택에서 생성된 Amazon SNS 주제에 사용되는 AWS KMS key ID입니다. | 
| `EnvironmentType` | 애플리케이션 스캔 파이프라인 배포를 위한 클라이언트 환경의 이름입니다. 허용된 값의 드롭다운 목록에서 환경 이름을 선택합니다. | 
| `S3LambdaBucket` | 개정이 포함된 Amazon S3 버킷의 이름. | 
| `SESEmail` | 사전 조건에 설명된 대로 Amazon SES에 등록된 이메일 자격 증명의 이름입니다. [사전 조건 및 제한 사항](#deploy-chatops-solution-to-manage-sast-scan-results-prereqs) 이 자격 증명은 소스 이메일 주소입니다. | 
| `SharedInboxMail` | 스캔 알림이 전송되는 대상 이메일 주소입니다. | 
| `SlackChannelId` | 알림을 전송할 Slack 채널의 채널 ID입니다. 채널 ID를 찾으려면 Slack 앱의 채널 **세부 정보에서 채널** 이름을 마우스 오른쪽 버튼으로 클릭합니다. 채널 ID는 하단에 있습니다. | 
| `SlackWorkspaceId` | [사전 조건에 설명된 Slack 워크스페이스 ID입니다](#deploy-chatops-solution-to-manage-sast-scan-results-prereqs). Slack 워크스페이스 ID를 찾으려면에 로그인하고 채팅 애플리케이션 콘솔에서 Amazon Q Developer를 AWS Management Console연 다음 **구성된 클라이언트**, **Slack**, **WorkspaceID**를 선택합니다. | 
| `StackName` | CloudFormation 스택 이름을 로 설정합니다. | 
| `SonarFileDirectory` | Data Pump 파일이 포함된 디렉터리입니다. | 
| `SonarFileName` | 파일 이름입니다 | 
| `SourceCodeZip` | 파일과 소스 코드가 포함된 .zip `sonar.project.<env>properties` 파일의 이름입니다. | 

# Terraform을 사용하여 CrewAI 프레임워크를 사용하여 Amazon Bedrock에 에이전트 시스템 배포
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework"></a>

*Vanitha Dontireddy, Amazon Web Services*

## 요약
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-summary"></a>

이 패턴은 [Amazon Bedrock](https://aws.amazon.com/bedrock/?nc1=h_ls) 및 [Terraform](https://registry.terraform.io/)과 통합된 [CrewAI](https://www.crewai.com/) 프레임워크를 사용하여 확장 가능한 다중 에이전트 AI 시스템을 구현하는 방법을 보여줍니다. 이 솔루션을 통해 조직은 코드형 인프라(IaC)를 통해 정교한 AI 에이전트 워크플로를 생성, 배포 및 관리할 수 있습니다. 이 패턴에서 CrewAI 다중 에이전트 오케스트레이션 기능은 Amazon Bedrock 파운데이션 모델 및 Terraform 인프라 자동화와 결합됩니다. 따라서 팀은 최소한의 인적 감독으로 복잡한 작업을 처리하는 프로덕션 지원 AI 시스템을 구축할 수 있습니다. 이 패턴은 엔터프라이즈급 보안, 확장성 및 운영 모범 사례를 구현합니다.

## 사전 조건 및 제한 사항
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-prereqs"></a>

**사전 조건 **
+ [Amazon Bedrock 파운데이션 모델에 액세스할](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) 수 있는 적절한 권한이 AWS 계정 있는 활성
+ Terraform 버전 1.5 이상 [설치](https://developer.hashicorp.com/terraform/install)
+ Python 버전 3.9 이상 [설치](https://www.python.org/downloads/)됨
+ CrewAI 프레임워크 [설치](https://docs.crewai.com/installation)됨

**제한 사항 **
+ 에이전트 상호 작용은 모델 컨텍스트 기간에 따라 제한됩니다.
+ 대규모 배포에 대한 Terraform 상태 관리 고려 사항이이 패턴에 적용됩니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-architecture"></a>

이 패턴에서는 다음과 같은 상호 작용이 발생합니다.
+ Amazon Bedrock은 파운데이션 모델(FMs) 제품군을 통해 에이전트 인텔리전스의 기반을 제공합니다. 이를 통해 AI 에이전트의 자연어 처리(NLP), 추론 및 의사 결정 기능을 지원하는 동시에 고가용성 및 확장성을 유지할 수 있습니다.
+ CrewAI 프레임워크는 AI 에이전트를 생성하고 관리하기 위한 핵심 오케스트레이션 계층 역할을 합니다. Amazon Bedrock과 통합하면서 에이전트 통신 프로토콜, 작업 위임 및 워크플로 관리를 처리합니다.
+ Terraform은 컴퓨팅 리소스, 네트워킹, 보안 그룹 및 AWS Identity and Access Management (IAM) 역할을 포함하여 코드를 통해 전체 인프라 스택을 관리합니다. 환경 간에 일관되고 버전 관리된 배포를 보장합니다. Terraform 배포는 다음을 생성합니다.
  + AWS Lambda CrewAI 애플리케이션을 실행하는 함수
  + 리포지토리를 내보내기 위한 Amazon Simple Storage Service(S3) 버킷
  + 적절한 권한이 있는 IAM 역할입니다.
  + Amazon CloudWatch 로깅
  + Amazon EventBridge에서 예약된 실행

다음 다이어그램은 Amazon Bedrock 및 Terraform을 사용하여 CrewAI 다중 에이전트 시스템을 배포하기 위한 아키텍처를 보여줍니다.

![\[Terraform 및 Amazon Bedrock을 사용하여 CrewAI 다중 에이전트 시스템을 배포하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/b46069e9-4c38-405f-b0f0-310eabb06b06/images/b3296b17-e388-46ba-8d71-2ec7ce3ed3e0.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 사용자가 리포지토리를 복제합니다.

1. 사용자가 명령을 실행`terraform apply`하여 AWS 리소스를 배포합니다.

1. Amazon Bedrock 모델 구성에는 CrewAI 에이전트를 구성하는 데 사용할 파운데이션 모델(FM)을 지정하는 작업이 포함됩니다.

1. EventBridge 규칙은 정의된 일정에 따라 Lambda 함수를 트리거하도록 설정됩니다.

1. 트리거되면(일정에 따라 또는 수동으로) Lambda 함수는 및 Amazon Bedrock에 액세스할 수 있는 권한이 있는 IAM 역할을 초기화 AWS 서비스 하고 수임합니다.

1. CrewAI 프레임워크는 YAML 파일에서 에이전트 구성을 로드하고 특수 AI 에이전트(*AWS 인프라 보안 감사* 팀)를 생성합니다. Lambda 함수는 이러한 에이전트를 순차적으로 실행하여 AWS 리소스를 스캔하고, 보안 취약성을 분석하고, 포괄적인 감사 보고서를 생성합니다.

1. CloudWatch Logs는 365일의 보존 기간과 규정 준수 요구 사항에 대한 AWS Key Management Service (AWS KMS) 암호화를 사용하여 Lambda 함수에서 자세한 실행 정보를 캡처합니다. 로그는 에이전트 활동, 오류 추적 및 성능 지표에 대한 가시성을 제공하여 보안 감사 프로세스의 효과적인 모니터링 및 문제 해결을 지원합니다.

1. 보안 감사 보고서가 자동으로 생성되어 지정된 Amazon S3 버킷에 저장됩니다. 자동 설정은 운영 오버헤드를 최소화하면서 일관된 보안 모니터링을 유지하는 데 도움이 됩니다.

초기 배포 후 워크플로는 수동 개입 없이 AWS 인프라에 대한 지속적인 보안 감사 및 보고를 제공합니다.

**AI 에이전트 개요**

이 패턴은 각각 고유한 역할, 목표 및 도구를 가진 여러 AI 에이전트를 생성합니다.
+ **보안 분석가 에이전트**는 AWS 리소스 정보를 수집하고 분석합니다.
+ **침투 테스터 에이전트**는 AWS 리소스의 취약성을 식별합니다.
+ **규정 준수 전문가 에이전트**는 규정 준수 표준을 기준으로 구성을 확인합니다.
+ **보고서 작성기 에이전트**는 조사 결과를 포괄적인 보고서로 컴파일합니다.

이러한 에이전트는 보안 감사를 수행하고 포괄적인 보고서를 생성하기 위해 집합적 기술을 활용하여 일련의 작업에 협업합니다. (이 `config/agents.yaml` 파일에는이 트러프에 있는 각 에이전트의 기능과 구성이 요약되어 있습니다.)

보안 분석 처리는 다음 작업으로 구성됩니다.

1. 보안 분석가 에이전트는 다음과 같은 AWS 리소스에 대해 수집된 데이터를 검사합니다.
   + Amazon Elastic Compute Cloud(Amazon EC2) 보안 그룹을 생성합니다.
   + Amazon S3 버킷 및 구성
   + IAM 정책, 역할 및 권한
   + Virtual Private Cloud(VPC) 구성 및 네트워크 설정
   + Amazon RDS 데이터베이스 및 보안 설정
   + Lambda 함수 및 구성
   + 기타 감사 범위 AWS 서비스 내

1. 침투 테스터 에이전트는 잠재적 취약성을 식별합니다.

1. 에이전트는 CrewAI 프레임워크를 통해 협업하여 결과를 공유합니다.

보고서 생성은 다음 작업으로 구성됩니다.

1. 보고서 작성자 에이전트는 다른 모든 에이전트의 결과를 컴파일합니다.

1. 보안 문제는 서비스, 심각도 및 규정 준수 영향별로 구성됩니다.

1. 식별된 각 문제에 대해 해결 권장 사항이 생성됩니다.

1. 포괄적인 보안 감사 보고서는 마크다운 형식으로 생성되어 지정된 Amazon S3 버킷에 업로드됩니다. 규정 준수 추적 및 보안 태세 개선을 위해 기록 보고서가 보존됩니다.

로깅 및 모니터링 활동은 다음과 같습니다.
+ CloudWatch 로그는 실행 세부 정보와 오류를 캡처합니다.
+ Lambda 실행 지표는 모니터링을 위해 기록됩니다.

**참고**  
에 대한 코드는 AWS 샘플 컬렉션에서 사용할 수 있는 GitHub [3P-Agentic\$1frameworks](https://github.com/aws-samples/3P-Agentic-Frameworks/blob/main/crewai/aws-security-auditor-crew/README.md) 리포지토리에서 `aws-security-auditor-crew` 가져옵니다.

**가용성 및 규모 조정**

사용 가능한 에이전트를 4개 이상의 코어 에이전트로 확장할 수 있습니다. 추가 특수 에이전트로 규모를 조정하려면 다음과 같은 새 에이전트 유형을 고려하세요.
+ *위협 인텔리전스 전문* 에이전트는 다음을 수행할 수 있습니다.
  + 외부 위협 피드를 모니터링하고 내부 조사 결과와 상호 연관시킵니다.
  + 인프라와 관련된 새로운 위협에 대한 컨텍스트를 제공합니다.
  + 와일드에서 활성 악용을 기반으로 취약성 우선 순위 지정
+ *규정 준수 프레임워크* 에이전트는 다음과 같은 특정 규제 영역에 집중할 수 있습니다.
  + 지불 카드 산업(PCI) 데이터 보안 표준(DSS) 준수
  + HIPAA(미국 건강 보험 양도 및 책임에 관한 법)
  + SOC(시스템 및 조직 제어) 2
  + 일반 데이터 보호 규정(GDPR)

이 솔루션은 사용 가능한 에이전트를 신중하게 확장하여 대규모 AWS 환경에서 확장성을 유지하면서 더 심층적이고 전문화된 보안 인사이트를 제공할 수 있습니다. 구현 접근 방식, 도구 개발 및 조정 고려 사항에 대한 자세한 내용은 [추가 정보를](#deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-additional) 참조하세요.

## 도구
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-tools"></a>

**AWS 서비스**
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)은 선도적인 AI 기업과 Amazon의 고성능 파운데이션 모델(FM)을 통합 API를 통해 사용할 수 있게 해주는 완전 관리형 서비스입니다.
+ [Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)를 사용하면 모든 시스템, 애플리케이션 및의 로그를 중앙 집중화 AWS 서비스 하여 모니터링하고 안전하게 보관할 수 있습니다.
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)는 애플리케이션을 다양한 소스의 실시간 데이터와 연결할 수 있는 서버리스 이벤트 버스 서비스입니다. 예: AWS Lambda 함수, API 대상을 사용하는 HTTP 호출 엔드포인트 또는 다른의 이벤트 버스 AWS 계정. 이 패턴에서는 에이전트 워크플로를 예약하고 오케스트레이션하는 데 사용됩니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [AWS SDK for Python (Boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)는 Python 애플리케이션, 라이브러리 또는 스크립트를와 통합하는 데 도움이 되는 소프트웨어 개발 키트입니다 AWS 서비스.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다. 이 패턴에서는 에이전트 아티팩트 및 상태 관리를 위한 객체 스토리지를 제공합니다.

**기타 도구**
+ [CrewAI](https://www.crewai.com/open-source)는 다중 에이전트 AI 시스템을 구축하기 위한 오픈 소스 Python 기반 프레임워크입니다.
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.

**코드 리포지토리**

이 패턴의 코드는 [deploy-crewai-agents-terraform](https://github.com/aws-samples/deploy-crewai-agents-terraform.git) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-best-practices"></a>
+ Amazon DynamoDB 잠금과 함께 Amazon S3 백엔드를 사용하여 Terraform에 대한 적절한 상태 관리를 구현합니다. 자세한 내용은 Terraform 공급자 사용 [모범 사례의 백엔드](https://docs.aws.amazon.com/prescriptive-guidance/latest/terraform-aws-provider-best-practices/backend.html) 모범 사례를 참조하세요. * AWS * 
+ 워크스페이스를 사용하여 개발, 스테이징 및 프로덕션 환경을 분리합니다.
+ 최소 권한 원칙을 따르고 작업을 수행하는 데 필요한 최소 권한을 부여하세요. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv) 및 [보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)를 참조하세요.
+ CloudWatch Logs를 통해 세부 로깅 및 모니터링을 활성화합니다.
+ 에이전트 작업에 대한 재시도 메커니즘 및 오류 처리를 구현합니다.

## 에픽
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-epics"></a>

### CrewAI 프레임워크 배포
<a name="deploy-crewai-framework"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리포지토리를 복제합니다. | 로컬 시스템에서이 패턴의 리포지토리를 복제하려면 다음 명령을 실행합니다.<pre>git clone "git@github.com:aws-samples/deploy-crewai-agents-terraform.git"<br />cd deploy-crewai-agents-terraform</pre> | DevOps 엔지니어 | 
| 환경 변수를 편집합니다. | 환경 변수를 사용하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 엔지니어 | 
| 인프라를 생성합니다. | 인프라를 생성하려면 다음 명령을 실행합니다.<pre>cd terraform</pre><pre>terraform init</pre><pre>terraform plan</pre>실행 계획을 주의 깊게 검토합니다. 계획된 변경 사항이 허용 가능한 경우 다음 명령을 실행합니다.<pre>terraform apply --auto-approve</pre> | DevOps 엔지니어 | 

### CrewAI 에이전트 액세스
<a name="access-crewai-agents"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 에이전트에 액세스합니다. |  AWS 인프라 보안 감사 및 보고 팀의 에이전트는 Lambda 함수로 배포됩니다. 에이전트에 액세스하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 엔지니어 | 
| (선택 사항) 에이전트의 수동 실행을 구성합니다. | 에이전트는 매일 일정(자정 UTC)에 따라 자동으로 실행되도록 구성됩니다. 그러나 다음 단계를 사용하여 수동으로 트리거할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html)자세한 내용은 [Lambda 설명서의 콘솔에서 Lambda 함수 테스트를](https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html) 참조하세요. | DevOps 엔지니어 | 
| 디버깅을 위해 에이전트 로그에 액세스합니다. | CrewAI 에이전트는 보안 감사를 수행하고 Amazon S3에 보고서를 저장하는 데 필요한 권한이 있는 Lambda 환경에서 실행됩니다. 출력은 AWS 인프라에 대한 포괄적인 보안 분석을 제공하는 마크다운 보고서입니다.에이전트 동작의 세부 디버깅을 지원하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 엔지니어 | 
| 에이전트 실행 결과를 봅니다. | 에이전트 실행 결과를 보려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html)보고서는 다음과 같이 타임스탬프 기반 파일 이름으로 저장됩니다. `security-audit-report-YYYY-MM-DD-HH-MM-SS.md)`  | DevOps 엔지니어 | 
| 에이전트 실행을 모니터링합니다. | CloudWatch 로그를 통해 에이전트의 실행을 모니터링하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 엔지니어 | 
|  에이전트 동작을 사용자 지정합니다. | 에이전트 또는 해당 작업을 수정하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html)<pre>cd terraform </pre><pre>terraform apply</pre> | DevOps 엔지니어 | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 생성된 리소스를 삭제합니다. | 이 패턴으로 생성된 모든 인프라를 삭제하려면 다음 명령을 실행합니다.<pre>terraform plan -destroy </pre>다음 명령은이 패턴으로 생성된 모든 리소스를 영구적으로 삭제합니다. 명령을 실행하면 리소스를 제거하기 전에 확인 메시지가 표시됩니다.폐기 계획을 주의 깊게 검토합니다. 계획된 삭제가 허용 가능한 경우 다음 명령을 실행합니다.<pre>terraform destroy</pre> | DevOps 엔지니어 | 

## 문제 해결
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 에이전트 동작 | 이 문제에 대한 자세한 내용은 Amazon Bedrock 설명서의 [에이전트 동작 테스트 및 문제 해결](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-networking.html)을 참조하세요. | 
| Lambda 네트워크 문제 | 이러한 문제에 대한 자세한 내용은 [Lambda 설명서의 Lambda의 네트워킹 문제 해결을](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-networking.html) 참조하세요. | 
| IAM 권한 | 이러한 문제에 대한 자세한 내용은 [IAM 설명서의 IAM 문제 해결](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot.html)을 참조하세요. | 

## 관련 리소스
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-resources"></a>

**AWS 블로그**
+ [CrewAI 및 Amazon Bedrock을 사용하여 에이전트 시스템 구축](https://aws.amazon.com/blogs/machine-learning/build-agentic-systems-with-crewai-and-amazon-bedrock/)

**AWS 설명서**
+ [Amazon Bedrock 설명서](https://docs.aws.amazon.com/bedrock/)
+ [Amazon Bedrock Agents 작동 방식](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-how.html)
+ [AWS Well-Architected 프레임워크](https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html)

**기타 리소스**
+ [VMware 설명서](https://docs.crewai.com/introduction)
+ [Terraform AWS 공급자 설명서](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)

## 추가 정보
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-additional"></a>

이 섹션에는 [자동화 및 규모 조정의 이전 논의와 관련된 구현 접근 방식, 도구 개발 및 규모](#deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-architecture) 조정 고려 사항에 대한 정보가 포함되어 있습니다.

**구현 접근 방식**

에이전트를 추가하려면 다음 접근 방식을 고려하세요.

1. 에이전트 구성
   + `config/agents.yaml` 파일에 새 에이전트 정의를 추가합니다.
   + 각 에이전트에 대한 특수 백스토리, 목표 및 도구를 정의합니다.
   + 에이전트 전문 분야에 따라 메모리 및 분석 기능을 구성합니다.

1. Saga 오케스트레이션
   + 새 에이전트별 작업을 포함하도록 `config/tasks.yaml` 파일을 업데이트합니다.
   + 작업 간에 종속성을 생성하여 적절한 정보 흐름을 보장합니다.
   + 적절한 경우 병렬 작업 실행을 구현합니다.

**기술 구현**

다음은 제안된 위협 인텔리전스 전문가 에이전트의 `agents.yaml` 파일에 추가된 내용입니다.

```
Example new agent configuration in agents.yaml
threat_intelligence_agent:
 name: "Threat Intelligence Specialist"
 role: "Cybersecurity Threat Intelligence Analyst"
 goal: "Correlate AWS security findings with external threat intelligence"
 backstory: "Expert in threat intelligence with experience in identifying emerging threats and attack patterns relevant to cloud infrastructure." 
verbose: true 
allow_delegation: true 
tools: 
- "ThreatIntelligenceTool" 
- "AWSResourceAnalyzer"
```

**개발 도구**

CrewAI 프레임워크를 사용하면 다음 작업을 수행하여 보안 감사 팀의 효율성을 개선할 수 있습니다.
+ 새 에이전트를 위한 사용자 지정 도구를 생성합니다.
+ 위협 인텔리전스를 위해 외부 API와 통합합니다.
+ 다양한를 위한 특수 분석기를 개발합니다 AWS 서비스.

**조정 고려 사항**

 AWS 인프라 보안 감사 및 보고 시스템을 확장하여 더 큰 환경이나 더 포괄적인 감사를 처리할 때는 다음과 같은 조정 요소를 해결합니다.
+ **컴퓨팅 리소스**
  + Lambda 메모리 할당을 늘려 추가 에이전트를 처리합니다.
  + 에이전트 워크로드를 여러 Lambda 함수로 분할하는 것이 좋습니다.
+ **비용 관리**
  + 에이전트 수가 증가함에 따라 Amazon Bedrock API 사용량을 모니터링합니다.
  + 감사 범위에 따라 선택적 에이전트 활성화를 구현합니다.
+ **협업 효율성**
  + 에이전트 간의 정보 공유를 최적화합니다.
  + 복잡한 환경을 위한 계층적 에이전트 구조를 구현합니다.
+ **지식 기반 개선 사항**
  + 에이전트에게 도메인에 대한 전문 지식 기반을 제공합니다.
  + 새로운 보안 모범 사례로 에이전트 지식을 정기적으로 업데이트합니다.

# AWS CodePipeline CI/CD 파이프라인을 사용하여 AWS Glue 작업 배포
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline"></a>

*Bruno Klein, Luis Henrique Massao Yamada, Amazon Web Services*

## 요약
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-summary"></a>

이 패턴은 AWS CodeCommit과 AWS CodePipeline을 AWS Glue와 통합하고, 개발자가 변경 내용을 원격 AWS CodeCommit 리포지토리로 푸시하는 즉시 AWS Lambda를 사용하여 작업을 시작하는 방법을 보여줍니다. 

개발자가 추출, 전환, 적재(ETL) 리포지토리에 변경 내용을 제출하고 변경 내용을 AWS CodeCommit에 푸시하면 새 파이프라인이 호출됩니다. 파이프라인은 이러한 변경과 함께 Glue 작업을 시작하는 Lambda 함수를 시작합니다. Glue 작업은 ETL 작업을 수행합니다.

이 솔루션은 기업, 개발자, 데이터 엔지니어가 변경 내용을 커밋하고 대상 리포지토리에 푸시하는 즉시 작업을 시작하려는 경우에 유용합니다. 이를 통해 자동화 및 재현성 수준을 높여 작업 시작 및 수명 주기 동안 오류를 방지할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정
+ 로컬 시스템에 설치되는 [Git](https://git-scm.com/)
+ 로컬 시스템에 설치되는 [Amazon Cloud Development Kit(Amazon CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)
+ 로컬 머신에 설치되는 [Python](https://www.python.org/)
+ *첨부 파일* 섹션의 코드

**제한 사항 **
+ 파이프라인은 Glue 작업이 성공적으로 시작되는 즉시 완료됩니다. 작업이 마무리될 때까지 기다리지 않습니다.
+ 첨부 파일에 나와 있는 코드는 데모용으로만 사용됩니다.

## 아키텍처
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-architecture"></a>

**대상 기술 스택  **
+ Glue
+ Lambda
+ AWS CodePipeline
+ AWS CodeCommit

**대상 아키텍처 **

![\[개발자가 CodeCommit 리포지토리에 변경 사항을 푸시하는 즉시 Lambda를 사용하여 Glue 작업을 시작합니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/99a67388-5939-4267-8324-b6ca8bfa7962/images/917c9041-b94d-4e95-a3c4-9a1115ead228.png)


 

프로세스는 다음 단계로 구성됩니다.

1. 개발자 또는 데이터 엔지니어가 ETL 코드를 수정하여 커밋하고 변경 내용을 AWS CodeCommit에 푸시합니다.

1. 푸시는 파이프라인을 시작합니다.

1. 파이프라인은 리포지토리의 `codecommit:GetFile`(을)를 호출하고 파일을 Amazon Simple Storage Service(S3)에 업로드하는 Lambda 함수를 시작합니다.

1. Lambda 함수는 ETL 코드를 사용하여 새로운 Glue 작업을 시작합니다.

1. Lambda 함수는 파이프라인을 완료합니다.

**자동화 및 규모 조정**

샘플 첨부 파일은 AWS Glue를 AWS CodePipeline과 통합하는 방법을 보여줍니다. 용도에 맞게 사용자 지정하거나 확장할 수 있는 기본 예제를 제공합니다. 자세한 내용은*에픽* 섹션을 참조하세요.

## 도구
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-tools"></a>
+ [AWS CodePipeline](https://aws.amazon.com/codepipeline/) – AWS CodePipeline은 빠르고 안정적인 애플리케이션 및 인프라 업데이트를 위해 릴리스 파이프라인을 자동화하는 데 사용할 수 있는 완전관리형 [지속적 제공](https://aws.amazon.com/devops/continuous-delivery/) 서비스입니다.
+ [AWS CodeCommit](https://aws.amazon.com/codecommit/) — AWS CodeCommit은 안전한 Git 기반 리포지토리를 호스팅하는 완전 관리형 [소스 제어](https://aws.amazon.com/devops/source-control/) 서비스입니다.
+ [Lambda](https://aws.amazon.com/lambda/) – Lambda는 서버를 프로비저닝하거나 관리하지 않고도 코드를 실행할 수 있게 해주는 서버리스 컴퓨팅 서비스입니다.
+ [Glue](https://aws.amazon.com/glue) – Glue는 분석, 기계 학습, 애플리케이션 개발을 위해 데이터를 쉽게 검색, 준비, 결합할 수 있게 해주는 서버리스 데이터 통합 서비스입니다.
+ [Git 클라이언트](https://git-scm.com/downloads) — Git는 GUI 도구를 제공하거나, 또는 사용자가 명령줄 또는 데스크톱 도구를 사용하여 GitHub에서 필요한 아티팩트를 체크아웃할 수 있습니다. 
+ [CDK](https://aws.amazon.com/cdk/) - CDK는 오픈 소스 소프트웨어 개발 프레임워크로, 익숙한 프로그래밍 언어를 사용하여 클라우드 애플리케이션 리소스를 정의하도록 지원합니다.

## 에픽
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-epics"></a>

### 샘플 코드의 배포
<a name="deploy-the-sample-code"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CLI를 구성합니다. | 현재의 계정을 대상으로 지정하고 인증하도록 Command Line Interface(CLI)를 구성합니다. 자세한 지침은 [CLI 설명서](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)를 참조하십시오. | 개발자, DevOps 엔지니어 | 
| 샘플 프로젝트 파일을 추출합니다. | 첨부 파일에서 파일을 추출하여, 샘플 프로젝트 파일이 포함된 폴더를 생성합니다. | 개발자, DevOps 엔지니어 | 
| 샘플 코드를 배포합니다. | 파일을 추출한 후 추출 위치에서 다음 명령을 실행하여 기본 예제를 생성합니다.<pre>cdk bootstrap<br />cdk deploy<br />git init<br />git remote add origin <code-commit-repository-url><br />git stage .<br />git commit -m "adds sample code"<br />git push --set-upstream origin main</pre>마지막 명령 후 파이프라인의 상태와 Glue 작업을 모니터링할 수 있습니다. | 개발자, DevOps 엔지니어 | 
| 코드를 사용자 지정합니다. | 비즈니스 요구 사항에 따라 etl.py 파일의 코드를 사용자 지정합니다. ETL 코드를 수정하거나, 파이프라인 단계를 수정하거나, 솔루션을 확장할 수 있습니다. | 데이터 엔지니어 | 

## 관련 리소스
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-resources"></a>
+ [SDK 시작하기](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)
+ [AWS Glue에 작업 추가](https://docs.aws.amazon.com/glue/latest/dg/add-job.html)
+ [CodePipeline에서 소스 작업 통합](https://docs.aws.amazon.com/codepipeline/latest/userguide/integrations-action-type.html#integrations-source)
+ [CodePipeline의 파이프라인에서 Lambda 함수의 호출](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-invoke-lambda-function.html)
+ [Glue 프로그래밍](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming.html)
+ [AWS CodeCommit GetFile API](https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetFile.html)

## 첨부
<a name="attachments-99a67388-5939-4267-8324-b6ca8bfa7962"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/99a67388-5939-4267-8324-b6ca8bfa7962/attachments/attachment.zip) 파일의 압축을 풉니다.

# AWS CodePipeline, AWS CodeCommit, AWS CodeBuild를 사용하여 여러 AWS 리전에 코드 배포
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild"></a>

*Anand Krishna Varanasi, Amazon Web Services*

## 요약
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-summary"></a>

이 패턴은 AWS CloudFormation을 사용하여 여러 Amazon Web Services(AWS) 리전에 인프라 또는 아키텍처를 구축하는 방법을 보여줍니다. 배포 속도를 높이기 위해 여러 AWS 리전에 걸친 지속적 통합(CI) / 지속적 배포(CD)가 포함됩니다. ** ** 이 패턴의 단계는 예를 들어 세 개의 AWS 리전에 배포하기 위한 AWS CodePipeline 작업을 생성하기 위해 테스트되었습니다. 사용 사례를 바탕으로 리전의 수를 변경할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-prereqs"></a>

**사전 조건 **
+ 활성 상태의 계정
+ 
  + *AmazonS3FullAccess* 및 *CloudWatchFullAccess* 정책이 적용되는 코드빌드 역할. 이러한 정책을 통해 CodeBuild는 Amazon CloudWatch를 통해 AWS CodeCommit 이벤트를 관찰하고 Amazon Simple Storage Service(S3)를 아티팩트 스토어로 사용할 수 있는 액세스 권한을 제공합니다.
  + 다음 정책이 적용된 AWS CloudFormation 역할로서, 최종 빌드 단계에서 AWS CloudFormation에 AWS Lambda 함수를 생성 또는 업데이트하고, Amazon CloudWatch 로그를 푸시하거나 감시하고, 변경 세트를 생성 및 업데이트할 수 있는 기능을 제공합니다. 
    + *AWSLambdaFullAccess*
    + *AWSCodeDeployFullAccess*
    + *CloudWatchFullAccess*
    + *AWSCloudFormationFullAccess*
    + *AWSCodePipelineFullAccess*
**참고**  
CodeBuild에 대한 적절한 정책이 적용되어 테스트, 번들링, 아티팩트 패키징 및 여러 AWS 리전에 병렬로 배포하는 CI 작업을 수행하기 위한 AWS CodeBuild 및 AWS CloudFormation용 AWS Identity and Access Management(IAM) 역할 2개.   CodePipeline에서 생성한 정책을 비교 검토하여 CodeBuild와 AWS CloudFormation이 CI 및 CD 단계에서 적절한 권한을 가지고 있는지 확인하십시오.

## 아키텍처
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-architecture"></a>

![\[3개의 AWS 리전에 배포하는 AWS CodePipeline 작업.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/d44c393c-7243-4d4e-8b84-88a8503af98f/images/5c27fc35-5e62-4292-8b18-a7bc7faf2631.png)


이 패턴의 다중 리전 아키텍처 및 워크플로는 다음 단계로 구성됩니다.

1. CodeCommit 리포지토리로 코드를 전송합니다.

1. 코드 업데이트 또는 커밋을 수신하면 CodeCommit은 CloudWatch 이벤트를 간접 호출하고, 이 이벤트는 다시 CodePipeline 작업을 시작합니다.

1. CodePipeline은 CodeBuild에서 처리하는 CI를 사용합니다. 다음과 같은 작업이 수행됩니다.
   + AWS CloudFormation 템플릿 테스트(선택 사항)
   + 배포에 포함된 각 리전에 대한 AWS CloudFormation 템플릿 패키징. 예를 들어 이 패턴은 세 개의 AWS 리전에 병렬로 배포되므로 CodeBuild는 AWS CloudFormation 템플릿을 지정된 각 리전에 하나씩, 세 개의 S3 버킷으로 패키징합니다. S3 버킷은 CodeBuild에서 아티팩트 리포지토리로만 사용됩니다.

1. CodeBuild는 세 개의 AWS 리전에서 병렬로 실행되는 다음 배포 단계를 위한 입력으로 아티팩트를 패키징합니다. 리전 수를 다르게 지정하는 경우 CodePipeline은 해당 리전에 배포합니다.

## 도구
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-tools"></a>

**도구**
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) - CodePipeline은 소프트웨어 변경 사항을 지속적으로 릴리스하는데 필요한 단계를 모델링, 시각화, 자동화하는 데 사용할 수 있는 지속적 전달 서비스입니다.
+ [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은 클라우드에서 자산(예: 문서, 소스 코드, 바이너리 파일)을 비공개로 저장하여 관리하는 데 사용할 수 있도록 Amazon Web Services에서 호스트되는 버전 관리 서비스입니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) - AWS CloudFormation은 Amazon Web Services 리소스를 모델링하고 설정하여 리소스 관리 시간을 줄이고 AWS에서 실행되는 애플리케이션에 더 많은 시간을 사용하도록 해 주는 서비스입니다.
+ [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) - AWS Identity and Access Management(IAM)는 AWS 리소스에 대한 사용자의 액세스를 안전하게 제어하는 데 도움이 되는 웹 서비스입니다.
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/Welcome.html) – Amazon Simple Storage Service(S3)는 인터넷에 대한 스토리지입니다. 이 서비스는 개발자가 더 쉽게 웹 규모 컴퓨팅 작업을 수행할 수 있도록 설계되었습니다.

**코드**

다음 샘플 코드는 `BuildSpec.yaml` 파일용 샘플 코드입니다(빌드 단계).

```
---
artifacts:
discard-paths: true
files:
- packaged-first-region.yaml
- packaged-second-region.yaml
- packaged-third-region.yaml
phases:
build:
commands:
- echo "********BUILD PHASE - CF PACKAGING**********"
- "aws cloudformation package --template-file sam-template.yaml --s3-bucket $S3_FIRST_REGION --output-template-file packaged-first-region.yaml --region $FIRST_REGION"
- "aws cloudformation package --template-file sam-template.yaml --s3-bucket $S3_SECOND_REGION --output-template-file packaged-second-region.yaml --region $SECOND_REGION"
- "aws cloudformation package --template-file sam-template-anand.yaml --s3-bucket $S3_THIRD_REGION --output-template-file packaged-third-region.yaml --region $THIRD_REGION"
install:
commands:
- echo "********BUILD PHASE - PYTHON SETUP**********"
runtime-versions:
python: 3.8
post_build:
commands:
- echo "********BUILD PHASE - PACKAGING COMPLETION**********"
pre_build:
commands:
- echo "********BUILD PHASE - DEPENDENCY SETUP**********"
- "npm install --silent --no-progress"
- echo "********BUILD PHASE - DEPENDENCY SETUP DONE**********"
version: 0.2
```

## 에픽
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-epics"></a>

### 코드 및 CodeCommit 리포지토리 준비
<a name="prepare-the-code-and-the-codecommit-repository"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포할 기본 AWS 리전을 선택합니다. | AWS 계정에 로그인하고 배포할 기본 리전을 선택합니다. CodeCommit 리포지토리는 기본 리전에 위치합니다. | DevOps | 
| CodeCommit 리포지토리를 생성합니다. | CodeCommit 리포지토리를 만들고 필요한 코드를 해당 리포지토리에 푸시합니다. 코드에는 일반적으로 AWS CloudFormation 또는 AWS SAM 템플릿, Lambda 코드(있는 경우) 및 `buildspec.yaml` CodeBuild 파일을 AWS CodePipeline에 대한 입력으로 포함합니다. | DevOps | 
| CodeCommit 리포지토리로 코드를 푸시합니다. | *첨부* 섹션에서 이 예제의 코드를 다운로드한 다음 필요한 코드를 여기에 푸시합니다. 일반적으로 코드에는 AWS CloudFormation 또는 AWS SAM 템플릿, Lambda 코드 및 `buildspec.yaml` CodeBuild 파일을 파이프라인에 대한 입력으로 포함합니다. | DevOps | 

### 소스 단계: 파이프라인 생성
<a name="source-phase-create-the-pipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CodePipeline 작업을 생성합니다. | CodePipeline 콘솔에서 **파이프라인 생성**을 선택합니다. | DevOps | 
| CodePipeline 작업의 이름을 지정하고 서비스 역할 설정을 선택합니다. | 작업 이름을 입력하고 CodePipeline이 필요한 정책이 첨부된 역할을 생성하도록 기본 서비스 역할 설정을 유지합니다. | DevOps | 
| 아티팩트 스토어의 위치를 지정합니다. | **고급 설정**에서 CodePipeline이 코드 아티팩트 스토리지에 사용할 S3 버킷을 생성하도록 기본 옵션을 유지합니다. 기존 S3 버킷을 대신 사용하는 경우 버킷은 첫 번째 에픽에서 지정한 기본 리전에 있어야 합니다. | DevOps | 
| 암호화 키를 지정합니다. | 기본 옵션인 **기본 AWS 관리형 키**를 사용하거나, 자체 AWS Key Management Service(AWS KMS) 고객 관리형 키를 사용하도록 선택합니다. | DevOps | 
| 소스 공급자를 지정합니다. | **소스 공급자**에서 **AWS CodeCommit**을 선택합니다. | DevOps | 
| 리포지토리를 지정합니다. | 첫 번째 에픽에서 만든 CodeCommit 리포지토리를 선택합니다. 브랜치에 코드를 삽입했다면 브랜치를 선택하십시오. | DevOps | 
| 코드 변경을 감지하는 방법을 지정하십시오. | CodeCommit이 CodePipeline 작업을 시작하기 위한 변경 트리거로 기본값인 **Amazon CloudWatch Events**를 유지합니다. | DevOps | 

### 빌드 단계: 파이프라인 구성
<a name="build-phase-configure-the-pipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 빌드 제공자를 지정하십시오. | 빌드 공급자에서** AWS CodeBuild**를 선택합니다. | DevOps | 
| AWS 리전을 지정합니다. | 첫 번째 에픽에서 지정한 기본 리전을 선택합니다. | DevOps | 

### 빌드 단계: 프로젝트 생성 및 구성
<a name="build-phase-create-and-configure-the-project"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 프로젝트 생성 | **프로젝트 생성**을 선택한 다음, 프로젝트의 이름을 입력합니다. | DevOps | 
| 환경 이미지를 지정하십시오. | 이 패턴 데모에서는 기본 CodeBuild 관리 이미지를 사용하십시오. 사용자 지정 도커 이미지가 있는 경우 이를 사용할 수도 있습니다. | DevOps | 
| 운영 체제를 지정하십시오. | Amazon Linux 2 또는 Ubuntu를 선택합니다.Amazon Linux 2는 곧 지원이 종료됩니다. 자세한 내용은 [Amazon Linux 2 FAQ](https://aws.amazon.com/amazon-linux-2/faqs/)를 참조하세요. | DevOps | 
| 서비스 역할을 지정합니다. | CodePipeline 작업 생성을 시작하기 전에 CodeBuild용으로 생성한 역할을 선택합니다. (*사전 조건* 섹션 참조) | DevOps | 
| 추가 옵션을 설정하십시오. | **제한 시간** 및 **대기 중인 제한시간**의 경우 기본값을 유지하십시오. 인증서의 경우 사용하려는 사용자 지정 인증서가 없는 한 기본 설정을 유지하십시오. | DevOps | 
| 환경 변수를 생성합니다. | 배포하려는 각 AWS 리전에 대해 S3 버킷 이름과 리전 이름(예를 들어, 미국 동부-1)을 제공하여 환경 변수를 생성합니다. | DevOps | 
| buildspec.yml이 아닌 경우 buildspec 파일 이름을 입력하십시오. | 파일 이름이 기본값인 경우 이 필드를 비워 두세요, `buildspec.yaml`. buildspec 파일의 이름을 변경한 경우 여기에 이름을 입력하십시오. CodeCommit 리포지토리에 있는 파일 이름과 일치하는지 확인합니다. | DevOps | 
| 로깅을 지정합니다. | Amazon CloudWatch Events의 로그를 보려면 기본 설정을 유지합니다. 또는 특정 그룹 또는 로거 이름을 정의할 수 있습니다. | DevOps | 

### 배포 단계를 건너뛰십시오.
<a name="skip-the-deploy-phase"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포 단계를 건너뛰고 파이프라인 생성을 완료하십시오. | 파이프라인을 설정하면 CodePipeline을 사용하여 배포 단계에서 단 하나의 단계만 생성할 수 있습니다. 여러 AWS 리전에 배포하려면 이 단계를 건너뛰십시오. 파이프라인이 생성된 후 여러 배포 단계를 추가할 수 있습니다. | DevOps | 

### 배포 단계: 첫 번째 리전에 배포할 파이프라인을 구성합니다.
<a name="deploy-phase-configure-the-pipeline-for-deployment-to-the-first-region"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포 단계에 스테이지를 추가합니다. | 파이프라인을 편집하고 배포 단계에서 **스테이지 추가**를 선택합니다. 이 첫 번째 스테이지는 기본 리전을 위한 것입니다. | DevOps | 
| 스테이지의 액션 이름을 입력합니다. | 첫 번째 (기본) 스테이지와 리전을 반영하는 고유한 이름을 입력합니다. 예를 들어, **primary\$1<region>\$1deploy**를 입력합니다. | DevOps | 
| 작업 제공자를 지정하십시오. | **작업 공급자**에서 AWS CloudFormation을 선택합니다. | DevOps | 
| 첫 번째 스테이지를 위한 리전을 구성합니다. | CodePipeline과 CodeBuild가 설정된 동일한 리전인 첫 번째 (기본) 리전을 선택합니다. 스택을 배포할 기본 리전입니다. | DevOps | 
| 입력 아티팩트를 지정합니다. | **BuildArtifact**를 선택합니다. 빌드 단계의 출력입니다. | DevOps | 
| 취할 작업을 지정합니다. | **작업 모드**에서 **스택 생성 또는 업데이트**를 선택합니다. | DevOps | 
| CloudFormation 스택의 이름을 입력합니다. |  | DevOps | 
| 첫 번째 리전의 템플릿을 지정합니다. | CodeBuild에서 패키징하여 첫 번째 (기본) 리전의 S3 버킷에 덤프한 리전 특정 패키지 이름을 선택합니다. | DevOps | 
| 기능을 지정합니다. | 스택 템플릿에 IAM 리소스가 포함되어 있거나 매크로가 포함된 템플릿에서 직접 스택을 생성하는 경우 기능이 필요합니다. 이 패턴에는 CAPABILITY\$1IAM, CAPABILITY\$1NAMED\$1IAM, CAPABILITY\$1AUTO\$1EXPAND를 사용합니다. | DevOps | 

### 배포 단계: 두 번째 리전에 배포할 파이프라인을 구성합니다.
<a name="deploy-phase-configure-the-pipeline-for-deployment-to-the-second-region"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포 단계에 두 번째 스테이지를 추가합니다. | 두 번째 리전에 스테이지를 추가하려면 파이프라인을 편집하고 배포 단계에서 **스테이지 추가**를 선택합니다. 중요: 두 번째 리전을 만드는 과정은 다음 값을 제외하고 첫 번째 리전을 만드는 프로세스와 동일합니다. | DevOps | 
| 두 번째 스테이지의 액션 이름을 입력합니다. | 두 번째 스테이지와 두 번째 리전을 반영하는 고유한 이름을 입력합니다. | DevOps | 
| 두 번째 스테이지를 위한 리전을 구성합니다. | 스택을 배포하려는 두 번째 리전을 선택합니다. | DevOps | 
| 두 번째 리전의 템플릿을 지정합니다. | CodeBuild에서 패키징하여 두 번째 리전의 S3 버킷에 덤프한 리전 특정 패키지 이름을 선택합니다. | DevOps | 

### 배포 단계: 세 번째 리전에 배포할 파이프라인을 구성합니다.
<a name="deploy-phase-configure-the-pipeline-for-deployment-to-the-third-region"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포 단계에 세 번째 스테이지를 추가합니다. | 세 번째 리전에 스테이지를 추가하려면 파이프라인을 편집하고 배포 단계에서 **스테이지 추가**를 선택합니다. 중요: 세 번째 리전을 만드는 과정은 다음 값을 제외하고 이전 두 개 리전을 만드는 프로세스와 동일합니다. | DevOps | 
| 세 번째 스테이지의 액션 이름을 입력합니다. | 세 번째 스테이지와 세 번째 리전을 반영하는 고유한 이름을 입력합니다. | DevOps | 
| 세 번째 스테이지를 위한 리전을 구성합니다. | 스택을 배포하려는 세 번째 리전을 선택합니다. | DevOps | 
| 세 번째 리전의 템플릿을 지정합니다. | CodeBuild에서 패키징하여 세 번째 리전의 S3 버킷에 덤프한 리전 특정 패키지 이름을 선택합니다. | DevOps | 

### 배포 정리
<a name="clean-up-the-deployment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS 리소스를 삭제합니다. | 배포를 정리하려면 각 리전의 CloudFormation 스택을 삭제하십시오. 그런 다음 기본 리전에서 CodeCommit, CodeBuild, CodePipeline 리소스를 삭제합니다. | DevOps | 

## 관련 리소스
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-resources"></a>
+ [AWS CodePipeline이란 무엇입니까?](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)
+ [AWS Serverless Application Model](https://aws.amazon.com/serverless/sam/)
+ [AWS CloudFormation](https://aws.amazon.com/cloudformation/)
+ [AWS CodePipeline에 대한 AWS CloudFormation 아키텍처 구조 참조](https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-CloudFormation.html)

## 첨부
<a name="attachments-d44c393c-7243-4d4e-8b84-88a8503af98f"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/d44c393c-7243-4d4e-8b84-88a8503af98f/attachments/attachment.zip) 파일의 압축을 풉니다.

# Azure DevOps 파이프라인에서 프라이빗 Amazon EKS 클러스터로 워크로드 배포
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters"></a>

*Mahendra Revanasiddappa, Amazon Web Services*

## 요약
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-summary"></a>

이 패턴은 Azure DevOps 파이프라인에서 프라이빗 Amazon Elastic Kubernetes Service(Amazon EKS) 클러스터로 지속적 통합 및 지속적 전달(CI/CD)을 구현하는 방법을 보여줍니다. Amazon EKS 클러스터의 프라이빗 API 서버 엔드포인트로 전환하여 보안 태세를 강화하고 있는 조직이 직면한 중요한 문제를 해결합니다.

퍼블릭 엔드포인트는 Kubernetes API 서버를 인터넷에 직접 노출하여 악의적인 공격자가 잠재적으로 대상으로 삼을 수 있는 더 큰 공격 표면을 생성합니다. 프라이빗 엔드포인트로 전환하면 클러스터의 컨트롤 플레인에 대한 액세스가 고객의 Virtual Private Cloud(VPC) 내에서 로 제한됩니다.

Amazon EKS 클러스터를 프라이빗 API 엔드포인트로 전환하면 보안이 크게 향상되지만 Azure DevOps와 같은 외부 CI/CD 플랫폼에 연결 문제가 발생합니다. 프라이빗 엔드포인트는 클러스터의 VPC 또는 피어링된 네트워크 내에서만 액세스할 수 있습니다. 따라서 AWS 프라이빗 네트워크 외부에서 작동하는 표준 Microsoft 호스팅 Azure DevOps 에이전트는 Kubernetes API 서버에 직접 연결할 수 없습니다. 이렇게 하면 클러스터에 대한 연결을 설정하지 못하기 때문에 이러한 에이전트에서 실행되는 kubectl 또는 Helm과 같은 도구에 의존하는 일반적인 배포 워크플로가 중단됩니다.

이 문제를 해결하기 위해이 패턴은 프라이빗 Amazon EKS 클러스터 내에서 자체 호스팅된 Azure DevOps 에이전트를 사용하여 효율적인 접근 방식을 보여줍니다. 이 솔루션은 보안 요구 사항을 유지하면서 우수한 비용 최적화, 운영 효율성 및 확장성을 제공합니다. 이 접근 방식은 성능이나 보안을 손상시키지 않고 멀티 클라우드 DevOps 프로세스를 간소화하려는 기업에 특히 유용합니다.

## 사전 조건 및 제한 사항
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ AWS Command Line Interface (AWS CLI) 버전 2.13.17 이상, [설치됨.](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ kubectl 버전 1.25.1 이상 [설치](https://kubernetes.io/docs/tasks/tools/)
+ 네임스페이스, 보안 암호 및 배포를 생성할 수 있는 권한이 있는 프라이빗 Amazon EKS 클러스터 버전 1.24 이상이 [생성](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html)되었습니다[.](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html)
+ Amazon EKS 클러스터의 작업자 노드를 인터넷에 아웃바운드로 연결하여 해당 노드에서 실행되는 Azure DevOps 에이전트가 Azure DevOps 에이전트 풀에 연결할 수 있도록 합니다.
+ GitHub 계정이 [생성되었습니다](https://github.com/signup).
+ Azure Pipelines과 외부 또는 원격 서비스 간의 인증된 연결인 서비스 연결을 구성할 수 있는 액세스 권한이 있는 Azure DevOps 프로젝트가 [생성됩니다](https://learn.microsoft.com/en-us/azure/devops/user-guide/sign-up-invite-teammates?view=azure-devops&tabs=microsoft-account).
+ 이전 포인트에서 설명한 Azure DevOps 프로젝트를 위해 설치된 AWS Toolkit for Azure DevOps 버전 1.15 이상입니다. 설치 지침은 Visual Studio Marketplace[AWS Toolkit for Azure DevOps](https://marketplace.visualstudio.com/items?itemName=AmazonWebServices.aws-vsts-tools)의 섹션을 참조하세요.

**제한 사항 **
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-architecture"></a>

이 패턴은 다음을 생성합니다.
+ **Amazon ECR 리포지토리** - Amazon Elastic Container Registry(Amazon ECR) 리포지토리는 Azure DevOps 에이전트 및 배포된 샘플 앱과 함께 Docker 이미지를 저장합니다.
+ **Azure DevOps 에이전트 풀** - Azure DevOps 자체 호스팅 에이전트 풀은 프라이빗 Amazon EKS 클러스터에서 실행되는 에이전트를 등록합니다.
+ **IAM 역할** - 프라이빗 Amazon EKS 클러스터에서 실행 중인 에이전트에 필요한 액세스를 제공하는 Azure 서비스 연결을 위한 AWS Identity and Access Management (IAM) 역할입니다.
+ **Azure DevOps 서비스 연결** - 파이프라인 작업이에 액세스하는 데 필요한 액세스를 제공하는 IAM 역할을 사용하기 위한 Azure DevOps 계정의 서비스 연결입니다 AWS 서비스.

다음 다이어그램은 프라이빗 Amazon EKS 클러스터에 자체 호스팅된 Azure DevOps 에이전트를 배포하고 동일한 클러스터에 샘플 애플리케이션을 배포하는 아키텍처를 보여줍니다.

![\[프라이빗 Amazon EKS 클러스터에 자체 호스팅된 Azure DevOps 에이전트 및 샘플 애플리케이션 배포.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/a965834f-a1e2-4679-bd8c-15eed4f57b55/images/ee22bd3e-311c-46e0-8024-9b7e7752080a.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 자체 호스팅 Azure DevOps 에이전트를 Amazon EKS 클러스터 내에 배포로 배포합니다.

1. Azure DevOps 에이전트는 인증을 위해 개인 액세스 토큰(PAT)을 사용하여 Azure DevOps 계정의 에이전트 풀에 연결합니다.

1. Azure Pipelines은 GitHub 리포지토리의 코드를 사용하여 배포하도록 파이프라인을 구성합니다.

1. 파이프라인은 파이프라인 구성에 구성된 에이전트 풀의 에이전트에서 실행됩니다. Azure DevOps 에이전트는 Azure DevOps 계정으로 지속적으로 폴링하여 파이프라인의 작업 정보를 가져옵니다.

1. Azure DevOps 에이전트는 파이프라인 작업의 일부로 Docker 이미지를 빌드하고 이미지를 Amazon ECR 리포지토리로 푸시합니다.

1. Azure DevOps 에이전트는 라는 네임스페이스의 프라이빗 Amazon EKS 클러스터에 샘플 애플리케이션을 배포합니다`webapp`.

## 도구
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-tools"></a>

**도구**
+ [Amazon Elastic Container Registry(Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)는 안전하고 확장 가능하고 신뢰할 수 있는 관리형 컨테이너 이미지 레지스트리 서비스입니다.
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)를 사용하면 자체 Kubernetes 컨트롤 플레인 또는 노드를 설치하거나 유지 관리할 필요 AWS 없이에서 Kubernetes를 실행할 수 있습니다.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 액세스를 인증하고 사용할 수 있는 권한을 부여받은 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다.

**기타 도구**
+ [Docker](https://www.docker.com/)는 운영 체제 수준의 가상화를 사용하여 컨테이너에 소프트웨어를 제공하는 서비스형 플랫폼(PaaS) 제품 세트입니다.
+ [kubectl](https://kubernetes.io/docs/tasks/tools/)는 Kubernetes 클러스터에 대해 명령의 실행을 돕는 명령줄 인터페이스입니다.

**코드 리포지토리**
+ 이 패턴의 코드는 GitHub [deploy-kubernetes-resources-to-amazon-eks-using-azure-devops](https://github.com/aws-samples/deploy-kubernetes-resources-to-amazon-eks-using-azure-devops) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-best-practices"></a>
+ Amazon EKS의 경우 [Amazon EKS 모범 사례 가이드를](https://docs.aws.amazon.com/eks/latest/best-practices/introduction.html) 참조하세요.
+ 최소 권한 원칙을 따르고 작업을 수행하는 데 필요한 최소 권한을 부여하세요. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv) 및 [보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)를 참조하세요.

## 에픽
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-epics"></a>

### 간단한 연결 만들기
<a name="create-a-service-connection"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Azure DevOps 조직 GUID를 찾습니다. | Azure DevOps 계정에 로그인한 다음 다음 URL을 사용하여 조직 GUID를 찾습니다. URL`https://dev.azure.com/{DevOps_Org_ID}/_apis/projectCollections?api-version=6.0`에서를 Azure DevOps 조직 ID`{DevOps_org_ID}`로 바꿉니다. | DevOps | 
| 에서 IdP를 구성합니다 AWS 계정. | Azure 서비스 연결을 AWS 계정 위해에서 ID 제공업체(IdP)를 구성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)자세한 내용은 [ OpenID Connect를 사용하여 Azure DevOps AWS 에서 로 페더레이션하는 방법을](https://aws.amazon.com/blogs/modernizing-with-aws/how-to-federate-into-aws-from-azure-devops-using-openid-connect/) 참조하세요. | DevOps | 
|  AWS 계정을 사용하여 IAM 정책을 생성합니다. | Azure DevOps 파이프라인에서 사용하는 IAM 역할에 필요한 권한을 제공하는 IAM 정책을 생성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | DevOps | 
| 에서 IAM 역할 생성하기 | Azure 서비스 연결을 AWS 계정 위해에서 IAM 역할을 구성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Effect": "Allow",<br />      "Principal": {<br />        "Federated": "arn:aws:iam::{account_id}:oidc-provider/vstoken.dev.azure.com/{OrganizationGUID}"<br />      },<br />      "Action": "sts:AssumeRoleWithWebIdentity",<br />      "Condition": {<br />        "StringEquals": {<br />          "vstoken.dev.azure.com/{OrganizationGUID}:aud": "api://AzureADTokenExchange",<br />          "vstoken.dev.azure.com/{OrganizationGUID}:sub": "sc://{OrganizationName}/{ProjectName}/{ServiceConnectionName}"<br />        }<br />      }<br />    }<br />  ]<br />}</pre>정책에서 다음 자리 표시자에 대한 정보를 제공합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | DevOps | 
| Azure DevOps 계정에서 서비스 연결을 생성합니다. | Azure 서비스 연결을 구성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)자세한 내용은 Microsoft 설명서의 [서비스 연결 생성을](https://learn.microsoft.com/en-us/azure/devops/pipelines/library/service-endpoints?view=azure-devops#create-a-service-connection) 참조하세요. | DevOps | 
| Amazon EKS 구성 파일에 IAM 역할을 추가합니다. | IAM 역할에는 Amazon EKS 클러스터에서 필요한 작업을 수행하는 데 필요한 권한이 있어야 합니다. 파이프라인 역할이므로 IAM 역할은 클러스터에서 거의 모든 유형의 리소스를 관리할 수 있어야 합니다. 따라서 `system:masters` 그룹 권한은이 역할에 적합합니다.Kubernetes `aws-auth ConfigMap` 내의에 필요한 구성을 추가하려면 다음 코드를 사용합니다.<pre>- groups:<br />  - system:masters<br />  rolearn: arn:aws:iam::{account_id}:role/ADO-role<br />  username: ADO-role</pre>를 AWS 계정 ID`{account_id}`로 바꿉니다.자세한 내용은 [Amazon EKS 설명서의 Amazon EKS에서 IAM을 사용하는 방법을](https://docs.aws.amazon.com/eks/latest/userguide/security-iam-service-with-iam.html#security-iam-service-with-iam-roles) 참조하세요. | DevOps | 

### 에이전트 풀 생성
<a name="create-an-agent-pool"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 자체 호스팅 에이전트 풀을 생성합니다. | Azure DevOps 계정에서 자체 호스팅된 에이전트 풀을 구성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)자세한 내용은 Microsoft 설명서의 [에이전트 풀 생성 및 관리를 참조하세요](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/pools-queues?view=azure-devops&tabs=yaml%2Cbrowser). |  | 

### Azure DevOps 에이전트 이미지 빌드 및 Amazon ECR로 푸시
<a name="build-azure-devops-agent-image-and-push-to-ecr"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon ECR 리포지토리를 생성합니다. | 프라이빗 Amazon EKS 클러스터에 Azure DevOps 에이전트 및 샘플 애플리케이션(`webapp`)을 배포하는 데 사용되는 Docker 이미지는 Amazon ECR 리포지토리에 저장되어야 합니다. 다음 단계에 따라 프라이빗 리포지토리를 생성합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)자세한 내용은 Amazon ECR 설명서의 [이미지를 저장할 Amazon ECR 프라이빗 리포지토리 생성](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)을 참조하세요. | DevOps | 
| Dockerfile을 생성하여 Azure DevOps 에이전트를 빌드합니다. | Dockerfile을 생성하여 Azure DevOps 에이전트가 설치된 Docker 이미지를 빌드합니다. 다음 콘텐츠를 `Dockerfile`라는 파일에 복사합니다.<pre><br />FROM ubuntu:22.04 <br />ENV TARGETARCH="linux-x64"<br />RUN apt update && apt upgrade -y && apt install -y curl git jq libicu70 unzip wget<br /><br />RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"<br />RUN unzip awscliv2.zip<br />RUN ./aws/install<br />RUN rm -rf aws awscliv2.zip<br /><br />RUN curl -sSL https://get.docker.com/ | sh<br /><br />RUN curl -sL https://aka.ms/InstallAzureCLIDeb | bash<br />RUN mkdir -p azp <br />WORKDIR /azp/<br /><br />COPY ./start.sh ./ <br />RUN chmod +x ./start.sh<br /><br />RUN useradd -m -d /home/agent agent <br />RUN chown -R agent:agent /azp /home/agent<br />RUN groupadd -f docker <br />RUN usermod -aG docker agent<br />USER agent<br /><br />ENTRYPOINT [ "./start.sh" ]</pre> | DevOps | 
| Azure DevOps 에이전트용 스크립트를 생성합니다. | 다음 SQL 스크립트를 사용하여 테이블을 생성합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | DevOps | 
| Azure DevOps 에이전트를 사용하여 Docker 이미지를 빌드합니다. | Azure DevOps 에이전트를 설치할 Docker 이미지를 생성하려면 이전에 생성한 Dockerfile을 사용하여 이미지를 빌드합니다. 파일을 저장한 디렉터리에서 다음 명령을 실행합니다.<pre>aws ecr get-login-password --region region | docker login --username AWS --password-stdin aws_account_id.dkr.ecr.region.amazonaws.com<br /><br />docker build --platform linux/amd64 -t ado-agent:latest .<br /><br />docker tag ado-agent:latest aws_account_id.dkr.ecr.region.amazonaws.com/webapp:latest<br /><br />docker push aws_account_id.dkr.ecr.region.amazonaws.com/webapp:latest</pre>`aws_account_id` 및를 AWS 계정 ID 및 `region` 로 바꿉니다 AWS 리전. | DevOps | 

### 프라이빗 Amazon EKS 클러스터에 Azure DevOps 에이전트 배포
<a name="deploy-the-azure-devops-agent-to-a-private-eks-cluster"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 개인 액세스 토큰 생성: | 프라이빗 Amazon EKS 클러스터에서 실행되는 에이전트는 Azure DevOps 계정으로 인증할 수 있도록 개인 액세스 토큰(PAT)이 필요합니다. PAT를 생성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)<pre>apiVersion: v1<br />kind: Secret<br />metadata:<br />  name: azdevops-pat<br />  namespace: default<br />type: Opaque<br />stringData:<br />  AZP_TOKEN: <PAT Token></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)<pre>kubectl create -f ado-secret.yaml</pre>자세한 내용은 Microsoft 설명서의 [개인 액세스 토큰(PAT)을 사용하여 에이전트 등록](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/personal-access-token-agent-registration?view=azure-devops)을 참조하세요. | DevOps | 
| Kubernetes 배포 매니페스트 파일을 생성합니다. | 프라이빗 Amazon EKS 클러스터에 Azure DevOps 에이전트를 배포하려면 다음 매니페스트 파일을 복사하고 파일을 로 저장합니다. `agent-deployment.yaml` <pre>apiVersion: apps/v1<br />kind: Deployment<br />metadata:<br />  name: azure-pipelines-agent-eks<br />  labels:<br />    app: azure-pipelines-agent<br />spec:<br />  replicas: 1<br />  selector:<br />    matchLabels:<br />      app: azure-pipelines-agent<br />  template:<br />    metadata:<br />      labels:<br />        app: azure-pipelines-agent<br />    spec:<br />      containers:<br />      - name: docker<br />        image: docker:dind<br />        securityContext: <br />          privileged: true<br />        volumeMounts:<br />        - name: shared-workspace<br />          mountPath: /workspace<br />        - name: dind-storage<br />          mountPath: /var/lib/docker<br />        env:<br />        - name: DOCKER_TLS_CERTDIR<br />          value: ""<br />      - name: azure-pipelines-agent<br />        image: aws_account_id.dkr.ecr.region.amazonaws.com/webapp:latest<br />        env:<br />        - name: AZP_URL<br />          value: "<Azure account URL>"<br />        - name: AZP_POOL<br />          value: "eks-agent"<br />        - name: AZP_TOKEN<br />          valueFrom:<br />            secretKeyRef:<br />              name: azdevops-pat<br />              key: AZP_TOKEN<br />        - name: AZP_AGENT_NAME<br />          valueFrom:<br />            fieldRef:<br />              fieldPath: metadata.name<br />        - name: DOCKER_HOST<br />          value: tcp://localhost:2375<br />        volumeMounts:<br />        - mountPath: /workspace<br />          name: shared-workspace<br />      volumes:<br />      - name: dind-storage<br />        emptyDir: {}<br />      - name: shared-workspace<br />        emptyDir: {}</pre>`aws_account_id` 및를 AWS 계정 ID 및 Azure DevOps 계정 URL`<Azure account URL>`로 바꿉니다. | DevOps | 
| 프라이빗 Amazon EKS 클러스터에 에이전트를 배포합니다. | 프라이빗 Amazon EKS 클러스터에 Azure Devops 에이전트를 배포하려면 다음 명령을 사용합니다.<pre>kubectl create -f agent-deployment.tf</pre> | DevOps | 
|  에이전트가 실행 중인지 확인 |  에이전트가 실행 중인지 확인하려면 다음 명령을 사용합니다.<pre>kubectl get deploy azure-pipelines-agent-eks<br /></pre>출력은 다음 예시와 비슷해야 합니다.<pre><br />NAME                        READY   UP-TO-DATE   AVAILABLE   AGE<br />azure-pipelines-agent-eks   1/1     1            1           58s</pre>`READY `열에가 표시되는지 확인합니다`1/1`. | DevOps | 
| 에이전트가 Azure DevOps 에이전트 풀에 등록되어 있는지 확인합니다. | 에이전트가 프라이빗 Amazon EKS 클러스터에 배포되고 에이전트 풀에 등록되었는지 확인하려면 다음 단계를 `eks-agent`사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)**온라인** **상태**인 에이전트가 하나 나열되고 에이전트 이름이 **azure-pipelines-agent-eks-\$1**로 시작해야 합니다. | DevOps | 

### 샘플 애플리케이션 배포
<a name="deploy-sample-application"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 샘플 애플리케이션 리포지토리를 GitHub 계정으로 포크합니다. | GitHub 계정에 다음 AWS 샘플 리포지토리를 포크합니다.[https://github.com/aws-samples/deploy-kubernetes-resources-to-amazon-eks-using-azure-devops](https://github.com/aws-samples/deploy-kubernetes-resources-to-amazon-eks-using-azure-devops) | DevOps | 
| 파이프라인 생성. | Azure DevOps 계정에서 파이프라인을 생성하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)<pre>pool:<br />  name: eks-agent<br />#pool: self-hosted # If you are running self-hosted Azure DevOps Agents<br /><br />stages:<br /># Refering the pipeline template, input parameter that are not specified will be added with defaults<br />- template: ./pipeline_templates/main_template.yaml<br />  parameters:<br />    serviceConnectionName: aws-sc<br />    awsRegion: <your region><br />    awsEKSClusterName: <name of your EKS cluster><br />    projectName: webapp<br /></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | DevOps | 
| 샘플 애플리케이션이 실행 중인지 확인합니다. | 파이프라인이 완료되면 Amazon ECR 리포지토리와 Amazon EKS 클러스터를 모두 확인하여 샘플 애플리케이션의 성공적인 배포를 확인합니다.Amazon ECR 리포지토리에서 아티팩트를 확인하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)예: `20250501.1-image` 및 `20250501.1-helm`.네임스페이스의 프라이빗 Amazon EKS 클러스터에서 배포를 확인하려면 다음 명령을 `webapp`사용합니다.<pre>kubectl get deploy -n webapp </pre>예상 출력은 다음과 같습니다.<pre><br />NAME     READY   UP-TO-DATE   AVAILABLE<br />webapp   1/1     1            1           </pre>참고: 첫 번째 파이프라인 실행인 경우 서비스 연결 및 에이전트 풀을 승인해야 할 수 있습니다. Azure DevOps 파이프라인 인터페이스에서 권한 요청을 찾아 계속 진행하도록 승인합니다. | DevOps | 

## 문제 해결
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| Amazon ECR 리포지토리 이름이 일치하지 않으면 파이프라인이 실패합니다. `webapp`  | 샘플 애플리케이션은 Amazon ECR 리포지토리 이름이의 `projectName: webapp` 파라미터와 일치할 것으로 예상합니다`azure_pipeline.yml`.이 문제를 해결하려면 Amazon ECR 리포지토리의 이름을 로 바꾸`webapp`거나 다음을 업데이트합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | 
| 오류: Kubernetes 클러스터에 연결할 수 없음: 서버에서 클라이언트에 자격 증명을 제공하도록 요청했습니다. | Azure 파이프라인의 "Helm 차트 풀 및 배포" 단계에서이 오류가 발생하는 경우 근본 원인은 일반적으로 Amazon EKS 클러스터의에서 잘못된 IAM 역할 구성으로 인해 발생합니다`aws-auth ConfigMap`.이 문제를 해결하려면 다음과 같이 실행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | 

## 관련 리소스
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-resources"></a>

**AWS 블로그**
+ [OpenID Connect를 사용하여 Azure DevOps AWS 에서 로 페더레이션하는 방법](https://aws.amazon.com/blogs/modernizing-with-aws/how-to-federate-into-aws-from-azure-devops-using-openid-connect/)

**AWS 서비스 설명서**
+ [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)
+ [Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)

**Microsoft 설명서**
+ [Azure DevOps란 무엇인가요?](https://learn.microsoft.com/en-us/azure/devops/user-guide/what-is-azure-devops?view=azure-devops)
+ [Azure Pipelines이란 무엇인가요?](https://learn.microsoft.com/en-us/azure/devops/pipelines/get-started/what-is-azure-pipelines?view=azure-devops)

# Terraform을 사용하여 Amazon Redshift SQL 쿼리 실행
<a name="execute-redshift-sql-queries-using-terraform"></a>

*Sylvia Qi 및 Aditya Ambati, Amazon Web Services*

## 요약
<a name="execute-redshift-sql-queries-using-terraform-summary"></a>

Amazon Redshift의 배포 및 관리에 코드형 인프라(IaC)를 사용하는 것은 DevOps 내에서 널리 사용되는 관행입니다. IaC는 클러스터, 스냅샷 및 파라미터 그룹과 같은 다양한 Amazon Redshift 리소스의 배포 및 구성을 용이하게 합니다. 그러나 IaC는 테이블, 스키마, 뷰 및 저장 프로시저와 같은 데이터베이스 리소스의 관리로 확장되지 않습니다. 이러한 데이터베이스 요소는 SQL 쿼리를 통해 관리되며 IaC 도구에서 직접 지원되지 않습니다. 이러한 리소스를 관리하기 위한 솔루션과 도구가 있지만 기술 스택에 추가 도구를 도입하지 않는 것이 좋습니다.

이 패턴은 Terraform을 사용하여 테이블, 스키마, 뷰 및 저장 프로시저를 포함한 Amazon Redshift 데이터베이스 리소스를 배포하는 방법론을 간략하게 설명합니다. 패턴은 두 가지 유형의 SQL 쿼리를 구분합니다.
+ **반복할 수 없는 쿼리** - 이러한 쿼리는 초기 Amazon Redshift 배포 중에 한 번 실행되어 필수 데이터베이스 구성 요소를 설정합니다.
+ **반복 가능한 쿼리** - 이러한 쿼리는 변경할 수 없으며 데이터베이스에 영향을 주지 않고 다시 실행할 수 있습니다. 이 솔루션은 Terraform을 사용하여 반복 가능한 쿼리의 변경 사항을 모니터링하고 그에 따라 적용합니다.

자세한 내용은 [추가 정보의](#execute-redshift-sql-queries-using-terraform-additional) *솔루션 안내서*를 참조하세요.

## 사전 조건 및 제한 사항
<a name="execute-redshift-sql-queries-using-terraform-prereqs"></a>

**사전 조건 **

가 활성화되어 AWS 계정 있어야 하며 배포 시스템에 다음을 설치해야 합니다.
+ [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (AWS CLI)
+ Amazon Redshift 읽기/쓰기 권한으로 구성된 [AWS CLI 프로필](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) 
+ Terraform 버전 1.6.2 이상
+ [Python3](https://www.python.org/downloads/)
+ [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)

**제한 사항 **
+ Terraform은 클러스터 생성 중에 하나의 데이터베이스만 생성할 수 있으므로이 솔루션은 단일 Amazon Redshift 데이터베이스를 지원합니다.
+ 이 패턴에는 반복 가능한 쿼리를 적용하기 전에 변경 사항을 검증하는 테스트가 포함되지 않습니다. 신뢰성 향상을 위해 이러한 테스트를 통합하는 것이 좋습니다.
+ 솔루션을 설명하기 위해이 패턴은 로컬 Terraform 상태 `redshift.tf` 파일을 사용하는 샘플 파일을 제공합니다. 그러나 프로덕션 환경의 경우 향상된 안정성과 협업을 위해 잠금 메커니즘이 있는 원격 상태 파일을 사용하는 것이 좋습니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) 섹션을 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

**제품 버전**

이 솔루션은 [Amazon Redshift 패치 179](https://docs.aws.amazon.com/redshift/latest/mgmt/cluster-versions.html#cluster-version-179)에서 개발 및 테스트되었습니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [amazon-redshift-sql-deploy-terraform](https://github.com/aws-samples/amazon-redshift-sql-deploy-terraform) 리포지토리에서 사용할 수 있습니다.

## 아키텍처
<a name="execute-redshift-sql-queries-using-terraform-architecture"></a>

다음 다이어그램은 Terraform이 반복 불가능한 SQL 쿼리와 반복 가능한 SQL 쿼리를 모두 처리하여 Amazon Redshift 데이터베이스 리소스를 관리하는 방법을 보여줍니다.

![\[Terraform이 SQL 쿼리를 사용하여 Amazon Redshift 데이터베이스 리소스를 관리하는 프로세스입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/0f4467ac-761b-4b6b-a32f-e18a2ca2245d/images/3b6ff9e8-e3d1-48ed-9fa1-4b14f7d3d65b.png)


이 다이어그램은 다음 단계를 보여 줍니다.

1. Terraform은 초기 Amazon Redshift 클러스터 배포 중에 반복할 수 없는 SQL 쿼리를 적용합니다.

1. 개발자는 반복 가능한 SQL 쿼리에 변경 사항을 커밋합니다.

1. Terraform은 반복 가능한 SQL 쿼리의 변경 사항을 모니터링합니다.

1. Terraform은 반복 가능한 SQL 쿼리를 Amazon Redshift 데이터베이스에 적용합니다.

이 패턴에서 제공하는 솔루션은 [Amazon Redshift용 Terraform 모듈을](https://registry.terraform.io/modules/terraform-aws-modules/redshift/aws/latest) 기반으로 구축되었습니다. Terraform 모듈은 Amazon Redshift 클러스터와 데이터베이스를 프로비저닝합니다. 모듈을 개선하기 위해 Amazon Redshift [ExecuteStatement](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html) API 작업을 사용하여 SQL 쿼리를 실행하기 위해 사용자 지정 Python 스크립트를 간접적으로 호출하는 `terraform_data` 리소스를 사용했습니다. 따라서 모듈은 다음을 수행할 수 있습니다.
+ 데이터베이스를 프로비저닝한 후 SQL 쿼리를 사용하여 원하는 수의 데이터베이스 리소스를 배포합니다.
+ 반복 가능한 SQL 쿼리의 변경 사항을 지속적으로 모니터링하고 Terraform을 사용하여 해당 변경 사항을 적용합니다.

자세한 내용은 [추가 정보의](#execute-redshift-sql-queries-using-terraform-additional) *솔루션 안내서*를 참조하세요.

## 도구
<a name="execute-redshift-sql-queries-using-terraform-tools"></a>

**AWS 서비스**
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/mgmt/welcome.html)는의 완전관리형 페타바이트 규모의 데이터 웨어하우스 서비스입니다 AWS 클라우드.

**기타 도구**
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.
+ [Python](https://www.python.org/)은이 패턴에서 SQL 쿼리를 실행하는 데 사용되는 범용 프로그래밍 언어입니다.

## 모범 사례
<a name="execute-redshift-sql-queries-using-terraform-best-practices"></a>
+ [Amazon Redshift 모범 사례](https://docs.aws.amazon.com/redshift/latest/dg/best-practices.html)
+ [Amazon Redshift 데이터 API를 사용하여 Amazon Redshift 클러스터와 상호 작용](https://aws.amazon.com/blogs/big-data/using-the-amazon-redshift-data-api-to-interact-with-amazon-redshift-clusters/)

## 에픽
<a name="execute-redshift-sql-queries-using-terraform-epics"></a>

### Terraform을 사용하여 솔루션을 배포
<a name="deploy-the-solution-using-terraform"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| **리포지토리를 복제합니다.** | Amazon Redshift 클러스터 프로비저닝을 위한 Terraform 코드가 포함된 Git 리포지토리를 복제하려면 다음 명령을 사용합니다.<pre>git clone https://github.com/aws-samples/amazon-redshift-sql-deploy-terraform.git</pre> | DevOps 엔지니어 | 
| **Terraform 변수를 업데이트합니다.** | 특정 요구 사항에 따라 Amazon Redshift 클러스터 배포를 사용자 지정하려면 `terraform.tfvars` 파일에서 다음 파라미터를 업데이트합니다.<pre>region                    = "<AWS_REGION>"<br />cluster_identifier        = "<REDSHIFT_CLUSTER_IDENTIFIER>"<br />node_type                 = "<REDSHIFT_NODE_TYPE>"<br />number_of_nodes           = "<REDSHIFT_NODE_COUNT>"<br />database_name             = "<REDSHIFT_DB_NAME>"<br />subnet_ids                = "<REDSHIFT_SUBNET_IDS>"<br />vpc_security_group_ids    = "<REDSHIFT_SECURITY_GROUP_IDS>"<br />run_nonrepeatable_queries = true<br />run_repeatable_queries    = true<br />sql_path_bootstrap        = "<BOOTSTRAP_SQLS_PATH>"<br />sql_path_nonrepeatable    = "<NON-REPEATABLE_SQLS_PATH>"<br />sql_path_repeatable       = "<REPEATABLE_SQLS_PATH>"<br />sql_path_finalize         = "<FINALIZE_SQLS_PATH>"<br />create_random_password    = false<br />master_username           = "<REDSHIFT_MASTER_USERNAME>"</pre> | DevOps 엔지니어 | 
| Terraform을 사용하여 리소스를 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/execute-redshift-sql-queries-using-terraform.html) | DevOps 엔지니어 | 
| (선택 사항) 추가 SQL 쿼리를 실행합니다. | 샘플 리포지토리는 데모용으로 여러 SQL 쿼리를 제공합니다. 자체 SQL 쿼리를 실행하려면 다음 폴더에 추가합니다.`/bootstrap` `/nonrepeatable` `/repeatable` `/finalize` |  | 

### 실행 상태를 모니터링합니다.
<a name="monitor-the-execution-of-sql-statements"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| SQL 문의 배포를 모니터링합니다. | Amazon Redshift 클러스터에 대한 SQL 실행 결과를 모니터링할 수 있습니다. 실패 및 성공적인 SQL 실행을 보여주는 출력의 예는 [추가 정보의](#execute-redshift-sql-queries-using-terraform-additional) *예시 SQL 문*을 참조하세요. | DBA, DevOps 엔지니어 | 
| 리소스를 정리합니다. | 모든 AWS 리소스를 배포하려면 다음 명령을 실행합니다.<pre>terraform destroy</pre> | DevOps 엔지니어 | 

### 결과 검증
<a name="validate-the-results"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon Redshift 클러스터 검증 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/execute-redshift-sql-queries-using-terraform.html) | DBA, AWS DevOps | 

## 관련 리소스
<a name="execute-redshift-sql-queries-using-terraform-resources"></a>

**AWS 설명서**
+ [Amazon Redshift 프로비저닝된 클러스터](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html)
+ [Amazon Redshift Data API 문제 해결](https://docs.aws.amazon.com/redshift/latest/mgmt/data-api-troubleshooting.html)

**기타 리소스**
+ [명령: 적용](https://developer.hashicorp.com/terraform/cli/commands/apply)(Terraform 설명서)

## 추가 정보
<a name="execute-redshift-sql-queries-using-terraform-additional"></a>

**솔루션 연습**

솔루션을 사용하려면 Amazon Redshift SQL 쿼리를 특정 방식으로 구성해야 합니다. 모든 SQL 쿼리는 `.sql` 확장자가 있는 파일에 저장해야 합니다.

이 패턴과 함께 제공된 코드 예에서 SQL 쿼리는 다음 폴더 구조로 구성됩니다. 코드(`sql-queries.tf` 및 `sql-queries.py`)를 수정하여 고유한 사용 사례에 맞는 모든 구조로 작업할 수 있습니다.

```
/bootstrap
     |- Any # of files
     |- Any # of sub-folders
/nonrepeatable
     |- Any # of files
     |- Any # of sub-folders
/repeatable
     /udf
          |- Any # of files
          |- Any # of sub-folders
     /table
          |- Any # of files
          |- Any # of sub-folders
     /view
          |- Any # of files
          |- Any # of sub-folders
     /stored-procedure
          |- Any # of files
          |- Any # of sub-folders
/finalize
     |- Any # of files
     |- Any # of sub-folders
```

앞의 폴더 구조를 고려할 때 Amazon Redshift 클러스터 배포 중에 Terraform은 다음 순서로 쿼리를 실행합니다.

1. `/bootstrap`

1. `/nonrepeatable`

1. `/repeatable`

1. `/finalize`

`/repeatable`, `/udf` 및 `/table` 폴더에는 `/view`, 및 하위 폴더가 들어 있습니다. 이러한 하위 폴더는 Terraform이 SQL 쿼리를 실행하는 순서를 나타냅니다.

SQL 쿼리를 실행하는 Python 스크립트는 입니다`sql-queries.py`. 먼저 스크립트는 `sql_path_bootstrap` 파라미터와 같은 특정 소스 디렉터리의 모든 파일과 하위 폴더를 읽습니다. 그런 다음 스크립트는 Amazon Redshift [ExecuteStatement](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html) API 작업을 직접적으로 호출하여 쿼리를 실행합니다. 파일에 SQL 쿼리가 하나 이상 있을 수 있습니다. 다음 코드 조각은 Amazon Redshift 클러스터에 대해 파일에 저장된 SQL 문을 실행하는 Python 함수를 보여줍니다.

```
def execute_sql_statement(filename, cluster_id, db_name, secret_arn, aws_region):
    """Execute SQL statements in a file"""
    redshift_client = boto3.client(
        'redshift-data', region_name=aws_region)
    contents = get_contents_from_file(filename),
    response = redshift_client.execute_statement(
        Sql=contents[0],
        ClusterIdentifier=cluster_id,
        Database=db_name,
        WithEvent=True,
        StatementName=filename,
        SecretArn=secret_arn
    )
    ...
```

Terraform 스크립트 `sql-queries.tf`는 `sql-queries.py` 스크립트를 간접적으로 호출하는 [terraform\$1data](https://developer.hashicorp.com/terraform/language/resources/terraform-data) 리소스를 생성합니다. , `/bootstrap`, `/nonrepeatable` `/repeatable`및 네 개의 폴더 각각에 대한 `terraform_data` 리소스가 있습니다`/finalize`. 다음 코드 조각은 `/bootstrap` 폴더에서 SQL 쿼리를 실행하는 `terraform_data` 리소스를 보여줍니다.

```
locals {
  program               = "${path.module}/sql-queries.py"
  redshift_cluster_name = try(aws_redshift_cluster.this[0].id, null)
}

resource "terraform_data" "run_bootstrap_queries" {
  count      = var.create && var.run_nonrepeatable_queries && (var.sql_path_bootstrap != "") && (var.snapshot_identifier == null) ? 1 : 0
  depends_on = [aws_redshift_cluster.this[0]]

  provisioner "local-exec" {
    command = "python3 ${local.program} ${var.sql_path_bootstrap} ${local.redshift_cluster_name} ${var.database_name} ${var.redshift_secret_arn} ${local.aws_region}"
  }
}
```

다음 변수를 사용하여 이러한 쿼리를 실행할지 여부를 제어할 수 있습니다. `sql_path_bootstrap`, `sql_path_nonrepeatable``sql_path_repeatable`, 또는에서 쿼리를 실행하지 않으려면 해당 값을 로 `sql_path_finalize`설정합니다`""`.

```
  run_nonrepeatable_queries = true
  run_repeatable_queries    = true
  sql_path_bootstrap        = "src/redshift/bootstrap"
  sql_path_nonrepeatable    = "src/redshift/nonrepeatable"
  sql_path_repeatable       = "src/redshift/repeatable"
  sql_path_finalize         = "src/redshift/finalize"
```

를 실행하면 `terraform apply`Terraform은 스크립트의 결과에 관계없이 스크립트가 완료된 후 추가된 `terraform_data` 리소스를 고려합니다. 일부 SQL 쿼리가 실패하여 다시 실행하려는 경우 Terraform 상태에서 리소스를 수동으로 제거하고 `terraform apply` 다시 실행할 수 있습니다. 예를 들어 다음 명령은 Terraform 상태에서 `run_bootstrap_queries` 리소스를 제거합니다.

`terraform state rm module.redshift.terraform_data.run_bootstrap_queries[0]`

다음 코드 예에서는 `run_repeatable_queries` 리소스가 [sha256 해시](https://developer.hashicorp.com/terraform/language/functions/sha256)를 사용하여 `repeatable` 폴더의 변경 사항을 모니터링하는 방법을 보여줍니다. 폴더 내의 파일이 업데이트되면 Terraform은 업데이트를 위해 전체 디렉터리를 표시합니다. 그런 다음 Terraform은 다음에서 디렉터리의 쿼리를 다시 실행합니다`terraform apply`.

```
resource "terraform_data" "run_repeatable_queries" {
  count      = var.create_redshift && var.run_repeatable_queries && (var.sql_path_repeatable != "") ? 1 : 0
  depends_on = [terraform_data.run_nonrepeatable_queries]

  # Continuously monitor and apply changes in the repeatable folder
  triggers_replace = {
    dir_sha256 = sha256(join("", [for f in fileset("${var.sql_path_repeatable}", "**") : filesha256("${var.sql_path_repeatable}/${f}")]))
  }

  provisioner "local-exec" {
    command = "python3 ${local.sql_queries} ${var.sql_path_repeatable} ${local.redshift_cluster_name} ${var.database_name} ${var.redshift_secret_arn}"
  }
}
```

코드를 구체화하기 위해 모든 파일에 변경 사항을 무차별적으로 적용하는 대신 `repeatable` 폴더 내에서 업데이트된 파일에만 변경 사항을 감지하고 적용하는 메커니즘을 구현할 수 있습니다.

**SQL 문 예시**

다음 출력은 오류 메시지와 함께 실패한 SQL 실행을 보여줍니다.

```
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): Executing: ["/bin/sh" "-c" "python3 modules/redshift/sql-queries.py src/redshift/nonrepeatable testcluster-1 db1 arn:aws:secretsmanager:us-east-1:XXXXXXXXXXXX:secret:/redshift/master_user/password-8RapGH us-east-1"]
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): -------------------------------------------------------------------
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): src/redshift/nonrepeatable/table/admin/admin.application_family.sql
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): -------------------------------------------------------------------
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): Status: FAILED
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): SQL execution failed.
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): Error message: ERROR: syntax error at or near ")"
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec):   Position: 244
module.redshift.terraform_data.run_nonrepeatable_queries[0]: Creation complete after 3s [id=ee50ba6c-11ae-5b64-7e2f-86fd8caa8b76]
```

다음 출력은 성공적인 SQL 실행을 보여줍니다.

```
module.redshift.terraform_data.run_bootstrap_queries[0]: Provisioning with 'local-exec'...
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): Executing: ["/bin/sh" "-c" "python3 modules/redshift/sql-queries.py src/redshift/bootstrap testcluster-1 db1 arn:aws:secretsmanager:us-east-1:XXXXXXXXXXXX:secret:/redshift/master_user/password-8RapGH us-east-1"]
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): -------------------------------------------------------------------
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): src/redshift/bootstrap/db.sql
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): -------------------------------------------------------------------
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): Status: FINISHED
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): SQL execution successful.
module.redshift.terraform_data.run_bootstrap_queries[0]: Creation complete after 2s [id=d565ef6d-be86-8afd-8e90-111e5ea4a1be]
```

# AWS Organizations의 조직 전체에서 AWS Backup 보고서를 CSV 파일로 내보내기
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file"></a>

*Aromal Raj Jayarajan, Purushotham G K, Amazon Web Services*

## 요약
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-summary"></a>

이 패턴은 AWS Organizations의 조직 전체에서 AWS Backup 작업 보고서를 CSV 파일로 내보내는 방법을 보여줍니다. 이 솔루션은 AWS Lambda와 Amazon EventBridge를 사용하여 AWS Backup 작업 보고서를 상태에 따라 분류하므로 상태 기반 자동화를 구성할 때 도움이 될 수 있습니다.

AWS Backup은 조직이 AWS 서비스 전체, 클라우드 및 온프레미스에서 데이터 보호를 중앙에서 관리하고 자동화하는 데 도움을 줍니다. 하지만 AWS Organizations 내에 구성된 AWS Backup 작업의 경우 통합 보고는 각 조직의 관리 계정의 AWS Management Console에서만 사용할 수 있습니다. 이 보고를 관리 계정 외부로 가져오면 감사에 필요한 노력을 줄이고 자동화, 알림 및 경보의 범위를 늘릴 수 있습니다.

## 사전 조건 및 제한 사항
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-prereqs"></a>

**사전 조건**
+ 활성 상태의 AWS 계정
+ 하나 이상의 관리 계정과 멤버 계정을 포함하는 AWS Organizations에서 활성 [조직](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_tutorials_basic.html)
+ AWS Organizations의 조직 수준에서 구성된 AWS 백업 (자세한 내용은 [AWS Blog의 AWS Backup을 사용하여 AWS 서비스 전반에 걸쳐 대규모 중앙 집중식 백업 자동화](https://aws.amazon.com/blogs/storage/automate-centralized-backup-at-scale-across-aws-services-using-aws-backup/)를 참조)
+ [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git), 로컬 머신에 설치 및 구성됨

**제한 사항**

이 패턴으로 제공된 솔루션은 AWS Backup 작업에만 구성된 AWS 리소스를 식별합니다. 보고서에서는 AWS Backup을 통해 백업하도록 구성되지 않은 AWS 리소스를 식별할 수 없습니다.

## 아키텍처
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-architecture"></a>

**대상 기술 스택**
+ AWS Backup
+ AWS CloudFormation
+ Amazon EventBridge
+ AWS Lambda
+ AWS Security Token Service (AWS STS)
+ Amazon Simple Storage Service(Amazon S3)
+ AWS Identity and Access Management(IAM)

**대상 아키텍처**

다음 다이어그램은 AWS Organizations의 조직 전체에서 AWS Backup 작업 보고서를 CSV 파일로 내보내는 예제 워크플로우를 보여줍니다.

![\[EventBridge, Lambda, AWS STS 및 IAM을 사용하여 조직 전체에서 AWS Backup 작업 보고서를 CSV 형식으로 내보냅니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/74955aad-cc6d-488b-aa34-ae43f50fec60/images/5c39c79f-e731-4ad0-b404-51ebe0976420.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 예약된 EventBridge 이벤트 규칙은 멤버(보고) AWS 계정에서 Lambda 함수를 호출합니다.

1. 그런 다음 Lambda 함수는 AWS STS를 사용하여 관리 계정에 연결하는 데 필요한 권한이 있는 IAM 역할을 수임합니다.

1. 그런 다음 Lambda 함수는 다음 작업을 수행합니다.
   + AWS 백업 서비스에 통합된 AWS 백업 작업 보고서 요청
   + AWS Backup 작업 상태를 기반으로 결과를 분류
   + 응답을 CSV 파일로 변환
   + 생성 날짜를 기준으로 레이블이 지정된 폴더 내의 보고 계정의 Amazon S3 버킷에 결과를 업로드

## 도구
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-tools"></a>

**도구**
+ [AWS Backup](https://docs.aws.amazon.com/aws-backup/latest/devguide/whatisbackup.html)은 AWS 서비스 전체, 클라우드 및 온프레미스에서 데이터 보호를 중앙 집중화하고 자동화하는 데 도움을 주는 완전관리형 서비스입니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)을 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, 전체 AWS 계정 및 리전에서 수명 주기 전반에 걸쳐 관리할 수 있습니다.
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)는 애플리케이션을 다양한 소스의 실시간 데이터와 연결할 수 있는 서버리스 이벤트 버스 서비스입니다. AWS Lambda 함수, API 대상을 사용하는 HTTP 간접 호출 엔드포인트 또는 다른 AWS 계정의 이벤트 버스를 예로 들 수 있습니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [Amazon Simple Storage Service(Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.

**코드 **

이 패턴의 코드는 GitHub [aws-backup-report-generator](https://github.com/aws-samples/aws-backup-report-generator) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-best-practices"></a>
+ [Amazon S3의 보안 모범 사례](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-best-practices.html)(*Amazon S3 사용 설명서*)
+ [AWS Lambda 함수를 사용한 모범 사례](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)(*AWS Lambda 개발자 가이드*)
+ [관리 계정 모범 사례](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_best-practices_mgmt-acct.html)(*AWS Organizations 사용 설명서*)

## 에픽
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-epics"></a>

### 솔루션 구성 요소 배포
<a name="deploy-the-solution-components"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| GitHub 리포지토리를 복제합니다. | 터미널 창에 다음 명령을 실행하여 GitHub [aws-backup-report-generator](https://github.com/aws-samples/aws-backup-report-generator) 리포지토리를 복제합니다.<pre>git clone https://github.com/aws-samples/aws-backup-report-generator.git</pre>자세한 내용은 GitHub Docs에서 [리포지토리 복제](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)를 참조하세요. | AWS DevOps, DevOps 엔지니어 | 
| 멤버(보고) AWS 계정에 솔루션 구성 요소를 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | DevOps 엔지니어, AWS DevOps | 

### 솔루션 테스트
<a name="test-the-solution"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 테스트하기 전에 EventBridge 규칙이 실행되는지 확인합니다. | 24시간 이상 기다리거나 CloudFormation 템플릿의 **template-reporting.yml** 파일에서 보고 빈도를 늘려 EventBridge 규칙이 실행되는지 확인합니다.**보고 빈도를 높이려면**[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | AWS DevOps, DevOps 엔지니어 | 
| 생성된 보고서에 대한 Amazon S3 버킷을 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | AWS DevOps, DevOps 엔지니어 | 

### 리소스 정리
<a name="clean-up-your-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 멤버(보고) 계정에서 솔루션 구성 요소를 삭제합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | AWS DevOps, DevOps 엔지니어 | 
| 관리 계정에서 솔루션 구성 요소를 삭제합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | AWS DevOps, DevOps 엔지니어 | 

## 관련 리소스
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-resources"></a>
+ [자습서: 예정된 이벤트와 함께 AWS Lambda 사용](https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents-tutorial.html)(AWS Lambda 설명서)
+ [AWS Lambda 함수를 실행하기 위한 예약된 이벤트 생성](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html)(AWS SDK for JavaScript 설명서)
+ [IAM 자습서: IAM 역할을 사용한 AWS 계정 간 액세스 권한 위임](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)(IAM 설명서)
+ [AWS Organizations 용어 및 개념](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html) (AWS Organizations 설명서)
+ [AWS Backup 콘솔을 사용하여 보고서 계획 생성](https://docs.aws.amazon.com/aws-backup/latest/devguide/create-report-plan-console.html)(AWS Backup 설명서)
+ [감사 보고서 생성](https://docs.aws.amazon.com/aws-backup/latest/devguide/create-audit-report.html)(AWS Backup 설명서)
+ [온디맨드 보고서 생성](https://docs.aws.amazon.com/aws-backup/latest/devguide/create-on-demand-reports.html)(AWS Backup 설명서)
+ [AWS Backup이란 무엇입니까?](https://docs.aws.amazon.com/aws-backup/latest/devguide/whatisbackup.html) (AWS Backup 설명서)
+ [AWS Backup을 사용하여 AWS 서비스 전반에서 대규모 중앙 집중식 백업 자동화](https://aws.amazon.com/blogs/storage/automate-centralized-backup-at-scale-across-aws-services-using-aws-backup/)(AWS Blog 게시물)

# Amazon EC2 인스턴스 목록의 태그를 CSV 파일로 내보내기
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file"></a>

*Sida Ju, Pac Joonhyun, Amazon Web Services*

## 요약
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-summary"></a>

이 패턴은 프로그래밍 방식으로 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스 목록의 태그를 CSV 파일로 내보내는 방법을 보여줍니다.

제공된 예제 Python 스크립트를 사용하면 Amazon EC2 인스턴스를 검토하고 특정 태그별로 분류하는 데 걸리는 시간을 줄일 수 있습니다. 예를 들어, 이 스크립트를 사용하여 보안팀이 소프트웨어 업데이트를 위해 신고한 인스턴스 목록을 빠르게 식별하고 분류할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-prereqs"></a>

**사전 조건 **
+ Python 3 설치 및 구성
+ AWS Command Line Interface(AWS CLI) 설치 및 구성

**제한 사항 **

이 패턴에 제공된 예제 Python 스크립트는 다음 속성만을 기반으로 Amazon EC2 인스턴스를 검색할 수 있습니다.
+ 인스턴스 ID
+ 프라이빗 IPv4 주소
+ 퍼블릭 IPv4 주소

## 도구
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-tools"></a>
+ [Python](https://www.python.org/)은 범용 컴퓨터 프로그래밍 언어입니다.
+ [virtualenv](https://virtualenv.pypa.io/en/latest/)를 사용하면 격리된 Python 환경을 생성할 수 있습니다.
+ [AWS Command Line Interface(AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 쉘에서 명령을 사용하여 AWS 서비스와 상호 작용할 수 있는 오픈 소스 도구입니다.

**코드 리포지토리**

이 패턴에 대한 예제 Python 스크립트는 GitHub [search-ec2-instances-export-tags](https://github.com/aws-samples/search-ec2-instances-export-tags) 리포지토리에서 사용할 수 있습니다.

## 에픽
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-epics"></a>

### 사전 조건 설치 및 구성
<a name="install-and-configure-the-prerequisites"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| GitHub 리포지토리를 복제합니다. | AWS CLI 명령을 실행할 때 오류가 발생하는 경우 [최신 AWS CLI 버전을 사용하고 있는지 확인](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-troubleshooting.html)하십시오.터미널 창에서 다음 Git 명령을 실행하여 GitHub [search-ec2-instances-export-tags](https://github.com/aws-samples/search-ec2-instances-export-tags) 리포지토리를 복제합니다.<pre>git clone https://github.com/aws-samples/search-ec2-instances-export-tags.git</pre> | DevOps 엔지니어 | 
| 가상 환경을 설치하고 활성화합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file.html)자세한 내용은 [가상 환경 사용 설명서](https://virtualenv.pypa.io/en/latest/user_guide.html)를 참조하십시오. | DevOps 엔지니어 | 
| 종속 항목 설치 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file.html) | DevOps 엔지니어 | 
| AWS 명명된 프로파일을 구성합니다. | 아직 구성하지 않았다면 스크립트 실행에 필요한 자격 증명이 포함된 AWS 명명된 프로파일을 구성합니다. 명명된 프로파일을 생성하려면 [aws configure](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-methods) 명령을 실행합니다.자세한 내용은 AWS CLI 설명서에서 [네임드 프로파일 사용](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles)을 참조하세요. | DevOps 엔지니어 | 

### Python 스크립트 구성 및 실행
<a name="configure-and-run-the-python-script"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 입력 파일을 생성합니다. | 스크립트에서 태그를 검색하고 내보낼 Amazon EC2 인스턴스 목록이 포함된 입력 파일을 생성합니다. 인스턴스 ID, 프라이빗 IPv4 주소 또는 퍼블릭 IPv4 주소를 나열할 수 있습니다.각 Amazon EC2 인스턴스가 입력 파일의 한 줄에 나열되어 있는지 확인하십시오.**입력 파일 예제**<pre>1    i-0547c351bdfe85b9f<br />2    54.157.194.156<br />3    172.31.85.33<br />4    54.165.198.144<br />5    i-0b6223b5914111a4b<br />6    172.31.85.44<br />7    54.165.198.145<br />8    172.31.80.219<br />9    172.31.94.199</pre> | DevOps 엔지니어 | 
|  Python 스크립트를 실행합니다. | 터미널에서 다음 명령을 실행하여 스크립트를 실행합니다.<pre>python search_instances.py -i INPUTFILE -o OUTPUTFILE -r REGION [-p PROFILE]</pre>`INPUTFILE`을 입력 파일의 이름으로 바꿉니다. `OUTPUTFILE`을 CSV 출력 파일에 부여할 이름으로 바꿉니다. `REGION`을 Amazon EC2 리소스가 있는 AWS 리전으로 바꿉니다. AWS 명명된 프로파일을 사용하는 경우 `PROFILE`을 사용 중인 명명된 프로파일로 바꾸십시오.지원되는 파라미터 및 설명 목록을 가져오려면 다음 명령을 실행합니다.<pre>python search_instances.py -h</pre>자세한 내용과 출력 파일 예제를 보려면 GitHub [search-ec2-instances-export-tags](https://github.com/aws-samples/search-ec2-instances-export-tags) 리포지토리의 `README.md` 파일을 참조하십시오. | DevOps 엔지니어 | 

## 관련 리소스
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-resources"></a>
+ [AWS CLI 구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) (*AWS CLI 사용 설명서*)

# Troposphere를 사용하여 AWS Config 관리형 규칙이 포함된 AWS CloudFormation 템플릿을 생성합니다.
<a name="generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere"></a>

*Lucas Nation, Freddie Wilson, Amazon Web Services*

## 요약
<a name="generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere-summary"></a>

많은 조직이 [AWS Config 관리형](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_use-managed-rules.html) 규칙을 사용하여 일반적인 모범 사례에 대한 Amazon Web Services(AWS) 리소스의 규정 준수를 평가합니다. 하지만 이러한 규칙은 유지 관리하는 데 시간이 많이 걸릴 수 있으며 이 패턴을 사용하면 Python 라이브러리인 [Troposphere](https://troposphere.readthedocs.io/en/latest/quick_start.html)를 활용하여 AWS Config 관리형 규칙을 생성하고 관리할 수 있습니다.

이 패턴은 Python 스크립트를 사용하여 AWS 관리형 규칙이 포함된 Microsoft Excel 스프레드시트를 AWS CloudFormation 템플릿으로 변환함으로써 AWS Config 관리형 규칙을 관리하는 데 도움이 됩니다. Troposphere는 코드형 인프라(IAC) 역할을 하므로 JSON 또는 YAML 형식의 파일을 사용하는 대신 관리형 규칙을 사용하여 Excel 스프레드시트를 업데이트할 수 있습니다. 그런 다음 템플릿을 사용하여 AWS 계정에서 관리형 규칙을 생성하고 업데이트하는 AWS CloudFormation 스택을 시작합니다.

AWS CloudFormation 템플릿은 Excel 스프레드시트를 사용하여 각 AWS Config 관리형 규칙을 정의하므로 AWS Management Console 에서 개별 규칙을 수동으로 생성하지 않아도 됩니다. 스크립트는 각 관리형 규칙의 파라미터를 빈 딕셔너리로 기본 설정하고 범위의 `ComplianceResourceTypes` 기본값은 `THE_RULE_IDENTIFIER.template file`에서 초기화합니다.** 규칙 식별자에 대한 자세한 내용은 AWS Config 설명서의 [AWS CloudFormation 템플릿을 사용하여 AWS Config 관리형 규칙 생성](https://docs.aws.amazon.com/config/latest/developerguide/aws-config-managed-rules-cloudformation-templates.html)을 참조하세요.

## 사전 조건 및 제한 사항
<a name="generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정.
+ AWS CloudFormation 템플릿을 사용하여 AWS Config 관리형 규칙을 생성하는 방법에 대한 지식. 이에 대한 자세한 내용은 AWS Config 설명서의 [AWS CloudFormation 템플릿을 사용하여 AWS Config 관리형 규칙 생성](https://docs.aws.amazon.com/config/latest/developerguide/aws-config-managed-rules-cloudformation-templates.html)을 참조하세요. 
+ 설치 및 구성된 Python 3. 이에 대한 자세한 내용은 [Python 설명서](https://www.python.org/)를 참조하세요.
+ 기존의 통합 개발 환경(IDE). 
+ 첨부된 샘플 `excel_config_rules.xlsx` Excel 스프레드시트의 열에서 조직 단위(OU)를 식별합니다.

## 에픽
<a name="generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere-epics"></a>

### AWS Config 관리형 규칙을 사용자 지정하고 구성합니다.
<a name="customize-and-configure-the-aws-config-managed-rules"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 샘플 Excel 스프레드시트를 업데이트합니다. | 첨부된 샘플 `excel_config_rules.xlsx` Excel 스프레드시트와 레이블을 다운로드하여 사용하려는 AWS Config 관리형 규칙으로 `Implemented`로 레이블을 지정합니다. `Implemented`로 표시된 규칙은 AWS CloudFormation 템플릿에 추가됩니다. | 개발자 | 
| (선택 사항) AWS Config 규칙 파라미터를 사용하여 config\$1rules\$1params.json 파일을 업데이트합니다. | 일부 AWS Config 관리형 규칙에는 파라미터가 필요하며 `--param-file` 옵션을 사용하여 Python 스크립트에 JSON 파일로 전달해야 합니다. 예를 들어, `access-keys-rotated` 관리형 규칙은 다음 `maxAccessKeyAge` 파라미터를 사용합니다.<pre>{<br />         "access-keys-rotated": {<br />             "InputParameters": {<br />                 "maxAccessKeyAge": 90<br />             }<br />         }<br />     }</pre>이 샘플 파라미터에서는 `maxAccessKeyAge`가 90일로 설정되어 있습니다. 스크립트는 파라미터 파일을 읽고 찾은 `InputParameters`를 추가합니다. | 개발자 | 
| (선택 사항) config\$1rules\$1params.json 파일을 AWS Config ComplianceResourceTypes로 업데이트합니다. | 기본적으로 Python 스크립트는 AWS 정의 템플릿에서 `ComplianceResourceTypes`를 검색합니다. 특정 AWS Config 관리형 규칙의 범위를 재정의하려면 `--param-file` 옵션을 사용하여 Python 스크립트에 JSON 파일로 전달해야 합니다.예를 들어, 다음 샘플 코드는 `ec2-volume-inuse-check`를 위한 `ComplianceResourceTypes`가 `["AWS::EC2::Volume"]` 목록에 어떻게 설정되는지 보여줍니다.<pre>{<br />         "ec2-volume-inuse-check": {<br />             "Scope": {<br />                 "ComplianceResourceTypes": [<br />                     "AWS::EC2::Volume"<br />                 ]<br />             }<br />         }<br />     }</pre> | 개발자 | 

### Python 스크립트 실행
<a name="run-the-python-script"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| requirements.txt 파일에서 pip 패키지를 설치합니다. | 첨부된 `requirements.txt` 파일을 다운로드하고 IDE에서 다음 명령을 실행하여 Python 패키지를 설치합니다.`pip3 install -r requirements.txt` | 개발자 | 
|  Python 스크립트를 실행합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere.html)다음과 같은 선택적 파라미터도 추가할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere.html) | 개발자 | 

### AWS Config 관리형 규칙을 배포합니다.
<a name="deploy-the-aws-config-managed-rules"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS CloudFormation 스택을 시작합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere.html) | 개발자 | 

## 첨부
<a name="attachments-07c1cfff-fc9e-4a1f-bd36-48f025808bd8"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/07c1cfff-fc9e-4a1f-bd36-48f025808bd8/attachments/attachment.zip) 파일의 압축을 풉니다.

# SageMaker 노트북 인스턴스에 다른 AWS 계정의 CodeCommit 리포지토리에 대한 임시 액세스 권한 부여
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account"></a>

*Helge Aufderheide, Amazon Web Services*

## 요약
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-summary"></a>

이 패턴은 Amazon SageMaker 노트북 인스턴스와 사용자에게 다른 AWS 계정에 있는 AWS CodeCommit 리포지토리에 대한 임시 액세스 권한을 부여하는 방법을 보여줍니다. 또한 이 패턴은 각 엔티티가 각 리포지토리에서 수행할 수 있는 특정 작업에 대해 세분화된 권한을 부여하는 방법을 보여줍니다.

조직에서는 종종 개발 환경을 호스팅하는 계정과 다른 AWS 계정에 CodeCommit 리포지토리를 저장합니다. 이 다중 계정 설정은 리포지토리에 대한 액세스를 제어하고 실수로 삭제될 위험을 줄이는 데 도움이 됩니다. 이러한 교차 계정 권한을 부여하기 위해 AWS Identity and Access Management(IAM) 역할을 사용하는 것이 좋습니다. 그러면 각 AWS 계정의 사전 정의된 IAM ID가 일시적으로 역할을 맡아 계정 전체에 통제된 신뢰 체인을 만들 수 있습니다.

**참고**  
유사한 절차를 적용하여 다른 IAM ID에 CodeCommit 리포지토리에 대한 크로스 계정 액세스 권한을 부여할 수 있습니다. 자세한 내용은 *AWS CodeCommit 사용 설명서*의 [역할을 사용하여 AWS CodeCommit 리포지토리에 대한 크로스 계정 액세스 구성](https://docs.aws.amazon.com/codecommit/latest/userguide/cross-account.html)을 참조하세요.

## 사전 조건 및 제한 사항
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-prereqs"></a>

**사전 조건 **
+ CodeCommit 리포지토리가 있는 활성 AWS 계정(*계정 A*)
+ SageMaker 노트북 인스턴스가 있는 두 번째 활성 AWS 계정 (*계정 B*)
+ 계정 A에서 IAM 역할을 생성하고 수정할 수 있는 충분한 권한을 가진 AWS 사용자
+ 계정 B에서 IAM 역할을 생성하고 수정할 수 있는 충분한 권한을 가진 두 번째 AWS 사용자

## 아키텍처
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-architecture"></a>

다음 다이어그램은 SageMaker 노트북 인스턴스와 하나의 AWS 계정의 사용자에게 CodeCommit 리포지토리에 대한 크로스 계정 액세스 권한을 부여하는 예제 워크플로우를 보여줍니다.

![\[CodeCommit에 대한 크로스 계정 액세스를 위한 워크플로우\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/54d0fdb3-6d25-4433-9f67-c87846633d61/images/97a799af-ce88-4495-a61c-d0cd22493ce2.png)


이 다이어그램은 다음 워크플로우를 보여줍니다.

1. 계정 B의 AWS 사용자 역할 및 SageMaker 노트북 인스턴스 역할은 [명명된 프로필](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles)을 가정합니다.

1. 명명된 프로필의 권한 정책은 계정 A의 CodeCommit 액세스 역할을 지정합니다. 그러면 해당 프로필이 이 역할을 수임합니다.

1. 계정 A에 대한 CodeCommit 액세스 역할의 신뢰 정책에 따라 계정 B의 명명된 프로필이 CodeCommit 액세스 역할을 수임할 수 있습니다.

1. 계정 A의 CodeCommit 리포지토리 IAM 권한 정책은 CodeCommit 액세스 역할이 CodeCommit 리포지토리에 액세스하는 것을 허용합니다.

**기술 스택**
+ CodeCommit
+ Git
+ IAM
+ pip
+ SageMaker

## 도구
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-tools"></a>
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 나만의 원본 제어 시스템을 관리할 필요 없이 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 버전 제어 서비스입니다.
+ [AWS Identity and Access Management(IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 사용자에 대한 인증 및 권한 부여를 제어함으로써 AWS 리소스에 대한 액세스를 안전하게 제어할 수 있습니다.
+ [Git](https://git-scm.com/)은 소프트웨어 개발 중에 소스 코드의 변경 사항을 추적하기 위한 분산 버전 제어 시스템입니다.
+ [git-remote-codecommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-git-remote-codecommit.html)은 Git을 확장하여 CodeCommit 리포지토리에서 코드를 푸시하고 가져오는 데 도움이 되는 유틸리티입니다.
+ [pip](https://pypi.org/project/pip/)는 Python용 패키지 인스톨러입니다. pip를 사용하여 Python 패키지 색인 및 기타 색인에서 패키지를 설치할 수 있습니다.

## 모범 사례
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-best-practices"></a>

IAM 정책을 사용하여 권한을 설정하는 경우 작업을 수행하는 데 필요한 권한만 부여했는지 확인합니다. 자세한 내용은 IAM 설명서의 [최소 권한 적용](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)을 참조하십시오.

이 패턴을 구현할 때는 다음을 수행해야 합니다.
+ IAM 원칙에 각 리포지토리 내에서 필요한 특정 작업을 수행하는 데 필요한 권한만 있는지 확인합니다. 예를 들어 승인된 IAM 원칙이 특정 리포지토리 브랜치에 변경 내용을 푸시하고 병합하도록 허용하되 보호된 브랜치에 대한 병합만 요청할 수 있도록 허용하는 것이 좋습니다.
+ IAM 원칙에 각 프로젝트의 역할 및 책임에 따라 서로 다른 IAM 역할이 할당되었는지 확인합니다. 예를 들어, 개발자는 릴리스 관리자 또는 AWS 관리자와는 다른 액세스 권한을 가집니다.

## 에픽
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-epics"></a>

### IAM 역할 구성
<a name="configure-the-iam-roles"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CodeCommit 액세스 역할 및 권한 정책을 구성합니다. | 이 에픽에** **설명된 수동 설정 프로세스를 자동화하려면 [AWS CloudFormation 템플릿](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)을 사용할 수 있습니다.CodeCommit 리포지토리가 포함된 계정(*계정 A*)에서 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.html)이 설정을 프로덕션 환경으로 이전하기 전에 [최소 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)을 적용하는 자체 IAM 정책을 작성하는 것이 좋습니다. 자세한 내용은 이 패턴의 **추가 정보** 섹션을 참조하세요. | 일반 AWS, AWS DevOps | 
| 계정 B의 SageMaker 노트북 인스턴스 역할에 계정 A의 CodeCommit 액세스 역할을 수임할 수 있는 권한을 부여합니다. | SageMaker 노트북 인스턴스의 IAM 역할(*계정 B*)이 포함된 계정에서 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.html)리포지토리의 Amazon 리소스 이름(ARN)을 보려면 *AWS CodeCommit 사용 설명서*의 [CodeCommit 리포지토리 세부 정보 보기](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-view-repository-details.html)를 참조하세요. | 일반 AWS, AWS DevOps | 

### 계정 B에서 SageMaker 노트북 인스턴스 설정
<a name="set-up-your-sagemaker-notebook-instance-in-account-b"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS SageMaker 노트북 인스턴스에서 계정 A의 역할을 맡을 사용자 프로필을 설정합니다. | [최신 버전의 AWS Command Line Interface(AWS CL) 가 설치되어 있어야 합니다](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).SageMaker 노트북 인스턴스가 포함된 계정(*계정 B*)에서 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.html)<pre>------.aws/config--------------<br />[profile remoterepouser]<br />role_arn = arn:aws:iam::<ID of Account A>:role/<rolename><br />role_session_name = remoteaccesssession<br />region = eu-west-1<br />credential_source  = Ec2InstanceMetadata<br />----------------------------------</pre> | 일반 AWS, AWS DevOps | 
| git-remote-codecommit 유틸리티를 설치합니다. | *AWS CodeCommit 사용 설명서*의 [2단계: git-remote-codecommit 설치](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-git-remote-codecommit.html#setting-up-git-remote-codecommit-install)의 지침을 따릅니다. | 데이터 과학자 | 

### 리포지토리에 액세스
<a name="access-the-repository"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Git 명령 또는 SageMaker를 사용하여 CodeCommit 리포지토리에 접근할 수 있습니다. | **Git 사용하기**계정 B에서 SageMaker 노트북 인스턴스의 역할을 맡은 IAM 주체는 이제 Git 명령을 실행하여 계정 A의 CodeCommit 리포지토리에 액세스할 수 있습니다. 예를 들어, 사용자는, `git clone`, `git pull`, `git push` 등의 명령을 실행할 수 있습니다.지침은 *AWS CodeCommit 사용 설명서*의 [AWS CodeCommit 리포지토리에 연결](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)을 참조하세요.CodeCommit과 함께 Git을 사용하는 방법에 대한 자세한 내용은 *AWS CodeCommit 사용 설명서*의 [AWS CodeCommit 시작하기](https://docs.aws.amazon.com/codecommit/latest/userguide/getting-started-cc.html)를 참조하세요.**SageMaker 사용하기**SageMaker 콘솔에서 Git을 사용하려면 Git이 CodeCommit 리포지토리에서 보안 인증 정보를 검색하도록 허용해야 합니다. 지침은 SageMaker 설명서의 [다른 AWS 계정의 CodeCommit 리포지토리를 노트북 인스턴스와 연결](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-git-cross.html)을 참조하세요. | Git, bash 콘솔 | 

## 관련 리소스
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-resources"></a>
+ [역할을 사용하여 AWS CodeCommit 리포지토리에 대한 크로스 계정 액세스 구성](https://docs.aws.amazon.com/codecommit/latest/userguide/cross-account.html)(AWS CodeCommit 설명서)
+ [IAM 자습서: IAM 역할을 사용한 AWS 계정 간 액세스 권한 위임](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)(IAM 설명서)

## 추가 정보
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-additional"></a>

**CodeCommit 권한을 특정 작업에 제한하기**

CodeCommit 리포지토리에서 IAM 주체가 수행할 수 있는 작업을 제한하려면 CodeCommit 액세스 정책에서 허용되는 작업을 수정합니다.

CodeCommit API 작업에 대한 자세한 내용은 *AWS CodeCommit 사용 설명서*의 [CodeCommit 권한 참조](https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html)를 참조하세요.

**참고**  
사용 사례에 맞게 [AWSCodeCommitPowerUser](https://docs.aws.amazon.com/codecommit/latest/userguide/security-iam-awsmanpol.html#managed-policies-poweruser) AWS 관리형 정책을 편집할 수도 있습니다.

**CodeCommit 권한을 특정 리포지토리로 제한하기**

특정 사용자만 둘 이상의 코드 리포지토리에 액세스할 수 있는 멀티테넌트 환경을 만들려면 다음을 수행합니다.

1. 계정 A에서 CodeCommit 액세스 역할을 여러 개 만든 다음, 계정 B의 특정 사용자가 역할을 맡을 수 있도록 각 액세스 역할의 신뢰 정책을 구성합니다.

1. 각 CodeCommit 액세스 역할 정책에 **“리소스”** 조건을 추가하여 각 역할이 맡을 수 있는 코드 리포지토리를 제한합니다.

**특정 CodeCommit 리포지토리에 대한 IAM 보안 주체의 액세스를 제한하는 “리소스” 조건의 예**

```
"Resource" : [<REPOSITORY_ARN>,<REPOSITORY_ARN> ]
```

**참고**  
동일한 AWS 계정에서 여러 코드 리포지토리를 식별하고 구별하기 위해 리포지토리 이름에 다른 접두사를 할당할 수 있습니다. 예를 들어 **myproject-subproject1-repo1** 및 **myproject-subproject2-repo1**과 같이 다양한 개발자 그룹에 맞는 접두사를 사용하여 코드 리포지토리의 이름을 지정할 수 있습니다. 그런 다음 개발자 그룹에 할당된 접두사를 기반으로 각 개발자 그룹에 대한 IAM 역할을 생성할 수 있습니다. 예를 들어 **myproject-subproject1-repoaccess**라는 역할을 생성하고 **myproject-subproject1** 접두사가 포함된 모든 코드 리포지토리에 대한 액세스 권한을 부여할 수 있습니다.

**특정 접두사가 포함된 코드 리포지토리 ARN을 참조하는 “리소스” 조건의 예**

```
"Resource" : arn:aws:codecommit:<region>:<account-id>:myproject-subproject1-*
```

# 다중 계정 DevOps 환경을 위한 GitHub Flow 분기 전략 구현
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments"></a>

*Mike Stephens와 Abhilash Vinod, Amazon Web Services*

## 요약
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-summary"></a>

소스 코드 리포지토리를 관리할 때 다양한 분기 전략이 개발 팀이 사용하는 소프트웨어 개발 및 릴리스 프로세스에 영향을 미칩니다. 일반적인 분기 전략의 예로는 Trunk, GitHub Flow 및 Gitflow가 있습니다. 이러한 전략은 서로 다른 브랜치를 사용하며, 각 환경에서 수행되는 활동은 다릅니다. DevOps 프로세스를 구현하는 조직은 이러한 분기 전략 간의 차이를 이해하는 데 도움이 되는 시각적 가이드의 이점을 누릴 수 있습니다. 조직에서이 시각적 객체를 사용하면 개발 팀이 업무를 조정하고 조직 표준을 따르는 데 도움이 됩니다. 이 패턴은이 시각적 객체를 제공하고 조직에서 GitHub Flow 분기 전략을 구현하는 프로세스를 설명합니다.

이 패턴은 여러가 있는 조직의 DevOps 분기 전략을 선택하고 구현하는 방법에 대한 설명서 시리즈의 일부입니다 AWS 계정. 이 시리즈는 처음부터 올바른 전략과 모범 사례를 적용하여 클라우드에서의 경험을 간소화하는 데 도움이 되도록 설계되었습니다. GitHub Flow는 조직에서 사용할 수 있는 가능한 분기 전략 중 하나일 뿐입니다. 이 설명서 시리즈에서는 [Trunk](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-trunk-branching-strategy-for-multi-account-devops-environments.html) 및 [Gitflow](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) 분기 모델도 다룹니다. 아직 수행하지 않은 경우이 패턴의 지침을 구현하기 전에 [다중 계정 DevOps 환경에 대한 Git 분기 전략 선택을 검토하는](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/) 것이 좋습니다. 실사를 통해 조직에 적합한 분기 전략을 선택합니다.

이 가이드에서는 조직이 GitHub 흐름 전략을 구현하는 방법을 보여주는 다이어그램을 제공합니다. [AWS Well-Architected DevOps 지침을](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html) 검토하여 모범 사례를 검토하는 것이 좋습니다. 이 패턴에는 DevOps 프로세스의 각 단계에 대한 권장 작업, 단계 및 제한이 포함됩니다.

## 사전 조건 및 제한 사항
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-prereqs"></a>

**사전 조건 **
+ Git [설치](https://git-scm.com/downloads) 이는 소스 코드 리포지토리 도구로 사용됩니다.
+ Draw.io, [설치](https://github.com/jgraph/drawio-desktop/releases)됨. 이 애플리케이션은 다이어그램을 보고 편집하는 데 사용됩니다.

## 아키텍처
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**대상 아키텍처**

다음 다이어그램은 [Punnett 사각형](https://en.wikipedia.org/wiki/Punnett_square)(Wikipedia)처럼 사용할 수 있습니다. 세로 축의 브랜치를 가로 축의 AWS 환경과 정렬하여 각 시나리오에서 수행할 작업을 결정합니다. 숫자는 워크플로의 작업 순서를 나타냅니다. 이 예에서는 `feature` 브랜치에서 프로덕션 배포까지 안내합니다.

![\[각 브랜치 및 환경의 GitHub 흐름 활동의 Punnett 제곱입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/780a5bce-3cd2-4092-8537-b7a77c3d6b8d/images/8a2a774a-cd85-466e-838e-a9a1f3b58a63.png)


GitHub Flow 접근 방식의 AWS 계정, 환경 및 브랜치에 대한 자세한 내용은 [다중 계정 DevOps 환경을 위한 Git 분기 전략 선택을 참조하세요](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach).

**자동화 및 규모 조정**

지속적 통합 및 지속적 제공(CI/CD)은 소프트웨어 릴리스 수명 주기를 자동화하는 프로세스입니다. 일반적으로 초기 커밋에서 프로덕션으로 새 코드를 가져오는 데 필요한 수동 프로세스의 대부분 또는 전부를 자동화합니다. CI/CD 파이프라인에는 샌드박스, 개발, 테스트, 스테이징 및 프로덕션 환경이 포함됩니다. 각 환경에서 CI/CD 파이프라인은 코드를 배포하거나 테스트하는 데 필요한 모든 인프라를 프로비저닝합니다. CI/CD를 사용하면 개발 팀이 코드를 변경하여 자동으로 테스트하고 배포할 수 있습니다. 또한 CI/CD 파이프라인은 기능 수락 및 배포에 대한 일관성, 표준, 모범 사례 및 최소 허용 수준을 적용하여 개발 팀에 거버넌스 및 가드레일을 제공합니다. 자세한 내용은 [AWS에서 지속적 통합 및 지속적 전달 연습](https://docs.aws.amazon.com/whitepapers/latest/practicing-continuous-integration-continuous-delivery/welcome.html)을 참조하세요.

AWS 는 CI/CD 파이프라인을 구축하는 데 도움이 되도록 설계된 개발자 서비스 제품군을 제공합니다. 예를 들어 [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)는 빠르고 안정적인 애플리케이션 및 인프라 업데이트를 위해 릴리스 파이프라인을 자동화하는 데 도움이 되는 완전관리형 지속적 제공 서비스입니다.는 소스 코드를 [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)컴파일하고 테스트를 실행하며 ready-to-deploy 있는 소프트웨어 패키지를 생성합니다. 자세한 내용은 [의 개발자 도구를 AWS](https://aws.amazon.com/products/developer-tools/) 참조하세요.

## 도구
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-tools"></a>

**AWS 서비스 및 도구**

AWS 는이 패턴을 구현하는 데 사용할 수 있는 개발자 서비스 제품군을 제공합니다.
+ [AWS CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html)는 확장성이 뛰어난 관리형 아티팩트 리포지토리 서비스로, 애플리케이션 개발을 위한 소프트웨어 패키지를 저장하고 공유하는 데 도움을 줍니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)는 Amazon Elastic Compute Cloud(Amazon EC2) 또는 온프레미스 인스턴스, AWS Lambda 함수 또는 Amazon Elastic Container Service(Amazon ECS) 서비스에 대한 배포를 자동화합니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.

**기타 도구**
+ [Draw.io 데스크톱](https://github.com/jgraph/drawio-desktop/releases)은 흐름도와 다이어그램을 만들기 위한 애플리케이션입니다. 코드 리포지토리에는 Draw.io.drawio 형식의 템플릿이 포함되어 있습니다.
+ [Figma](https://www.figma.com/design-overview/)는 공동 작업을 위해 설계된 온라인 설계 도구입니다. 코드 리포지토리에는 Figma용 .fig 형식의 템플릿이 포함되어 있습니다.

**코드 리포지토리**

이 패턴의 다이어그램에 대한이 소스 파일은 GitHub [흐름용 Git 분기 전략 GitHub](https://github.com/awslabs/git-branching-strategies-for-multiaccount-devops/tree/main/github-flow)리포지토리에서 사용할 수 있습니다. 여기에는 PNG, draw.io 및 Figma 형식의 파일이 포함됩니다. 조직의 프로세스를 지원하도록 이러한 다이어그램을 수정할 수 있습니다.

## 모범 사례
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-best-practices"></a>

[AWS Well-Architected DevOps 지침](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html) 및 [다중 계정 DevOps 환경을 위한 Git 분기 전략 선택](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)의 모범 사례 및 권장 사항을 따릅니다. 이를 통해 GitHub 흐름 기반 개발을 효과적으로 구현하고, 협업을 촉진하고, 코드 품질을 개선하고, 개발 프로세스를 간소화할 수 있습니다.

## 에픽
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-epics"></a>

### GitHub 흐름 워크플로 검토
<a name="reviewing-the-github-flow-workflows"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 표준 GitHub 흐름 프로세스를 검토합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 엔지니어 | 
| 버그 수정 GitHub 흐름 프로세스를 검토합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 엔지니어 | 
| 핫픽스 GitHub 흐름 프로세스를 검토합니다. | GitHub Flow는 코드 변경이 더 높은 환경에 자주 안정적으로 배포되는 지속적인 전송을 지원하도록 설계되었습니다. 핵심은 언제든지 모든 `feature`브랜치를 배포할 수 있다는 것입니다.`Hotfix` `feature` 또는 브랜치와 유사한 `bugfix`브랜치는 이러한 다른 브랜치 중 하나와 동일한 프로세스를 따를 수 있습니다. 그러나 긴급성을 고려할 때 핫픽스는 일반적으로 우선 순위가 더 높습니다. 팀의 정책과 상황의 즉각성에 따라 프로세스의 특정 단계를 신속하게 처리할 수 있습니다. 예를 들어 핫픽스에 대한 코드 검토는 빠르게 추적될 수 있습니다. 따라서 핫픽스 프로세스는 기능 또는 버그픽스 프로세스와 병렬이지만 핫픽스를 둘러싼 긴급성으로 인해 절차 준수가 수정되어야 할 수 있습니다. 핫픽스를 효율적이고 안전하게 처리할 수 있도록 핫픽스 관리에 대한 지침을 수립하는 것이 중요합니다. | DevOps 엔지니어 | 

## 문제 해결
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 브랜치 충돌 | GitHub Flow 모델에서 발생할 수 있는 일반적인 문제는 프로덕션 환경에서 핫픽스가 발생해야 하지만 동일한 리소스가 수정되는 `feature`, `bugfix` 또는 `hotfix` 브랜치에서 해당 변경이 발생해야 하는 경우입니다. 를 `main`에 병합할 때 상당한 충돌을 방지하려면의 변경 사항을 하위 브랜치에 자주 병합하는 것이 좋습니다`main`. | 
| 팀 성숙도 | GitHub Flow는 진정한 지속적 통합 및 지속적 전달(CI/CD)을 수용하여 상위 환경에 대한 일일 배포를 장려합니다. 팀은 기능을 구축하고 자동화 테스트를 생성할 수 있는 엔지니어링 성숙도를 가지고 있어야 합니다. 변경 사항이 승인되기 전에 팀이 전체 병합 요청 검토를 수행해야 합니다. 이를 통해 개발 프로세스의 품질, 책임 및 효율성을 높이는 강력한 엔지니어링 문화를 조성할 수 있습니다. | 

## 관련 리소스
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-resources"></a>

이 가이드에는 Git에 대한 교육이 포함되어 있지 않지만이 교육이 필요한 경우 인터넷에서 사용할 수 있는 고품질 리소스가 많이 있습니다. [Git 설명서](https://git-scm.com/doc) 사이트로 시작하는 것이 좋습니다.

다음 리소스는의 GitHub Flow 분기 여정에 도움이 될 수 있습니다 AWS 클라우드.

**AWS DevOps 지침**
+ [AWS DevOps 지침](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)
+ [AWS 배포 파이프라인 참조 아키텍처](https://pipelines.devops.aws.dev/)
+ [DevOps란 무엇인가요?](https://aws.amazon.com/devops/what-is-devops/)
+ [DevOps 리소스](https://aws.amazon.com/devops/resources/)

**GitHub 흐름 지침**
+ [GitHub Flow Quickstart 자습서](https://docs.github.com/en/get-started/using-github/github-flow)(GitHub)
+ [GitHub Flow를 사용해야 하는 이유](https://githubflow.github.io/)

**기타 리소스**
+ [12단계 앱 방법론](https://12factor.net/)(12factor.net)

# 다중 계정 DevOps 환경을 위한 Gitflow 분기 전략 구현
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments"></a>

*Mike Stephens, Stephen DiCato, Abhilash Vinod, Tim Wondergem, Amazon Web Services*

## 요약
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-summary"></a>

소스 코드 리포지토리를 관리할 때 다양한 분기 전략이 개발 팀이 사용하는 소프트웨어 개발 및 릴리스 프로세스에 영향을 미칩니다. 일반적인 분기 전략의 예로는 Trunk, Gitflow 및 GitHub Flow가 있습니다. 이러한 전략은 서로 다른 브랜치를 사용하며, 각 환경에서 수행되는 활동은 다릅니다. DevOps 프로세스를 구현하는 조직은 이러한 분기 전략 간의 차이를 이해하는 데 도움이 되는 시각적 가이드의 이점을 누릴 수 있습니다. 조직에서이 시각적 객체를 사용하면 개발 팀이 업무를 조정하고 조직 표준을 따르는 데 도움이 됩니다. 이 패턴은이 시각적 객체를 제공하고 조직에서 Gitflow 분기 전략을 구현하는 프로세스를 설명합니다.

이 패턴은 여러가 있는 조직의 DevOps 분기 전략을 선택하고 구현하는 방법에 대한 설명서 시리즈의 일부입니다 AWS 계정. 이 시리즈는 처음부터 올바른 전략과 모범 사례를 적용하여 클라우드에서의 경험을 간소화하는 데 도움이 되도록 설계되었습니다. Gitflow는 조직에서 사용할 수 있는 가능한 분기 전략 중 하나일 뿐입니다. 이 설명서 시리즈에서는 [Trunk](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-trunk-branching-strategy-for-multi-account-devops-environments.html) 및 [GitHub Flow](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) 분기 모델도 다룹니다. 아직 수행하지 않은 경우이 패턴의 지침을 구현하기 전에 [다중 계정 DevOps 환경에 대한 Git 분기 전략 선택을 검토하는](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/) 것이 좋습니다. 실사를 통해 조직에 적합한 분기 전략을 선택합니다.

이 가이드에서는 조직이 Gitflow 전략을 구현하는 방법을 보여주는 다이어그램을 제공합니다. [AWS Well-Architected DevOps 지침을](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html) 검토하여 모범 사례를 검토하는 것이 좋습니다. 이 패턴에는 DevOps 프로세스의 각 단계에 대한 권장 작업, 단계 및 제한이 포함됩니다.

## 사전 조건 및 제한 사항
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-prereqs"></a>

**사전 조건 **
+ Git [설치](https://git-scm.com/downloads) 이는 소스 코드 리포지토리 도구로 사용됩니다.
+ Draw.io, [설치](https://github.com/jgraph/drawio-desktop/releases)됨. 이 애플리케이션은 다이어그램을 보고 편집하는 데 사용됩니다.
+ (선택 사항) Gitflow 플러그인이 [설치되어](https://github.com/nvie/gitflow) 있습니다.

## 아키텍처
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**대상 아키텍처**

다음 다이어그램은 [Punnett 사각형](https://en.wikipedia.org/wiki/Punnett_square)(Wikipedia)처럼 사용할 수 있습니다. 세로 축의 브랜치를 가로 축의 AWS 환경과 정렬하여 각 시나리오에서 수행할 작업을 결정합니다. 숫자는 워크플로의 작업 순서를 나타냅니다. 이 예에서는 기능 브랜치에서 프로덕션 배포까지 안내합니다.

![\[각 브랜치 및 환경의 Gitflow 활동의 Punnett 제곱입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/1dee2a06-cc54-4797-b9a9-78b6685edd33/images/d8be49bf-dca1-4892-ac4c-11996a7258c2.png)


Gitflow 접근 방식의 AWS 계정, 환경 및 브랜치에 대한 자세한 내용은 [다중 계정 DevOps 환경을 위한 Git 브랜치 전략 선택을 참조하세요](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/).

**자동화 및 규모 조정**

지속적 통합 및 지속적 제공(CI/CD)은 소프트웨어 릴리스 수명 주기를 자동화하는 프로세스입니다. 일반적으로 초기 커밋에서 프로덕션으로 새 코드를 가져오는 데 필요한 수동 프로세스의 대부분 또는 전부를 자동화합니다. CI/CD 파이프라인에는 샌드박스, 개발, 테스트, 스테이징 및 프로덕션 환경이 포함됩니다. 각 환경에서 CI/CD 파이프라인은 코드를 배포하거나 테스트하는 데 필요한 모든 인프라를 프로비저닝합니다. CI/CD를 사용하면 개발 팀이 코드를 변경하여 자동으로 테스트하고 배포할 수 있습니다. 또한 CI/CD 파이프라인은 기능 수락 및 배포에 대한 일관성, 표준, 모범 사례 및 최소 허용 수준을 적용하여 개발 팀에 거버넌스 및 가드레일을 제공합니다. 자세한 내용은 [AWS에서 지속적 통합 및 지속적 전달 연습](https://docs.aws.amazon.com/whitepapers/latest/practicing-continuous-integration-continuous-delivery/welcome.html)을 참조하세요.

AWS 는 CI/CD 파이프라인을 구축하는 데 도움이 되도록 설계된 개발자 서비스 제품군을 제공합니다. 예를 들어 [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)는 빠르고 안정적인 애플리케이션 및 인프라 업데이트를 위해 릴리스 파이프라인을 자동화하는 데 도움이 되는 완전관리형 지속적 제공 서비스입니다.는 소스 코드를 [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)컴파일하고 테스트를 실행하며 ready-to-deploy 있는 소프트웨어 패키지를 생성합니다. 자세한 내용은 [의 개발자 도구를 AWS](https://aws.amazon.com/products/developer-tools/) 참조하세요.

## 도구
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-tools"></a>

**AWS 서비스 및 도구**

AWS 는이 패턴을 구현하는 데 사용할 수 있는 개발자 서비스 제품군을 제공합니다.
+ [AWS CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html)는 확장성이 뛰어난 관리형 아티팩트 리포지토리 서비스로, 애플리케이션 개발을 위한 소프트웨어 패키지를 저장하고 공유하는 데 도움을 줍니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)는 Amazon Elastic Compute Cloud(Amazon EC2) 또는 온프레미스 인스턴스, AWS Lambda 함수 또는 Amazon Elastic Container Service(Amazon ECS) 서비스에 대한 배포를 자동화합니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.

**기타 도구**
+ [Draw.io 데스크톱](https://github.com/jgraph/drawio-desktop/releases)은 흐름도와 다이어그램을 만들기 위한 애플리케이션입니다. 코드 리포지토리에는 Draw.io.drawio 형식의 템플릿이 포함되어 있습니다.
+ [Figma](https://www.figma.com/design-overview/)는 공동 작업을 위해 설계된 온라인 설계 도구입니다. 코드 리포지토리에는 Figma용 .fig 형식의 템플릿이 포함되어 있습니다.
+ (선택 사항) [Gitflow 플러그인](https://github.com/nvie/gitflow)은 Gitflow 분기 모델에 대한 상위 수준 리포지토리 작업을 제공하는 Git 확장 모음입니다.

**코드 리포지토리**

이 패턴의 다이어그램에 대한이 소스 파일은 GitFlow 리포지토리용 GitHub [Git 분기 전략 GitFlow](https://github.com/awslabs/git-branching-strategies-for-multiaccount-devops/tree/main/gitflow)에서 사용할 수 있습니다. 여기에는 PNG, draw.io 및 Figma 형식의 파일이 포함됩니다. 조직의 프로세스를 지원하도록 이러한 다이어그램을 수정할 수 있습니다.

## 모범 사례
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-best-practices"></a>

[AWS Well-Architected DevOps 지침](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html) 및 [다중 계정 DevOps 환경을 위한 Git 분기 전략 선택](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)의 모범 사례 및 권장 사항을 따릅니다. 이를 통해 Gitflow 기반 개발을 효과적으로 구현하고, 협업을 촉진하고, 코드 품질을 개선하고, 개발 프로세스를 간소화할 수 있습니다.

## 에픽
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-epics"></a>

### Gitflow 워크플로 검토
<a name="reviewing-the-gitflow-workflows"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 표준 Gitflow 프로세스를 검토합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 엔지니어 | 
| 핫픽스 Gitflow 프로세스를 검토합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 엔지니어 | 
| 버그 수정 Gitflow 프로세스를 검토합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 엔지니어 | 

## 문제 해결
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 브랜치 충돌 | Gitflow 모델에서 흔히 발생하는 문제는 프로덕션에서 핫픽스가 필요하지만 동일한 리소스를 수정 중인 또 다른 브랜치가 있는 하위 환경에서도 동일한 변경이 필요할 때 생기는 상황입니다. 한 번에 하나의 릴리스 브랜치만 활성화하는 것이 좋습니다. 한 번에 둘 이상의 활성 상태가 있는 경우 환경의 변경 사항이 충돌할 수 있으며 브랜치를 프로덕션으로 이동하지 못할 수 있습니다. | 
| 병합 | 릴리스는 기본 브랜치로 다시 병합하고 가능한 한 빨리 개발하여 작업을 기본 브랜치로 다시 통합해야 합니다. | 
| 스쿼시 병합 | `feature` 브랜치에서 브랜치로 병합할 때만 스쿼시 병합을 사용합니다`develop`. 상위 브랜치에서 스쿼시 병합을 사용하면 변경 사항을 하위 브랜치로 다시 병합할 때 문제가 발생합니다. | 

## 관련 리소스
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-resources"></a>

이 가이드에는 Git에 대한 교육이 포함되어 있지 않지만이 교육이 필요한 경우 인터넷에서 사용할 수 있는 고품질 리소스가 많이 있습니다. [Git 설명서](https://git-scm.com/doc) 사이트로 시작하는 것이 좋습니다.

다음 리소스는의 Gitflow 분기 여정에 도움이 될 수 있습니다 AWS 클라우드.

**AWS DevOps 지침**
+ [AWS DevOps 지침](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)
+ [AWS 배포 파이프라인 참조 아키텍처](https://pipelines.devops.aws.dev/)
+ [DevOps란 무엇인가요?](https://aws.amazon.com/devops/what-is-devops/)
+ [DevOps 리소스](https://aws.amazon.com/devops/resources/)

**Gitflow 지침**
+ [원본 Gitflow 블로그](https://nvie.com/posts/a-successful-git-branching-model/)(Vincent Driessen 블로그 게시물)
+ [Gitflow 워크플로](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow)(Atlassian)
+ [GitHub: GitHub 기반 리포지토리와 함께 Git Flow 워크플로를 사용하는 방법](https://youtu.be/WQuxeEvaCxs)(YouTube 비디오)
+ [Git 흐름 초기화 예시](https://www.youtube.com/watch?v=d4cDLBFbekw)(YouTube 동영상)
+ [시작부터 끝까지 Gitflow 릴리스 브랜치](https://www.youtube.com/watch?v=rX80eKPdA28)(YouTube 비디오)

**기타 리소스**

[12단계 앱 방법론](https://12factor.net/)(12factor.net)

# 다중 계정 DevOps 환경을 위한 트렁크 분기 전략 구현
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments"></a>

*Mike Stephens와 Rayjan Wilson, Amazon Web Services*

## 요약
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-summary"></a>

소스 코드 리포지토리를 관리할 때 다양한 분기 전략이 개발 팀이 사용하는 소프트웨어 개발 및 릴리스 프로세스에 영향을 미칩니다. 일반적인 분기 전략의 예로는 Trunk, GitHub Flow 및 Gitflow가 있습니다. 이러한 전략은 서로 다른 브랜치를 사용하며, 각 환경에서 수행되는 활동은 다릅니다. DevOps 프로세스를 구현하는 조직은 이러한 분기 전략 간의 차이를 이해하는 데 도움이 되는 시각적 가이드의 이점을 누릴 수 있습니다. 조직에서이 시각적 객체를 사용하면 개발 팀이 업무를 조정하고 조직 표준을 따르는 데 도움이 됩니다. 이 패턴은이 시각적 객체를 제공하고 조직에서 트렁크 분기 전략을 구현하는 프로세스를 설명합니다.

이 패턴은 여러가 있는 조직의 DevOps 분기 전략을 선택하고 구현하는 방법에 대한 설명서 시리즈의 일부입니다 AWS 계정. 이 시리즈는 처음부터 올바른 전략과 모범 사례를 적용하여 클라우드에서의 경험을 간소화하는 데 도움이 되도록 설계되었습니다. 트렁크는 조직에서 사용할 수 있는 가능한 분기 전략 중 하나일 뿐입니다. 이 설명서 시리즈에서는 [GitHub Flow](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) 및 [Gitflow](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) 분기 모델도 다룹니다. 아직 수행하지 않은 경우이 패턴의 지침을 구현하기 전에 [다중 계정 DevOps 환경에 대한 Git 분기 전략 선택을 검토하는](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/) 것이 좋습니다. 실사를 통해 조직에 적합한 분기 전략을 선택합니다.

이 가이드에서는 조직이 트렁크 전략을 구현하는 방법을 보여주는 다이어그램을 제공합니다. 공식 [AWS Well-Architected DevOps 지침을](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html) 검토하여 모범 사례를 검토하는 것이 좋습니다. 이 패턴에는 DevOps 프로세스의 각 단계에 대한 권장 작업, 단계 및 제한이 포함됩니다.

## 사전 조건 및 제한 사항
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-prereqs"></a>

**사전 조건 **
+ Git [설치](https://git-scm.com/downloads) 이는 소스 코드 리포지토리 도구로 사용됩니다.
+ Draw.io, [설치](https://github.com/jgraph/drawio-desktop/releases)됨. 이 애플리케이션은 다이어그램을 보고 편집하는 데 사용됩니다.

## 아키텍처
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**대상 아키텍처**

다음 다이어그램은 [Punnett 사각형](https://en.wikipedia.org/wiki/Punnett_square)(Wikipedia)처럼 사용할 수 있습니다. 세로 축의 브랜치를 가로 축의 AWS 환경과 정렬하여 각 시나리오에서 수행할 작업을 결정합니다. 숫자는 워크플로의 작업 순서를 나타냅니다. 이 예에서는 `feature` 브랜치에서 프로덕션 배포까지 안내합니다.

![\[각 브랜치 및 환경의 트렁크 활동의 Punnett 제곱\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/5df23e4d-84fe-4ab3-a54f-96b6406abc57/images/ad549ef4-90ad-47c1-bd01-f21d6ce5511a.png)


트렁크 접근 방식의 AWS 계정, 환경 및 브랜치에 대한 자세한 내용은 [다중 계정 DevOps 환경을 위한 Git 브랜치 전략 선택을 참조하세요](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach).

**자동화 및 규모 조정**

지속적 통합 및 지속적 제공(CI/CD)은 소프트웨어 릴리스 수명 주기를 자동화하는 프로세스입니다. 일반적으로 초기 커밋에서 프로덕션으로 새 코드를 가져오는 데 필요한 수동 프로세스의 대부분 또는 전부를 자동화합니다. CI/CD 파이프라인에는 샌드박스, 개발, 테스트, 스테이징 및 프로덕션 환경이 포함됩니다. 각 환경에서 CI/CD 파이프라인은 코드를 배포하거나 테스트하는 데 필요한 모든 인프라를 프로비저닝합니다. CI/CD를 사용하면 개발 팀이 코드를 변경하여 자동으로 테스트하고 배포할 수 있습니다. 또한 CI/CD 파이프라인은 기능 수락 및 배포에 대한 일관성, 표준, 모범 사례 및 최소 허용 수준을 적용하여 개발 팀에 거버넌스 및 가드레일을 제공합니다. 자세한 내용은 [AWS에서 지속적 통합 및 지속적 전달 연습](https://docs.aws.amazon.com/whitepapers/latest/practicing-continuous-integration-continuous-delivery/welcome.html)을 참조하세요.

AWS 는 CI/CD 파이프라인을 구축하는 데 도움이 되도록 설계된 개발자 서비스 제품군을 제공합니다. 예를 들어 [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)는 빠르고 안정적인 애플리케이션 및 인프라 업데이트를 위해 릴리스 파이프라인을 자동화하는 데 도움이 되는 완전관리형 지속적 제공 서비스입니다.는 소스 코드를 [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)컴파일하고 테스트를 실행하며 ready-to-deploy 있는 소프트웨어 패키지를 생성합니다. 자세한 내용은 [의 개발자 도구를 AWS](https://aws.amazon.com/products/developer-tools/) 참조하세요.

## 도구
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-tools"></a>

**AWS 서비스 및 도구**

AWS 는이 패턴을 구현하는 데 사용할 수 있는 개발자 서비스 제품군을 제공합니다.
+ [AWS CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html)는 확장성이 뛰어난 관리형 아티팩트 리포지토리 서비스로, 애플리케이션 개발을 위한 소프트웨어 패키지를 저장하고 공유하는 데 도움을 줍니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)는 Amazon Elastic Compute Cloud(Amazon EC2) 또는 온프레미스 인스턴스, AWS Lambda 함수 또는 Amazon Elastic Container Service(Amazon ECS) 서비스에 대한 배포를 자동화합니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.

**기타 도구**
+ [Draw.io 데스크톱](https://github.com/jgraph/drawio-desktop/releases) - 흐름도 및 다이어그램을 만들기 위한 애플리케이션입니다.
+ [Figma](https://www.figma.com/design-overview/)는 공동 작업을 위해 설계된 온라인 설계 도구입니다. 코드 리포지토리에는 Figma용 .fig 형식의 템플릿이 포함되어 있습니다.

**코드 리포지토리**

이 패턴의 다이어그램에 대한이 소스 파일은 GitHub [Git Branching Strategy for Trunk](https://github.com/awslabs/git-branching-strategies-for-multiaccount-devops/tree/main/trunk) 리포지토리에서 사용할 수 있습니다. 여기에는 PNG, draw.io 및 Figma 형식의 파일이 포함됩니다. 조직의 프로세스를 지원하도록 이러한 다이어그램을 수정할 수 있습니다.

## 모범 사례
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-best-practices"></a>

[AWS Well-Architected DevOps 지침](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html) 및 [다중 계정 DevOps 환경을 위한 Git 분기 전략 선택](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)의 모범 사례 및 권장 사항을 따릅니다. 이를 통해 Trunk 기반 개발을 효과적으로 구현하고, 협업을 촉진하고, 코드 품질을 개선하고, 개발 프로세스를 간소화할 수 있습니다.

## 에픽
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-epics"></a>

### 트렁크 워크플로 검토
<a name="reviewing-the-trunk-workflow"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 표준 트렁크 프로세스를 검토합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/implement-a-trunk-branching-strategy-for-multi-account-devops-environments.html) | DevOps 엔지니어 | 

## 문제 해결
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 브랜치 충돌 | Trunk 모델에서 발생할 수 있는 일반적인 문제는 프로덕션 환경에서 핫픽스가 발생해야 하지만 동일한 리소스가 수정되는 `feature` 브랜치에서 해당 변경이 발생해야 하는 경우입니다. 에 병합`main`할 때 상당한 충돌을 방지하려면의 변경 사항을 하위 브랜치에 자주 병합하는 것이 좋습니다`main`. | 

## 관련 리소스
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-resources"></a>

이 가이드에는 Git에 대한 교육이 포함되어 있지 않지만이 교육이 필요한 경우 인터넷에서 사용할 수 있는 고품질 리소스가 많이 있습니다. [Git 설명서](https://git-scm.com/doc) 사이트로 시작하는 것이 좋습니다.

다음 리소스는의 트렁크 분기 여정에 도움이 될 수 있습니다 AWS 클라우드.

**AWS DevOps 지침**
+ [AWS DevOps 지침](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)
+ [AWS Deployment Pipeline Reference Architecture](https://pipelines.devops.aws.dev/)
+ [DevOps란 무엇인가요?](https://aws.amazon.com/devops/what-is-devops/)
+ [DevOps 리소스](https://aws.amazon.com/devops/resources/)

**트렁크 지침**
+ [트렁크 기반 개발](https://trunkbaseddevelopment.com/)

**기타 리소스**
+ [12단계 앱 방법론](https://12factor.net/)(12factor.net)

# AWS 인프라를 배포하기 전에 중앙 집중식 사용자 지정 Checkov 스캔을 구현하여 정책을 적용합니다.
<a name="centralized-custom-checkov-scanning"></a>

*Benjamin Morris, Amazon Web Services*

## 요약
<a name="centralized-custom-checkov-scanning-summary"></a>

이 패턴은 GitHub 조직 전체에서 재사용할 수 있는 사용자 지정 Checkov 정책을 하나의 리포지토리에 작성하기 위한 GitHub Actions 프레임워크를 제공합니다. 이 패턴을 따르면 정보 보안 팀이 회사 요구 사항에 따라 사용자 지정 정책을 작성, 추가 및 유지할 수 있습니다. 사용자 지정 정책은 GitHub 조직의 모든 파이프라인으로 자동으로 가져올 수 있습니다. 이 접근 방식은 리소스를 배포하기 전에 리소스에 대한 회사 표준을 적용하는 데 사용할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="centralized-custom-checkov-scanning-prereqs"></a>

**사전 조건**
+ 활성 AWS 계정
+ GitHub Actions를 사용하는 GitHub 조직
+ AWS HashiCorp Terraform 또는 로 배포된 인프라 AWS CloudFormation

**제한 사항**
+ 이 패턴은 GitHub Actions용으로 작성되었습니다. 하지만 GitLab과 같은 유사한 지속적 통합 및 지속적 전달(CI/CD) 프레임워크에 맞게 조정할 수 있습니다. GitHub의 특정 유료 버전은 필요하지 않습니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 AWS 설명서의 [서비스 엔드포인트 및 할당량을](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html) 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="centralized-custom-checkov-scanning-architecture"></a>

이 패턴은 GitHub 재사용 가능한 워크플로와 사용자 지정 Checkov 정책이 포함된 GitHub 리포지토리로 배포되도록 설계되었습니다. 재사용 가능한 워크플로는 Terraform 및 CloudFormation 코드형 인프라(IaC) 리포지토리를 모두 스캔할 수 있습니다.

다음 다이어그램은 **재사용 가능한 GitHub 워크플로 리포지토리**와 **사용자 지정 Checkov 정책 리포지토리**를 별도의 아이콘으로 보여줍니다. 하지만 이들 리포지토리는 별도의 리포지토리 또는 단일 리포지토리로 구현할 수 있습니다. 이 코드 예는 워크플로용 파일(`.github/workflows`)과 동일한 리포지토리의 사용자 지정 정책용 파일(`custom_policies` 폴더 및 `.checkov.yml` 구성 파일)과 함께 단일 리포지토리를 사용합니다.

![\[GitHub Actions는 재사용 가능한 GitHub 워크플로와 사용자 지정 Checkov 정책을 사용하여 IaC를 평가합니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/6c0c941f-14f9-4569-92da-9f81ab3e525c/images/a1539ce5-0ee6-4af1-bd01-cafad0f71708.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 사용자가 GitHub 리포지토리에서 풀 요청을 생성합니다.

1. 파이프라인 워크플로는 Checkov 재사용 가능한 워크플로에 대한 참조를 포함하여 GitHub Actions에서 시작됩니다.

1. 파이프라인 워크플로가 외부 리포지토리에서 참조된 Checkov 재사용 가능한 워크플로를 다운로드하고 GitHub Actions를 사용하여 해당 Checkov 워크플로를 실행합니다.

1. Checkov 재사용 가능한 워크플로는 외부 리포지토리에서 사용자 지정 정책을 다운로드합니다.

1. Checkov 재사용 가능 워크플로는 내장 및 사용자 지정 Checkov 정책을 모두 기준으로 GitHub 리포지토리의 IaC를 평가합니다. Checkov 재사용 가능한 워크플로는 보안 문제가 있는지 여부에 따라 통과하거나 실패합니다.

**자동화 및 규모 조정**

이 패턴을 사용하면 Checkov 구성을 중앙에서 관리할 수 있으므로, 정책 업데이트를 한 위치에 적용할 수 있습니다. 단, 이 패턴을 사용하려면 각 리포지토리가 재사용 가능한 중앙 워크플로에 대한 참조가 포함된 워크플로를 사용해야 합니다. 이 참조를 수동으로 추가하거나 스크립트를 사용하여 파일을 각 리포지토리의 `.github/workflows` 폴더로 푸시할 수 있습니다.

## 도구
<a name="centralized-custom-checkov-scanning-tools"></a>

**AWS 서비스**
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, AWS 계정 및 리전의 수명 주기 동안 리소스를 관리할 수 있습니다. Checkov는 CloudFormation을 스캔할 수 있습니다.

**기타 도구**
+ [Checkov](https://www.checkov.io/)는 IaC의 보안 및 규정 준수 구성 오류를 확인하는 정적 코드 분석 도구입니다.
+ [GitHub Actions](https://github.com/features/actions)는 GitHub 플랫폼에 통합되어 GitHub 리포지토리 내에서 워크플로를 생성, 공유 및 실행하도록 지원합니다. GitHub Actions를 사용하여 코드 빌드, 테스트 및 배포와 같은 작업을 자동화할 수 있습니다.
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 IaC 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다. Checkov는 Terraform을 스캔할 수 있습니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [centralized-custom-checkov-sast](https://github.com/aws-samples/centralized-custom-checkov-sast) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="centralized-custom-checkov-scanning-best-practices"></a>
+ 일관된 보안 태세를 유지하려면 회사의 보안 정책을 Checkov 정책에 따라 조정합니다.
+ Checkov 사용자 지정 정책을 구현하는 초기 단계에서 Checkov 스캔의 소프트 실패 옵션을 사용하여 보안 문제가 있는 IaC를 병합할 수 있습니다. 프로세스가 성숙해지면 소프트 실패 옵션에서 하드 실패 옵션으로 전환합니다.

## 에픽
<a name="centralized-custom-checkov-scanning-epics"></a>

### 사용자 지정 정책을 위한 중앙 Checkov 리포지토리 생성
<a name="create-a-central-checkov-repository-for-custom-policies"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 중앙 Checkov 리포지토리를 생성합니다. | 조직 내에서 사용할 사용자 지정 Checkov 정책을 저장할 리포지토리를 생성합니다.빠른 시작을 위해 이 패턴의 GitHub [centralized-custom-checkov-sast ](https://github.com/aws-samples/centralized-custom-checkov-sast)리포지토리의 내용을 중앙 Checkov 리포지토리에 복사할 수 있습니다. | DevOps 엔지니어 | 
| 재사용 가능한 워크플로를 위한 리포지토리를 생성합니다. | 재사용 가능한 워크플로에 대한 리포지토리가 이미 있거나 사용자 지정 Checkov 정책과 동일한 리포지토리에 재사용 가능한 워크플로 파일을 포함하려는 경우 이 단계를 건너뛸 수 있습니다.재사용 가능한 워크플로를 보관할 GitHub 리포지토리를 생성합니다. 다른 리포지토리의 파이프라인은 이 리포지토리를 참조합니다. | DevOps 엔지니어 | 

### 재사용 가능한 예시 Checkov 워크플로 생성
<a name="create-reusable-and-example-checkov-workflows"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 재사용 가능한 Checkov 워크플로를 추가합니다. | 재사용 가능한 워크플로 리포지토리에서 재사용 가능한 Checkov GitHub Actions 워크플로(YAML 파일)를 생성합니다. 이 패턴에 제공된 워크플로 파일에서 재사용 가능한 워크플로를 조정할 수 있습니다.대표적인 변경 사항의 예는 소프트 실패 옵션을 사용하도록 재사용 가능한 워크플로를 변경하는 것입니다. `soft-fail`을 `true`로 설정하면 Checkov 스캔에 실패한 경우에도 작업이 성공적으로 완료될 수 있습니다. 지침은 Checkov 설명서의 [하드 및 소프트 실패](https://www.checkov.io/2.Basics/Hard%20and%20soft%20fail.html)를 참조하세요. | DevOps 엔지니어 | 
| 워크플로 예시를 추가합니다. | `reusable` 워크플로를 참조하는 예사 Checkov 워크플로를 추가합니다. 그러면 `reusable` 워크플로를 재사용하는 방법에 대한 템플릿이 제공됩니다. 예제 리포지토리에서 `checkov-source.yaml`는 재사용 가능한 워크플로이고 `checkov-scan.yaml`는 `checkov-source`를 사용하는 예입니다.예제 Checkov 워크플로 작성에 대한 자세한 내용은 [추가 정보](#centralized-custom-checkov-scanning-additional)를 참조하세요. | DevOps 엔지니어 | 

### 회사 정책을 Checkov 사용자 지정 정책에 연결
<a name="associate-company-policies-to-checkov-custom-policies"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Checkov로 적용할 수 있는 정책을 결정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/centralized-custom-checkov-scanning.html)Checkov 사용자 지정 정책 생성에 대한 자세한 내용은 Checkov 설명서의 [사용자 지정 정책 개요](https://www.checkov.io/3.Custom%20Policies/Custom%20Policies%20Overview.html)를 참조하세요. | 보안 및 규정 준수 | 
| Checkov 사용자 지정 정책을 추가합니다. | 식별된 회사 정책을 중앙 리포지토리의 사용자 지정 Checkov 정책으로 변환합니다. Python 또는 YAML에서 간단한 Checkov 정책을 작성할 수 있습니다. | 보안 | 

### 중앙 집중식 Checkov 사용자 지정 정책 구현
<a name="implement-centralized-checkov-custom-policies"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Checkov 재사용 가능 워크플로를 모든 리포지토리에 추가합니다. | 이때 재사용 가능 워크플로를 참조하는 Checkov 워크플로 예시가 있어야 합니다. 재사용 가능 워크플로를 참조하는 샘플 Checkov 워크플로를 필요한 각 리포지토리에 복사합니다. | DevOps 엔지니어 | 
| 병합 전에, Checkov가 실행되도록 하는 메커니즘을 생성합니다. | 모든 풀 요청에 대해 Checkov 워크플로가 실행되도록 하려면 풀 요청을 병합하기 전에 성공적인 Checkov 워크플로가 필요한 [상태 확인](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/about-status-checks)을 생성합니다. GitHub를 사용하면 풀 요청을 병합하기 전에 특정 워크플로를 실행하도록 요구할 수 있습니다. | DevOps 엔지니어 | 
| 조직 전체의 PAT를 생성하고 시크릿으로 공유합니다. | GitHub 조직이 공개적으로 표시되는 경우 이 단계를 건너뛸 수 있습니다.이 패턴을 사용하려면 Checkov 워크플로가 GitHub 조직의 사용자 지정 정책 리포지토리에서 사용자 지정 정책을 다운로드할 수 있어야 합니다. Checkov 워크플로가 해당 리포지토리에 액세스할 수 있도록 권한을 제공해야 합니다.이렇게 하려면 조직 리포지토리를 읽을 수 있는 권한이 있는 [개인 액세스 토큰(PAT)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token)을 생성합니다. 이 PAT를 조직 전체의 시크릿(유료 플랜의 경우) 또는 각 리포지토리의 보안 암호(무료 버전)로 리포지토리와 공유합니다. 샘플 코드에서 보안 암호의 기본 이름은 `ORG_PAT`입니다. | DevOps 엔지니어 | 
| (선택 사항) Checkov 워크플로 파일이 수정되지 않도록 보호합니다. | Checkov 워크플로 파일을 원치 않는 변경으로부터 보호하려면 `CODEOWNERS` 파일을 사용하면 됩니다. `CODEOWNERS` 파일은 일반적으로 디렉터리의 루트에 배포됩니다.예를 들어 `checkov-scan.yaml` 파일을 수정할 때 GitHub 조직의 `secEng` 그룹에 승인을 요구하려면 리포지토리의 `CODEOWNERS` 파일에 다음을 추가합니다.<pre>[Checkov]<br />.github/workflows/checkov-scan.yaml @myOrg/secEng</pre>`CODEOWNERS` 파일은 파일이 있는 리포지토리에 고유합니다. 리포지토리에서 사용하는 Checkov 워크플로를 보호하려면 각 리포지토리에 `CODEOWNERS` 파일을 추가(또는 업데이트)해야 합니다.Checkov 워크플로 파일 보호에 대한 자세한 내용은 [추가 정보](#centralized-custom-checkov-scanning-additional)를 참조하세요. `CODEOWNERS` 파일에 대한 자세한 내용은 CI/CD 공급자의 공식 설명서(예: [GitHub](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners))를 참조하세요. | DevOps 엔지니어 | 

## 관련 리소스
<a name="centralized-custom-checkov-scanning-resources"></a>
+ [Checkov 사용자 지정 정책 개요](https://www.checkov.io/3.Custom%20Policies/Custom%20Policies%20Overview.html)
+ [CloudFormation 구성 스캔](https://www.checkov.io/7.Scan%20Examples/Cloudformation.html)
+ [GitHub 작업 재사용 가능한 워크플로](https://docs.github.com/en/actions/using-workflows/reusing-workflows)

## 추가 정보
<a name="centralized-custom-checkov-scanning-additional"></a>

**Checkov 워크플로 파일 작성**

`checkov-scan.yaml`을 작성할 때는 언제 실행할지 고려합니다. 최상위 `on` 키는 워크플로 실행 시기를 결정합니다. 예제 리포지토리에서 워크플로는 `main` 브랜치를 대상으로 하는 풀 요청이 있을 때(및 풀 요청의 소스 브랜치가 수정될 때마다) 실행됩니다. `workflow_dispatch` 키로 인해 필요에 따라 워크플로를 실행할 수도 있습니다.

워크플로를 실행할 빈도에 따라 워크플로 트리거 조건을 변경할 수 있습니다. 예를 들어를 `pull_request`를 `push`로 바꾸고 `branches` 키를 제거하여 코드가 브랜치로 푸시될 때마다 실행되도록 워크플로를 변경할 수 있습니다.

개별 리포지토리 내에서 생성한 예시 워크플로 파일을 수정할 수 있습니다. 예를 들어 리포지토리가 `production` 브랜치를 중심으로 구조화된 경우 대상 브랜치의 이름을 `main`에서 `production`로 조정할 수 있습니다.

**Checkov 워크플로 파일 보호**

Checkov 스캔은 잠재적인 보안 구성 오류에 대한 유용한 정보를 제공합니다. 하지만 일부 개발자는 이를 생산성의 장벽으로 인식하고 스캔 워크플로를 제거하거나 비활성화하려고 할 수 있습니다.

이 문제를 해결할 방법에는 보안 스캔의 장기 가치에 대한 더 나은 메시징과 보안 인프라를 배포하는 방법에 대한 더 명확한 설명서 등 여러 가지가 있습니다. 이는 이 문제의 근본 원인에 대한 솔루션으로 볼 수 있는 DevSecOps 협업에 대한 중요한 ‘소프트’ 접근 방식입니다. 그러나 `CODEOWNERS` 파일과 같은 기술 제어를 가드레일로 사용하여 개발자를 올바른 경로로 유지할 수도 있습니다.

**샌드박스에서 패턴 테스트**

샌드박스 환경에서 이 패턴을 테스트하려면 다음 단계를 따릅니다.

1. 새 GitHub 조직을 생성합니다. 조직의 모든 리포지토리에 대한 읽기 전용 액세스 권한이 있는 토큰을 생성합니다. 이 토큰은 유료 환경이 아닌 샌드박스 환경을 위한 것이므로 이 토큰을 조직 전체의 보안 암호에 저장할 수 없습니다.

1. Checkov 구성을 보관할 `checkov` 리포지토리와 재사용 가능한 워크플로 구성을 보관할 `github-workflows` 리포지토리를 생성합니다. 리포지토리를 예시 리포지토리의 콘텐츠로 채웁니다.

1. 애플리케이션 리포지토리를 생성하고 `checkov-scan.yaml` 워크플로를 복사하여 `.github/workflows` 폴더에 붙여 넣습니다. 조직 읽기 전용 액세스를 위해 생성한 PAT가 포함된 시크릿을 리포지토리에 추가합니다. 기본 보안 암호는 `ORG_PAT`입니다.

1. 애플리케이션 리포지토리에 Terraform 또는 CloudFormation 코드를 추가하는 풀 요청을 생성합니다. Checkov는 결과를 스캔하여 반환해야 합니다.

# K8sGPT 및 Amazon Bedrock 통합을 사용하여 AI 기반 Kubernetes 진단 및 문제 해결 구현
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration"></a>

*Ishwar Chauthaiwale, Muskan . 및 Prafful Gupta, Amazon Web Services*

## 요약
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-summary"></a>

이 패턴은 K8sGPT를 Amazon Bedrock에서 사용할 수 있는 Anthropic Claude v2 모델과 통합하여 AI 기반 Kubernetes 진단 및 문제 해결을 구현하는 방법을 보여줍니다. 이 솔루션은 안전한 접속 호스트 아키텍처를 통해 Kubernetes 클러스터 문제에 대한 자연어 분석 및 수정 단계를 제공합니다. K8sGPT Kubernetes 전문 지식과 Amazon Bedrock 고급 언어 기능을 결합하여 DevOps 팀은 클러스터 문제를 신속하게 식별하고 해결할 수 있습니다. 이러한 기능을 사용하면 평균 해결 시간(MTTR)을 최대 50% 줄일 수 있습니다.

이 클라우드 네이티브 패턴에서는 Kubernetes 관리에 Amazon Elastic Kubernetes Service(Amazon EKS)를 사용합니다. 이 패턴은 적절한 AWS Identity and Access Management (IAM) 역할 및 네트워크 격리를 통해 보안 모범 사례를 구현합니다. 이 솔루션은 Kubernetes 운영을 간소화하고 AI 지원을 통해 문제 해결 기능을 개선하려는 조직에 특히 유용합니다.

## 사전 조건 및 제한 사항
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-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)됨
+ Amazon EKS 클러스터
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)에서 Anthropic Claude 2 모델에 대한 액세스
+ 필수 보안 그룹 설정이 있는 접속 호스트
+ K8sGPT [설치](https://docs.k8sgpt.ai/getting-started/installation/)됨

**제한 사항 **
+ K8sGPT 분석은 Claude v2 모델의 컨텍스트 창 크기에 따라 제한됩니다.
+ Amazon Bedrock API 속도 제한은 계정 할당량에 따라 적용됩니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

**제품 버전**
+ Amazon EKS [버전 1.31 이상](https://docs.aws.amazon.com/eks/latest/userguide/kubernetes-versions.html)
+ Amazon Bedrock의 [Claude 2 모델](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html) 
+ K8sGPT [v0.4.2 이상](https://github.com/k8sgpt-ai/k8sgpt/releases)

## 아키텍처
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-architecture"></a>

다음 다이어그램은에서 Amazon Bedrock과 통합된 K8sGPT를 사용하는 AI 기반 Kubernetes 진단 아키텍처를 보여줍니다 AWS 클라우드.

![\[Amazon Bedrock과 통합된 K8sGPT를 사용한 Kubernetes 진단용 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/09bc08f6-e191-4cef-b26b-dcb6225b15cc/images/8789891d-4a90-44b0-a108-387f6d96496b.png)


이 아키텍처는 다음 워크플로를 보여줍니다.

1. 개발자는 접속 호스트에 대한 보안 연결을 통해 환경에 액세스합니다. 이 Amazon EC2 인스턴스는 보안 진입점 역할을 하며 K8sGPT 명령줄 인터페이스(CLI) 설치 및 필수 구성을 포함합니다.

1. 특정 IAM 역할로 구성된 접속 호스트는 Amazon EKS 클러스터와 Amazon Bedrock 엔드포인트 모두에 대한 보안 연결을 설정합니다. K8sGPT는 Kubernetes 클러스터 분석을 수행하기 위해 접속 호스트에 설치 및 구성됩니다.

1. Amazon EKS는 Kubernetes 컨트롤 플레인 및 작업자 노드를 관리하여 K8sGPT 분석을 위한 대상 환경을 제공합니다. 이 서비스는 Virtual Private Cloud(VPC) 내의 여러 가용 영역에서 실행되므로 고가용성과 복원력을 제공하는 데 도움이 됩니다. Amazon EKS는 Kubernetes API를 통해 운영 데이터를 제공하므로 포괄적인 클러스터 분석이 가능합니다.

1. K8sGPT는 자연어 처리를 위한 Claude v2 파운데이션 모델(FM)을 제공하는 Amazon Bedrock으로 분석 데이터를 전송합니다. 이 서비스는 K8sGPT 분석을 처리하여 사람이 읽을 수 있는 설명을 생성하고 식별된 문제를 기반으로 자세한 문제 해결 제안을 제공합니다. Amazon Bedrock은 고가용성과 확장성을 갖춘 서버리스 AI 서비스로 운영됩니다.

**참고**  
이 워크플로 전체에서 IAM은 역할 및 정책을 통해 구성 요소 간의 액세스를 제어하여 접속 호스트, Amazon EKS 및 Amazon Bedrock 상호 작용에 대한 인증을 관리합니다. IAM은 최소 권한 원칙을 구현하고 아키텍처 전체에서 안전한 서비스 간 통신을 지원합니다.

**자동화 및 규모 조정**

K8sGPT 작업은 다양한 AWS 서비스 및 도구를 통해 여러 Amazon EKS 클러스터에서 자동화하고 확장할 수 있습니다. 이 솔루션은 예약된 분석을 [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 위해 [Jenkins](https://www.jenkins.io/), [GitHub Actions](https://docs.github.com/en/actions/get-started/understand-github-actions) 또는를 사용한 지속적 통합 및 지속적 배포(CI/CD) 통합을 지원합니다. K8sGPT 연산자를 사용하면 자동화된 문제 감지 및 보고 기능을 통해 클러스터 내 모니터링을 지속적으로 수행할 수 있습니다. 엔터프라이즈급 배포의 경우 [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)를 사용하여 사용자 지정 스크립트로 스캔을 예약하고 자동 응답을 트리거할 수 있습니다. AWS SDK 통합을 통해 대규모 클러스터 플릿에서 프로그래밍 방식으로 제어할 수 있습니다.

## 도구
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-tools"></a>

**서비스**
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 셸의 명령을 AWS 서비스 통해와 상호 작용하는 데 도움이 되는 오픈 소스 도구입니다.
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)를 사용하면 자체 Kubernetes 컨트롤 플레인 또는 노드를 설치하거나 유지 관리할 필요 AWS 없이에서 Kubernetes를 실행할 수 있습니다.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 액세스를 인증하고 사용할 수 있는 권한을 부여받은 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다.

**기타 도구**
+ [K8sGPT](https://k8sgpt.ai/)는 Kubernetes 관리를 변환하는 오픈 소스 AI 기반 도구입니다. 가상 사이트 신뢰성 엔지니어링(SRE) 전문가 역할을 하여 Kubernetes 클러스터 문제를 자동으로 스캔, 진단 및 해결합니다. 관리자는 자연어를 사용하여 K8sGPT와 상호 작용하고 클러스터 상태, 포드 충돌 및 서비스 장애에 대한 명확하고 실행 가능한 인사이트를 얻을 수 있습니다. 도구의 내장 분석기는 잘못 구성된 구성 요소부터 리소스 제약 조건에 이르기까지 다양한 문제를 감지하고 easy-to-understand 설명과 솔루션을 제공합니다.

## 모범 사례
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-best-practices"></a>
+ [접속 호스트 액세스에를 사용하여 보안 액세스](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html) 제어를 구현 AWS Systems Manager Session Manager 합니다.
+ K8sGPT 인증이 Amazon Bedrock 및 Amazon EKS 상호 작용에 대한 최소 권한 권한이 있는 전용 IAM 역할을 사용하는지 확인합니다. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv) 및 [보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)를 참조하세요.
+ [리소스 태깅](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/what-are-tags.html)을 구성하고, [감사 추적에 대해 Amazon CloudWatch 로깅](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html)을 활성화하고, 민감한 정보에 대한 [데이터 익명화](https://aws.amazon.com/solutions/guidance/data-anonymization-on-aws/)를 구현합니다.
+ 사용량이 적은 시간에 자동 스캔 일정을 설정하여 운영 영향을 최소화하면서 K8sGPT 구성을 정기적으로 백업합니다.

## 에픽
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-epics"></a>

### AI 백엔드 공급자 목록에 Amazon Bedrock을 추가합니다.
<a name="add-br-to-ai-backend-provider-list"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon Bedrock을 K8sGPT의 AI 백엔드 공급자로 설정합니다. | Amazon Bedrock을 K8sGPT용 AI [백엔드 제공](https://docs.k8sgpt.ai/reference/providers/backend/) r로 설정하려면 다음 AWS CLI 명령을 사용합니다.<pre>k8sgpt auth add -b amazonbedrock \<br /> -r us-west-2 \<br /> -m anthropic.claude-v2 \<br /> -n endpoint-name <br /></pre>예시 명령은 AWS 리전으로 `us-west-2`를 사용합니다. 그러나 Amazon EKS 클러스터와 해당 Amazon Bedrock 모델을 모두 선택한 리전에서 사용할 수 있고 활성화되어 있는 경우 다른 리전을 선택할 수 있습니다.`amazonbedrock`이 AI 백엔드 공급자 목록에 추가되고 `Active` 상태인지 확인하려면 다음 명령을 실행합니다.<pre>k8sgpt auth list</pre>다음은 이 명령의 예상 출력의 예입니다.<pre>Default: <br />> openai<br />Active: <br />> amazonbedrock<br />Unused: <br />> openai<br />> localai<br />> ollama<br />> azureopenai<br />> cohere<br />> amazonsagemaker<br />> google<br />> noopai<br />> huggingface<br />> googlevertexai<br />> oci<br />> customrest<br />> ibmwatsonxai</pre> | DevOps | 

### 필터를 사용하여 리소스 스캔
<a name="scan-resources-using-a-filter"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 사용 가능한 필터 목록을 봅니다. | 사용 가능한 모든 필터 목록을 보려면 다음 AWS CLI 명령을 사용합니다.<pre>k8sgpt filters list</pre>다음은 이 명령의 예상 출력의 예입니다.<pre>Active: <br />> Deployment<br />> ReplicaSet<br />> PersistentVolumeClaim<br />> Service<br />> CronJob<br />> Node<br />> MutatingWebhookConfiguration<br />> Pod<br />> Ingress<br />> StatefulSet<br />> ValidatingWebhookConfiguration</pre> | DevOps | 
| 필터를 사용하여 특정 네임스페이스에서 포드를 스캔합니다. | 이 명령은 Amazon Bedrock AI 기능을 사용하여 발견한 문제를 분석하고 설명함으로써 Kubernetes 클러스터 내의 특정 포드 문제를 대상으로 디버깅하는 데 유용합니다.필터를 사용하여 특정 네임스페이스의 포드를 스캔하려면 다음 AWS CLI 명령을 사용합니다.<pre>k8sgpt analyze --backend amazonbedrock --explain --filter Pod -n default</pre>다음은 이 명령의 예상 출력의 예입니다.<pre>100% |████████████████████████████████████████████████████████| (1/1, 645 it/s)        <br />AI Provider: amazonbedrock<br /><br />0: Pod default/crashme()<br />- Error: the last termination reason is Error container=crashme pod=crashme<br />Error: The pod named crashme terminated because the container named crashme crashed.<br />Solution: Check logs for crashme pod to identify reason for crash. Restart pod or redeploy application to resolve crash.</pre> | DevOps | 
| 필터를 사용하여 특정 네임스페이스에서 배포를 스캔합니다. | 이 명령은 특히 실제 상태가 원하는 상태와 일치하지 않는 경우 배포별 문제를 식별하고 해결하는 데 유용합니다.필터를 사용하여 특정 네임스페이스에서 배포를 스캔하려면 다음 AWS CLI 명령을 사용합니다.<pre>k8sgpt analyze --backend amazonbedrock --explain --filter Deployment -n default</pre>다음은 이 명령의 예상 출력의 예입니다.<pre>100% |██████████████████████████████████████████████████████████| (1/1, 10 it/min)        <br />AI Provider: amazonbedrock<br /><br />0: Deployment default/nginx()<br />- Error: Deployment default/nginx has 1 replicas but 2 are available<br /> Error: The Deployment named nginx in the default namespace has 1 replica specified but 2 pod replicas are running.<br />Solution: Check if any other controllers like ReplicaSet or StatefulSet have created extra pods. Delete extra pods or adjust replica count to match available pods.</pre> | DevOps | 
| 필터를 사용하여 특정 네임스페이스의 노드를 스캔합니다. | 필터를 사용하여 특정 네임스페이스의 노드를 스캔하려면 다음 AWS CLI 명령을 사용합니다.<pre>k8sgpt analyze --backend amazonbedrock --explain --filter Node -n default </pre>다음은 이 명령의 예상 출력의 예입니다.<pre>AI Provider: amazonbedrock<br /><br />No problems detected</pre> | DevOps | 

### 세부 출력 분석
<a name="analyze-detailed-outputs"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 자세한 출력을 가져옵니다. |  세부 출력을 가져오려면 다음 AWS CLI 명령을 사용합니다.<pre>k8sgpt analyze --backend amazonbedrock --explain --ouput json</pre>다음은 이 명령의 예상 출력의 예입니다.<pre>{<br />  "provider": "amazonbedrock",<br />  "errors": null,<br />  "status": "ProblemDetected",<br />  "problems": 1,<br />  "results": [<br />    {<br />      "kind": "Pod",<br />      "name": "default/crashme",<br />      "error": [<br />        {<br />          "Text": "the last termination reason is Error container=crashme pod=crashme",<br />          "KubernetesDoc": "",<br />          "Sensitive": []<br />        }<br />      ],<br />      "details": " Error: The pod named crashme terminated because the container named crashme crashed.\nSolution: Check logs for crashme pod to identify reason for crash. Restart pod or redeploy application to resolve crash.",<br />      "parentObject": ""<br />    }<br />  ]<br />}</pre> | DevOps | 
| 문제가 있는 포드를 확인합니다. | 특정 문제가 있는 포드를 확인하려면 다음 AWS CLI 명령을 사용합니다.<pre>kubectl get pods --all-namespaces | grep -v Running</pre>다음은 이 명령의 예상 출력의 예입니다.<pre>NAMESPACE    NAME      READY    STATUS          RESTARTS      AGE                                       <br />default     crashme     0/1   CrashLoopBackOff   260(91s ago)   21h</pre> | DevOps | 
| 애플리케이션별 인사이트를 얻습니다. | 이 명령은 다음과 같은 경우에 특히 유용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration.html)애플리케이션별 인사이트를 얻으려면 다음 명령을 사용합니다.<pre>k8sgpt analyze --backend amazonbedrock --explain -L app=nginx -n default</pre>다음은 이 명령의 예상 출력의 예입니다.<pre>AI Provider: amazonbedrock<br /><br />No problems detected</pre> |  | 

## 관련 리소스
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-resources"></a>

**AWS Blog**
+ [Amazon Bedrock 에이전트 워크플로를 사용하여 Amazon EKS 문제 해결 자동화](https://aws.amazon.com/blogs/machine-learning/automate-amazon-eks-troubleshooting-using-an-amazon-bedrock-agentic-workflow/)
+ [K8sGPT 및 Amazon Bedrock을 사용하여 Kubernetes 클러스터 유지 관리 간소화](https://aws.amazon.com/blogs/machine-learning/use-k8sgpt-and-amazon-bedrock-for-simplified-kubernetes-cluster-maintenance/)

**AWS 설명서**
+ AWS CLI 명령: [create-cluster](https://docs.aws.amazon.com/cli/latest/reference/eks/create-cluster.html) 및 [describe-cluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-cluster.html)
+ [Amazon EKS 시작하기](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)(Amazon EKS 설명서)
+ [IAM의 보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)(IAM 설명서)

**기타 리소스**
+ [K8sGPT](https://k8sgpt.ai/)

# CodeCommit의 모노리포지토리에 대한 변경 사항 자동 감지 및 다양한 CodePipeline 파이프라인 시작
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit"></a>

*Helton Ribeiro, Petrus Batalha, Ricardo Morais, Amazon Web Services*

## 요약
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-summary"></a>

**알림**: AWS Cloud9 신규 고객은 더 이상를 사용할 수 없습니다. 의 기존 고객은 평소와 같이 서비스를 계속 사용할 AWS Cloud9 수 있습니다. [자세히 알아보기](https://aws.amazon.com/blogs/devops/how-to-migrate-from-aws-cloud9-to-aws-ide-toolkits-or-aws-cloudshell/)

이 패턴을 사용하면에서 모노 리포지토리 기반 애플리케이션의 소스 코드에 대한 변경 사항을 자동으로 감지 AWS CodeCommit 한 다음 각 마이크로서비스에 대해 지속적 통합 및 지속적 전달(CI/CD) 자동화를 AWS CodePipeline 실행하는 파이프라인을에서 시작할 수 있습니다. 이 접근 방식은 모노리포지토리 기반 애플리케이션의 각 마이크로서비스가 전용 CI/CD 파이프라인을 가질 수 있다는 것을 의미하며, 이를 통해 가시성을 높이고, 코드를 더 쉽게 공유하고, 협업, 표준화 및 검색 가능성을 개선할 수 있습니다.

이 패턴에 설명된 솔루션은 모노 리포지토리 내의 마이크로서비스 간에 종속성 분석을 수행하지 않습니다. 소스 코드의 변경 사항만 감지하고 일치하는 CI/CD 파이프라인을 시작합니다.

이 패턴은를 통합 개발 환경(IDE) AWS Cloud9 으로 사용하고 AWS Cloud Development Kit (AWS CDK) 를 사용하여 `MonoRepoStack` 및의 두 CloudFormation 스택을 사용하여 인프라를 정의합니다`PipelinesStack`. `MonoRepoStack` 스택은에 모노레포 AWS CodeCommit 와 CI/CD 파이프라인을 시작하는 AWS Lambda 함수를 생성합니다. `PipelinesStack` 스택은 파이프라인 인프라를 정의합니다.

**중요**  
이 패턴의 워크플로는 개념 증명(PoC)입니다. 테스트 환경에서만 사용하는 것이 좋습니다. 프로덕션 환경에서이 패턴의 접근 방식을 사용하려면 AWS Identity and Access Management (IAM) 설명서[의 IAM의 보안 모범 사례를](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) 참조하고 IAM 역할 및를 필요한 대로 변경합니다 AWS 서비스. 

## 사전 조건 및 제한 사항
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정.
+ AWS Command Line Interface (AWS CLI), 설치 및 구성됨. 자세한 내용은 AWS CLI 설명서[AWS CLI의 설치, 업데이트 및 제거](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)를 참조하세요. 
+ Python 3 및 `pip` 로컬 머신에 설치. 자세한 내용은 [Python 설명서](https://www.python.org/)를 참조하세요. 
+ AWS CDK설치 및 구성 자세한 내용은 AWS CDK 설명서[의 시작하기 AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)를 참조하세요. 
+ 설치 및 구성된 AWS Cloud9 IDE입니다. 자세한 내용은 AWS Cloud9 설명서의 [설정을 AWS Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/setting-up.html) 참조하세요. 
+ GitHub [AWS CodeCommit 모노리포지토리 다중 파이프라인은 로컬 시스템에 복제된 리포지토리를 트리거합니다](https://github.com/aws-samples/monorepo-multi-pipeline-trigger). 
+ CodePipeline으로 빌드하고 배포하려는 애플리케이션 코드가 들어 있는 기존 디렉터리.
+  AWS 클라우드의 DevOps 모범 사례 숙지 및 경험 DevOps에 대한 친숙도를 높이려면 AWS 권장 가이드 웹 사이트에서 [ DevOps 사례를 사용하여 마이크로서비스와 느슨하게 결합된 아키텍처 구축 AWS Cloud9](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/build-a-loosely-coupled-architecture-with-microservices-using-devops-practices-and-aws-cloud9.html) 패턴을 사용할 수 있습니다. 

## 아키텍처
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-architecture"></a>

다음 다이어그램은 AWS CDK 를 사용하여 `MonoRepoStack` 및 라는 두 개의 AWS CloudFormation 스택이 있는 인프라를 정의하는 방법을 보여줍니다`PipelinesStack`.

![\[AWS CDK를 사용하여 두 개의 CloudFormation 스택이 있는 인프라를 정의하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/a3397158-a208-4033-844e-969af13ae8b6/images/b0bb1094-b598-4b3d-ab8b-ad9b0eb45f38.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 부트스트랩 프로세스는 AWS CDK 를 사용하여 AWS CloudFormation 스택 `MonoRepoStack` 및를 생성합니다`PipelinesStack`.

1. `MonoRepoStack` 스택은 애플리케이션과 각 커밋 후에 시작되는 `monorepo-event-handler` Lambda 함수를 위한 CodeCommit 리포지토리를 생성합니다.

1. `PipelinesStack` 스택은 Lambda 함수에 의해 시작되는 파이프라인을 CodePipeline에 생성합니다. 각 마이크로서비스에는 정의된 인프라 파이프라인이 있어야 합니다.

1. `microservice-n`의 파이프라인은 Lambda 함수에 의해 시작되고 CodeCommit의 소스 코드를 기반으로 하는 격리된 CI/CD 단계를 시작합니다.

1. `microservice-1`의 파이프라인은 Lambda 함수에 의해 시작되고 CodeCommit의 소스 코드를 기반으로 하는 격리된 CI/CD 단계를 시작합니다.

다음 다이어그램은 계정에 AWS CloudFormation 스택 `MonoRepoStack` 및를 배포`PipelinesStack`하는 방법을 보여줍니다.

![\[AWS 계정에 CloudFormation 스택 MonoRepoStack 및 PipelinesStack 배포.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/a3397158-a208-4033-844e-969af13ae8b6/images/39e60e49-dea2-486d-8a2c-6cae438f69b4.png)


1. 사용자가 애플리케이션의 마이크로서비스 중 하나에서 코드를 변경합니다.

1. 사용자가 로컬 리포지토리에서 CodeCommit 리포지토리로 변경 내용을 푸시합니다.

1. 푸시 활동은 CodeCommit 리포지토리에 대한 모든 푸시를 수신하는 Lambda 함수를 시작합니다.

1. 이 Lambda 함수는 AWS Systems Manager의 기능인 Parameter Store에서 파라미터를 읽고 가장 최근의 커밋 ID를 검색합니다. 파라미터는 `/MonoRepoTrigger/{repository}/{branch_name}/LastCommit` 명명 형식을 사용합니다. 파라미터를 찾을 수 없는 경우 Lambda 함수는 CodeCommit 리포지토리에서 마지막 커밋 ID를 읽고 반환된 값을 파라미터 스토어에 저장합니다.

1. Lambda 함수는 커밋 ID와 변경된 파일을 식별한 후 각 마이크로서비스 디렉터리의 파이프라인을 식별하고 필요한 CodePipeline 파이프라인을 시작합니다.

## 도구
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-tools"></a>
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)는 코드에서 클라우드 인프라를 정의하고 이를 프로비저닝하기 위한 소프트웨어 개발 프레임워크입니다 CloudFormation.
+ [Python](https://www.python.org/)은 빠르게 작업하고 시스템을 보다 효과적으로 통합할 수 있는 프로그래밍 언어입니다.

**코드**

이 패턴의 소스 코드와 템플릿은 GitHub [AWS CodeCommit 모노리포지토리 다중 파이프라인 트리거](https://github.com/aws-samples/monorepo-multi-pipeline-trigger) 리포지토리에서 제공됩니다.

## 모범 사례
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-best-practices"></a>
+ 이 샘플 아키텍처에는 배포된 인프라에 대한 모니터링 솔루션이 포함되어 있지 않습니다. 프로덕션 환경에이 솔루션을 배포하려면 모니터링을 활성화하는 것이 좋습니다. 자세한 내용은 AWS Serverless Application Model (AWS SAM) 설명서의 [ CloudWatch Application Insights를 사용하여 서버리스 애플리케이션 모니터링을 참조하세요](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/monitor-app-insights.html).
+ 이 패턴에서 제공하는 샘플 코드를 편집할 때는 AWS CDK 설명서의 [클라우드 인프라 개발 및 배포 모범 사례를](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html) 따르세요.
+ 마이크로서비스 파이프라인을 정의할 때 AWS CodePipeline 설명서의 [보안 모범 사례를](https://docs.aws.amazon.com/codepipeline/latest/userguide/security-best-practices.html) 검토하세요.
+ [cdk-nag](https://github.com/cdklabs/cdk-nag) 유틸리티를 사용하여 AWS CDK 코드에서 모범 사례를 확인할 수도 있습니다. 이 도구는 팩별로 그룹화된 규칙 세트를 사용하여 코드를 평가합니다. 사용 가능한 팩은 다음과 같습니다.
  + [AWS 솔루션 라이브러리](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#awssolutions)
  + [건강보험 이동성 및 책임법(HIPAA) 보안](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#hipaa-security)
  + [국립 표준 기술 연구소(NIST) 800-53 버전 4](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#nist-800-53-rev-4)
  + [NIST 800-53 버전 5](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#nist-800-53-rev-5)
  + [지불 카드 산업 데이터 보안 표준(PCI DSS) 3.2.1](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#pci-dss-321)

## 에픽
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-epics"></a>

### 환경 설정
<a name="set-up-the-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 가상 Python 환경을 생성합니다. |  AWS Cloud9 IDE에서 다음 명령을 실행하여 가상 Python 환경을 생성하고 필요한 종속성을 설치합니다.`make install` | 개발자 | 
| 에 AWS 리전 대해 AWS 계정 및를 부트스트랩합니다 AWS CDK. | 다음 명령을 실행하여 필수 AWS 계정 및 리전을 부트스트랩합니다.`make bootstrap account-id=<your-AWS-account-ID> region=<required-region>` | 개발자 | 

### 마이크로서비스를 위한 새 파이프라인 추가
<a name="add-a-new-pipeline-for-a-microservice"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  애플리케이션 디렉터리에 샘플 코드를 추가합니다. | 샘플 애플리케이션 코드가 들어 있는 디렉터리를 복제된 GitHub [AWS CodeCommit 모노리포지토리 다중 파이프라인 트리거](https://github.com/aws-samples/monorepo-multi-pipeline-trigger) 리포지토리의 `monorepo-sample` 디렉터리에 추가합니다. | 개발자 | 
| `monorepo-main.json` 파일을 편집합니다. | 애플리케이션 코드의 디렉터리 이름과 파이프라인 이름을 복제된 리포지토리의 `monorepo-main.json` 파일에 추가합니다. | 개발자 | 
| 파이프라인을 생성하십시오. | 리포지토리의 `Pipelines` 디렉터리에 애플리케이션의 `class` 파이프라인을 추가합니다. 디렉터리에는 `pipeline_hotsite.py` 및 라는 두 개의 샘플 파일이 포함되어 있습니다`pipeline_demo.py`. 각 파일에는 소스, 빌드 및 배포라는 세 단계가 있습니다.애플리케이션 요구 사항에 따라 파일 중 하나를 복사하고 변경할 수 있습니다.  | 개발자 | 
| `monorepo_config.py` 파일을 편집합니다. | `service_map`에서 애플리케이션의 디렉터리 이름과 파이프라인용으로 만든 클래스를 추가합니다.예를 들어, 다음 코드는 `MySamplePipeline` 클래스로 이름이 `pipeline_mysample.py`로 지정된 파일을 사용하는 `Pipelines` 디렉터리의 파이프라인 정의를 보여줍니다.<pre>...<br /># Pipeline definition imports<br />from pipelines.pipeline_demo import DemoPipeline<br />from pipelines.pipeline_hotsite import HotsitePipeline<br />from pipelines.pipeline_mysample import MySamplePipeline<br /><br />### Add your pipeline configuration here<br />service_map: Dict[str, ServicePipeline]  = {<br />    # folder-name -> pipeline-class<br />    'demo': DemoPipeline(),<br />    'hotsite': HotsitePipeline(),<br />    'mysample': MySamplePipeline()<br />}</pre> | 개발자 | 

### MonoRepoStack 스택 배포
<a name="deploy-the-monorepostack-stack"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  AWS CloudFormation 스택을 배포합니다. | `make deploy-core` 명령을 실행하여 복제된 AWS CloudFormation `MonoRepoStack`리포지토리의 루트 디렉터리에 기본 파라미터 값을 사용하여 스택을 배포합니다.`make deploy-core monorepo-name=<repo_name>` 명령을 실행하여 리포지토리 이름을 변경할 수 있습니다.`make deploy monorepo-name=<repo_name>` 명령을 사용하여 두 파이프라인을 동시에 배포할 수 있습니다. | 개발자 | 
| CodeCommit 리포지토리를 확인합니다. | `aws codecommit get-repository --repository-name <repo_name>` 명령을 실행하여 리소스가 생성되었는지 확인합니다. CloudFormation 스택은 모노 리포지토리가 저장되는 CodeCommit 리포지토리를 생성하기 때문에 수정 내용을 푸시하기 시작한 경우 `cdk destroy MonoRepoStack `명령을 실행하지 마십시오. | 개발자 | 
|  CloudFormation 스택 결과를 검증합니다. | 다음 명령을 실행하여 스택이 CloudFormation `MonoRepoStack` 올바르게 생성되고 구성되었는지 확인합니다.<pre>aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE --query 'StackSummaries[?StackName == 'MonoRepoStack']'</pre> | 개발자 | 

### PipelinesStack 스택 배포
<a name="deploy-the-pipelinesstack-stack"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  CloudFormation 스택을 배포합니다. | 스택을 AWS CloudFormation `PipelinesStack` 배포한 후에는 `MonoRepoStack` 스택을 배포해야 합니다. 새 마이크로서비스가 모노리포지토리의 코드 베이스에 추가되면 스택의 크기가 증가하고 새 마이크로서비스가 온보딩되면 재배포됩니다.`make deploy-pipelines` 명령을 실행하여 PipelinesStack 스택을 배포합니다.`make deploy monorepo-name=<repo_name>` 명령을 실행하여 두 파이프라인을 동시에 배포할 수도 있습니다.다음 샘플 출력은 구현 종료 시 `PipelinesStacks` 배포가 마이크로서비스의 URL을 인쇄하는 방법을 보여줍니다.<pre>Outputs:<br />PipelinesStack.demourl = .cloudfront.net<br />PipelinesStack.hotsiteurl = .cloudfront.net</pre> | 개발자 | 
|  AWS CloudFormation 스택 결과를 검증합니다. | 다음 명령을 실행하여 스택이 AWS CloudFormation `PipelinesStacks` 올바르게 생성되고 구성되었는지 확인합니다.<pre>aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE --query 'StackSummaries[?StackName == 'PipelinesStack']'</pre> | 개발자 | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  AWS CloudFormation 스택을 삭제합니다. | `make destroy` 명령을 실행합니다. | 개발자 | 
| 파이프라인의 S3 버킷을 삭제하십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html) | 개발자 | 

## 문제 해결
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
|  AWS CDK 문제가 발생했습니다. | AWS CDK 설명서의 [일반적인 AWS CDK 문제 해결을](https://docs.aws.amazon.com/cdk/v2/guide/troubleshooting.html) 참조하세요. | 
| 마이크로서비스 코드를 푸시했지만 마이크로서비스 파이프라인이 실행되지 않았습니다. | **설정 검증***브랜치 구성을 확인합니다.*[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)*구성 파일 검증:*[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)**콘솔 문제 해결***AWS CodePipeline 검사:*[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)*AWS Lambda 문제 해결:*[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html) | 
| 모든 마이크로서비스를 재배포해야 합니다. | 모든 마이크로서비스를 강제로 재배포하려면 두 가지 접근 방식이 있습니다. 요구 사항에 맞는 옵션을 선택합니다.**접근 방식 1: 파라미터 스토어에서 파라미터 삭제**이 방법에는 배포에 사용된 마지막 커밋 ID를 추적하는 Systems Manager Parameter Store 내에서 특정 파라미터를 삭제하는 작업이 포함됩니다. 이 파라미터를 제거하면 시스템은 새 상태로 인식되므로 다음 트리거 시 모든 마이크로서비스를 다시 배포해야 합니다.단계:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)장점:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)단점:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)**접근 방식 2: 각 모노 리포지토리 하위 폴더에서 커밋 푸시**이 방법에는 사소한 변경을 수행하고 모노레포 내의 각 마이크로서비스 하위 폴더에 푸시하여 개별 파이프라인을 시작하는 작업이 포함됩니다.단계:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)장점:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)단점:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html) | 

## 관련 리소스
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-resources"></a>
+ [CDK Pipelines을 사용한 지속적 통합 및 전송(CI/CD)](https://docs.aws.amazon.com/cdk/latest/guide/cdk_pipeline.html)(AWS CDK 문서화)
+ [aws-cdk/pipelines 모듈](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html)(AWS CDK API 참조)

# AWS CloudFormation을 사용하여 Bitbucket 리포지토리를 AWS Amplify와 통합
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation"></a>

*Alwin Abraham, Amazon Web Services*

## 요약
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-summary"></a>

AWS Amplify를 사용하면 일반적으로 필요한 인프라를 설정하지 않고도 정적 웹 사이트를 빠르게 배포하고 테스트할 수 있습니다. 조직에서 기존 애플리케이션 코드를 마이그레이션하든 새 애플리케이션을 구축하든 관계없이 소스 제어에 Bitbucket을 사용하려는 경우 이 패턴의 접근 방식을 배포할 수 있습니다. AWS CloudFormation을 사용하여 Amplify를 자동으로 설정하면 사용 중인 구성에 대한 가시성을 제공할 수 있습니다.

이 패턴은 AWS CloudFormation을 사용하여 Bitbucket 리포지토리를 AWS Amplify와 통합함으로써 프런트 엔드 지속적 통합 및 지속적 배포(CI/CD) 파이프라인 및 배포 환경을 만드는 방법을 설명합니다. 이 패턴의 접근 방식은 반복 가능한 배포를 위한 Amplify 프런트 엔드 파이프라인을 구축할 수 있음을 의미합니다.

## 사전 조건 및 제한 사항
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-prereqs"></a>

**사전 조건**** **
+ 활성 Amazon Web Services(AWS) 계정
+ 관리자 액세스 권한이 있는 활성 Bitbucket 계정
+ [cURL](https://curl.se/) 또는 [Postman](https://www.postman.com/) 애플리케이션을 사용하는 터미널에 액세스
+ Amplify에 대한 지식
+ AWS CloudFormation에 대한 지식
+ YAML 형식의 파일에 대한 지식

## 아키텍처
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-architecture"></a>

![\[Diagram showing user interaction with Bitbucket repository connected to AWS Amplify in AWS 클라우드 region.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/24ae87ed-aa5d-4114-9c5d-bdcb4d40a78b/images/25d73a9d-d2ae-40bc-9ebc-57f9bd13884a.png)


**기술 스택  **
+ Amplify
+ AWS CloudFormation
+ Bitbucket

## 도구
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-tools"></a>
+ [AWS Amplify](https://docs.aws.amazon.com/amplify/) - Amplify는 개발자가 클라우드 기반 모바일 및 웹 앱을 개발하고 배포할 수 있도록 지원합니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) – AWS CloudFormation은 AWS 리소스를 모델링하고 설정하여 리소스 관리 시간을 줄이고 AWS에서 실행되는 애플리케이션에 더 많은 시간을 사용하도록 해 주는 서비스입니다.
+ [Bitbucket](https://bitbucket.org/) - Bitbucket은 전문가 팀을 위해 설계된 Git 리포지토리 관리 솔루션입니다. Git 리포지토리를 관리하고, 소스 코드에 대해 협업하고, 개발 흐름을 안내할 수 있는 중앙 장소를 제공합니다.

 

**코드**

`bitbucket-amplify.yml` 파일(첨부)에는 이 패턴에 대한 AWS CloudFormation 템플릿이 포함되어 있습니다.

## 에픽
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-epics"></a>

### Bitbucket 리포지토리 구성
<a name="configure-the-bitbucket-repository"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| (선택 사항) Bitbucket 리포지토리를 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)기존 Bitbucket 리포지토리를 사용할 수도 있습니다. | DevOps 엔지니어 | 
| 워크스페이스 설정을 엽니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html) | DevOps 엔지니어 | 
| OAuth 소비를 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html) | DevOps 엔지니어 | 
| OAuth 액세스 토큰을 확보합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)`curl -X POST -u "KEY:SECRET" https://bitbucket.org/site/oauth2/access_token -d grant_type=client_credentials ``KEY` 및 `SECRET`을 이전에 기록한 키와 비밀번호로 바꿉니다. 2. 따옴표를 사용하지 않고 액세스 토큰을 기록합니다. 토큰은 제한된 시간에만 유효하며 기본 시간은 2시간입니다. 이 기간 내에 AWS CloudFormation 템플릿을 실행해야 합니다. | DevOps 엔지니어 | 

### AWS CloudFormation 스택 생성 및 배포
<a name="create-and-deploy-the-aws-cloudformation-stack"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  AWS CloudFormation 템플릿을 다운로드합니다. | `bitbucket-amplify.yml` AWS CloudFormation 템플릿(첨부)을 다운로드합니다. 이 템플릿은 Amplify 프로젝트 및 브랜치 외에도 Amplify에서 CI/CD 파이프라인을 생성합니다. |  | 
| AWS CloudFormation 스택을 생성하고 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)5. **다음**을 선택한 다음 **스택 생성**을 선택합니다. | DevOps 엔지니어 | 

### CI/CD 파이프라인 테스트
<a name="test-the-ci-cd-pipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리포지토리의 브랜치에 코드를 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)자세한 내용은 Bitbucket 설명서의 [기본 Git 명령](https://confluence.atlassian.com/bitbucketserver/basic-git-commands-776639767.html)을 참조하세요.  | 앱 개발자 | 

## 관련 리소스
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-resources"></a>

[인증 방법](https://developer.atlassian.com/bitbucket/api/2/reference/meta/authentication)(Atlassian 설명서)

## 첨부
<a name="attachments-24ae87ed-aa5d-4114-9c5d-bdcb4d40a78b"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/24ae87ed-aa5d-4114-9c5d-bdcb4d40a78b/attachments/attachment.zip) 파일의 압축을 풉니다.

# Step Functions와 Lambda 프록시 함수를 사용하여 여러 AWS 계정에서 CodeBuild 프로젝트 시작
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function"></a>

*Richard Milner-Watts 및 Amit Anjarlekar, Amazon Web Services*

## 요약
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-summary"></a>

이 패턴은 AWS Step Functions와 AWS Lambda 프록시 함수를 사용하여 여러 AWS 계정에서 AWS CodeBuild 프로젝트를 비동기적으로 시작하는 방법을 보여줍니다. 패턴의 샘플 Step Functions 상태 머신을 사용하여 CodeBuild 프로젝트의 성공 여부를 테스트할 수 있습니다.

CodeBuild는 완전관리형 런타임 환경에서 AWS Command Line Interface(AWS CLI)를 사용하여 운영 작업을 시작할 수 있도록 지원합니다. 환경 변수를 재정의하여 런타임 시 CodeBuild 프로젝트의 동작을 변경할 수 있습니다. 또한 CodeBuild를 사용하여 워크플로우를 관리할 수 있습니다. 자세한 내용은 AWS 워크숍 웹사이트의 [서비스 카탈로그 도구](https://service-catalog-tools-workshop.com/tools.html) 및 AWS 데이터베이스 블로그의 [AWS CodeBuild와 Amazon EventBridge를 사용하는 Amazon RDS for PostgreSQL의 작업 일정 잡기](https://aws.amazon.com/blogs/database/schedule-jobs-in-amazon-rds-for-postgresql-using-aws-codebuild-and-amazon-eventbridge/)를 참조하세요.

## 사전 조건 및 제한 사항
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정 두 개: Step Functions를 사용하여 Lambda 프록시 함수를 호출하기 위한 소스 계정과 원격 CodeBuild 샘플 프로젝트를 빌드하기 위한 대상 계정

**제한 사항 **
+ 이 패턴은 계정 간에 [아티팩트](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html)를 복사하는 데 사용할 수 없습니다.

## 아키텍처
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-architecture"></a>

다음 다이어그램은 이 패턴이 구축하는 아키텍처를 보여줍니다.

![\[여러 AWS 계정에서 CodeBuild 프로젝트를 시작하는 아키텍처 다이어그램\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/809a5716-56e5-477c-aac6-02243675a2f2/images/857ba3ae-eb9a-4d6b-b73e-e596f41c8cb8.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. Step Functions 상태 시스템은 제공된 입력 맵을 구문 분석하고 정의한 각 계정, 리전 및 프로젝트에 대해 Lambda 프록시 함수(`codebuild-proxy-lambda`)를 간접적으로 호출합니다.

1. 이 Lambda 프록시 함수는 AWS Security Token Service(AWS STS)를 사용하여 대상 계정의 IAM 정책(`codebuild-proxy-policy`)과 연결된 IAM 프록시 역할(`codebuild-proxy-role`)을 맡습니다.

1. 맡은 역할을 사용하여 이 Lambda 함수는 CodeBuild 프로젝트를 시작하고 CodeBuild 작업 ID를 반환합니다. Step Functions 상태 머신은 성공 또는 실패 상태를 수신할 때까지 CodeBuild 작업을 반복하고 폴링합니다.

상태 시스템 로직은 다음 이미지에 나와 있습니다.

![\[Step Functions 상태 시스템의 워크플로\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/809a5716-56e5-477c-aac6-02243675a2f2/images/4729bbfc-79ad-455d-a85a-b96cce00f432.png)


**기술 스택  **
+ AWS CloudFormation
+ CodeBuild
+ IAM
+ Lambda
+ 단계 함수
+ X-Ray

## 도구
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)을 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, 전체 AWS 계정 및 리전에서 수명 주기 전반에 걸쳐 관리할 수 있습니다.
+ [AWS CloudFormation Designer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/working-with-templates-cfn-designer-json-editor.html)는 CloudFormation 템플릿을 보고 편집하는 데 도움이 되는 통합 JSON 및 YAML 편집기를 제공합니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)는 AWS Lambda 함수와 기타 AWS 서비스를 결합할 수 있는 서버리스 오케스트레이션 서비스로, 비즈니스 크리티컬 애플리케이션을 구축합니다.
+ [AWS X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html)는 애플리케이션이 처리하는 요청에 대한 데이터를 수집하는 웹 서비스이며 해당 데이터를 보고, 필터링하고, 통찰을 얻어 문제와 최적화 기회를 식별할 수 있는 도구를 제공합니다.

**코드**

이 패턴의 샘플 코드는 GitHub [교차 계정 CodeBuild 프록시](https://github.com/aws-samples/cross-account-codebuild-proxy) 리포지토리에서 사용할 수 있습니다. 이 패턴은 AWS Lambda Powertools for Python 라이브러리를 사용하여 로깅 및 추적 기능을 제공합니다. 이 라이브러리 및 해당 유틸리티에 대한 자세한 내용은 [Powertools for AWS Lambda (Python)](https://docs.powertools.aws.dev/lambda/python/latest/)를 참조하세요.

## 모범 사례
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-best-practices"></a>

1. Step Function 상태 시스템의 대기 시간 값을 조정하여 작업 상태에 대한 폴링 요청을 최소화합니다. CodeBuild 프로젝트의 예상 실행 시간을 사용합니다.

1. Step Functions에서 맵의 `MaxConcurrency` 속성을 조정하여 병렬로 실행할 수 있는 CodeBuild 프로젝트 수를 제어합니다.

1. 필요한 경우 샘플 코드에서 프로덕션 준비 상태를 검토합니다. 솔루션에서 로깅할 수 있는 데이터와 기본 Amazon CloudWatch 암호화가 충분한지 여부를 고려합니다.

## 에픽
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-epics"></a>

### 소스 계정에서 Lambda 프록시 함수 및 관련 IAM 역할을 생성합니다.
<a name="create-the-lambda-proxy-function-and-associated-iam-role-in-the-source-account"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS 계정 ID를 기록합니다. | 여러 계정에 대한 액세스를 설정하려면 AWS 계정 ID가 필요합니다.소스 및 대상 계정의 AWS 계정 ID를 기록해 둡니다. 자세한 내용은 IAM 설명서의 [AWS 계정 ID 찾기](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html#FindingYourAWSId)를 참조하세요. | AWS DevOps | 
| AWS CloudFormation 템플릿을 다운로드합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html)AWS CloudFormation 템플릿에서 는 소스 계정의 AWS 계정 ID이고, 는 대상 계정의 AWS 계정 ID입니다. | DevOps | 
| AWS CloudFormation 스택을 생성하고 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html)대상 계정에 리소스를 생성하기 전에 프록시 Lambda 함수를 위한 AWS CloudFormation 스택을 생성해야 합니다. 대상 계정에서 신뢰 정책을 생성하면 IAM 역할이 역할 이름에서 내부 식별자로 변환됩니다. 따라서 IAM 역할이 이미 존재해야 합니다. | AWS DevOps | 
| 프록시 함수 및 상태 머신의 생성을 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 

### 대상 계정에서 IAM 역할을 생성하고 샘플 CodeBuild 프로젝트를 시작합니다.
<a name="create-an-iam-role-in-the-target-account-and-launch-a-sample-codebuild-project"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS CloudFormation 스택을 생성하고 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 
| 샘플 CodeBuild 프로젝트가 생성되었는지 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 

### 교차 계정 Lambda 프록시 함수 테스트
<a name="test-the-cross-account-lambda-proxy-function"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 상태 머신을 실행합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 
| 환경 변수를 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | DevOps | 

## 문제 해결
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| Step Functions 실행 시간이 예상보다 오래 걸립니다. | Step Function 상태 시스템에서 맵의 `MaxConcurrency` 속성을 조정하여 병렬로 실행할 수 있는 CodeBuild 프로젝트 수를 제어합니다. | 
| CodeBuild 작업 실행 시간이 예상보다 오래 걸립니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | 

# Application Recovery Controller를 사용하여 EMR 클러스터에 대한 다중 AZ 장애 조치 관리
<a name="multi-az-failover-spark-emr-clusters-arc"></a>

*Aarti Rajput, Ashish Bhatt, Neeti Mishra, Nidhi Sharma, Amazon Web Services*

## 요약
<a name="multi-az-failover-spark-emr-clusters-arc-summary"></a>

이 패턴은 Amazon EMR 워크로드에 효율적인 재해 복구 전략을 제공하여 단일 내의 여러 가용 영역에서 고가용성 및 데이터 일관성을 보장하는 데 도움이 됩니다 AWS 리전. 이 설계는 [Amazon Application Recovery Controller](https://docs.aws.amazon.com/r53recovery/latest/dg/what-is-route53-recovery.html)와 [Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)를 사용하여 Apache Spark 기반 EMR 클러스터의 장애 조치 작업 및 트래픽 분산을 관리합니다.

표준 조건에서 기본 가용 영역은 전체 읽기/쓰기 기능을 갖춘 활성 EMR 클러스터 및 애플리케이션을 호스팅합니다. 가용 영역이 예기치 않게 실패하면 트래픽이 자동으로 보조 가용 영역으로 리디렉션되어 새 EMR 클러스터가 시작됩니다. 두 가용 영역 모두 전용 [게이트웨이 엔드포인트](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-s3.html)를 통해 공유 Amazon Simple Storage Service(Amazon S3) 버킷에 액세스하여 일관된 데이터 관리를 보장합니다. 이 접근 방식을 사용하면 가동 중지 시간을 최소화하고 가용 영역 장애 발생 시 중요한 빅 데이터 워크로드를 신속하게 복구할 수 있습니다. 솔루션은 실시간 분석이 중요한 금융 또는 소매와 같은 산업에서 유용합니다.

## 사전 조건 및 제한 사항
<a name="multi-az-failover-spark-emr-clusters-arc-prereqs"></a>

**사전 조건 **
+ 활성 [AWS 계정](https://aws.amazon.com/resources/create-account/)
+ [Amazon Elastic Compute Cloud(Amazon EC2)](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html)
+ EMR 클러스터의 마스터 노드에서 Amazon S3에 대한 액세스입니다.
+ AWS 다중 AZ 인프라

**제한 사항 **
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) 섹션을 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html) 페이지를 참조하고 서비스 링크를 선택합니다.

**제품 버전**
+ [Amazon EMR 릴리스 6.x 이상](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-release-components.html)

## 아키텍처
<a name="multi-az-failover-spark-emr-clusters-arc-architecture"></a>

**대상 기술 스택**
+ Amazon EMR 클러스터
+ Amazon Application Recovery Controller
+ Application Load Balancer
+ Amazon S3 버킷
+ Amazon S3에 대한 게이트웨이 엔드포인트

**대상 아키텍처 **

![\[Application Recovery Cotnroller를 사용한 자동 복구 메커니즘의 아키텍처입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/e5ecdb66-0eef-4a6a-8367-982a55104748/images/e982d580-13db-4bdd-9f6b-6400d7c31c01.png)


이 아키텍처는 여러 가용 영역을 사용하고 Application Recovery Controller를 통해 자동화된 복구 메커니즘을 구현하여 애플리케이션 복원력을 제공합니다.

1. Application Load Balancer는 일반적으로 기본 가용 영역의 기본 EMR 클러스터인 활성 Amazon EMR 환경으로 트래픽을 라우팅합니다.

1. 활성 EMR 클러스터는 애플리케이션 요청을 처리하고 읽기 및 쓰기 작업을 위한 전용 Amazon S3 게이트웨이 엔드포인트를 통해 Amazon S3에 연결합니다.

1. Amazon S3는 중앙 데이터 리포지토리 역할을 하며 잠재적으로 체크포인트 또는 EMR 클러스터 간의 공유 스토리지로 사용됩니다. EMR 클러스터는 `s3://` 프로토콜 및 [EMR 파일 시스템(EMRFS)](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-fs.html)을 통해 Amazon S3에 직접 쓸 때 데이터 일관성을 유지합니다.

1. Application Recovery Controller는 기본 가용 영역의 상태를 지속적으로 모니터링하고 필요한 경우 장애 조치 작업을 자동으로 관리합니다.

1. Application Recovery Controller가 기본 EMR 클러스터에서 장애를 감지하면 다음 작업을 수행합니다.
   + 가용 영역 2의 보조 EMR 클러스터에 대한 장애 조치 프로세스를 시작합니다.
   + 트래픽을 보조 클러스터로 전달하도록 라우팅 구성을 업데이트합니다.

## 도구
<a name="multi-az-failover-spark-emr-clusters-arc-tools"></a>

**서비스**
+ [Amazon Application Recovery Controller](https://docs.aws.amazon.com/r53recovery/latest/dg/what-is-route53-recovery.html)** **를 사용하면 AWS 리전 및 가용 영역에서 애플리케이션 복구를 관리하고 조정할 수 있습니다. 이 서비스는 기존 도구 및 프로세스에 필요한 수동 단계를 줄여 프로세스를 간소화하고 애플리케이션 복구의 신뢰성을 개선합니다.
+ Application Load Balancer는 개방형 시스템 간 상호 연결(OSI) 모델의 일곱 번째 계층인 애플리케이션 계층에서 작동합니다. 로드 밸런서는 여러 가용 영역에서 EC2 인스턴스 같은 여러 대상에 수신 애플리케이션 트래픽을 분산합니다. 이렇게 하면 애플리케이션의 가용성이 향상됩니다.
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 셸의 명령을 AWS 서비스 통해와 상호 작용하는 데 도움이 되는 오픈 소스 도구입니다.
+ [Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html)은 Apache Spark, Apache Hive 및 Presto와 같은 오픈 소스 프레임워크에 대한 데이터 처리, 대화형 분석 및 기계 학습을 제공하는 빅 데이터 플랫폼입니다.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 액세스를 인증하고 사용할 수 있는 권한을 부여받은 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다.
+ Amazon S3에서 제공하는 단순한 웹 서비스 인터페이스를 사용하여 언제든지 웹상 어디서나 원하는 양의 데이터를 저장하고 검색할 수 있습니다. 이 서비스를 사용하면 클라우드 네이티브 스토리지를 활용하는 애플리케이션을 쉽게 구축할 수 있습니다.
+ [Amazon S3의 게이트웨이 엔드포인트](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-s3.html)는 AWS 네트워크를 통해 Virtual Private Cloud(VPC)에서 Amazon S3에 액세스하기 위해 라우팅 테이블에 지정하는 게이트웨이입니다.

## 모범 사례
<a name="multi-az-failover-spark-emr-clusters-arc-best-practices"></a>
+ [AWS 보안, 자격 증명 및 규정 준수 모범 사례를](https://aws.amazon.com/architecture/security-identity-compliance/?cards-all.sort-by=%5b…%5d.sort-order=desc&awsf.content-type=*all&awsf.methodology=*all) 따라 강력하고 안전한 아키텍처를 보장합니다.
+  Well-Architected Framework에 맞춰 조정하기
+ Amazon S3 Access Grants를 사용하여 Spark 기반 EMR 클러스터에서 Amazon S3로의 액세스를 관리합니다. 자세한 내용은 블로그 게시물 [Use Amazon EMR with S3 Access Grants to Scale Spark access to Amazon S3](https://aws.amazon.com/blogs/big-data/use-amazon-emr-with-s3-access-grants-to-scale-spark-access-to-amazon-s3/)를 참조하세요.
+ [Amazon S3를 사용하여 Spark 성능을 개선](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-s3-performance.html)합니다.

## 에픽
<a name="multi-az-failover-spark-emr-clusters-arc-epics"></a>

### 환경을 설정합니다
<a name="set-up-your-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
|  AWS Management Console에 로그인합니다. | [IAM 사용자로AWS Management Console에 로그인](https://console.aws.amazon.com/) 지침은 [AWS 설명서](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-iam-user-sign-in-tutorial.html)를 참조하세요. | DevOps | 
| 구성.. AWS CLI**** | 에서와 상호 작용할 수 있도록를 설치 AWS CLI 하거나 최신 버전으로 업데이트 AWS 서비스 합니다 AWS Management Console. 지침은 [AWS CLI 설명서](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)를 참조하세요. | DevOps | 

### EMR 클러스터에 Spark 애플리케이션 배포
<a name="deploy-a-spark-application-on-your-emr-cluster"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| S3 버킷을 생성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | DevOps | 
| EMR 클러스터 생성 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | DevOps | 
| EMR 클러스터의 보안 설정을 구성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | DevOps | 
| 클러스터에 연결 | 제공된 키 페어를 사용하여 SSH를 통해 EMR 클러스터의 마스터 노드에 연결합니다.키 페어 파일이 애플리케이션과 동일한 디렉터리에 있는지 확인합니다.다음 명령을 실행하여 키 페어에 대한 올바른 권한을 설정하고 SSH 연결을 설정합니다.<pre>chmod 400 <key-pair-name><br />ssh -i ./<key-pair-name> hadoop@<master-node-public-dns></pre> | DevOps | 
|  SAM 애플리케이션 배포 | SSH 연결을 설정하면 하둡 콘솔에 있게 됩니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | DevOps | 
| Spark 애플리케이션을 모니터링합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | DevOps | 

### 트래픽을 다른 가용 영역으로 이동
<a name="shift-traffic-to-another-availability-zone"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Application Load Balancer을 생성합니다. | 내의 두 가용 영역에 배포된 Amazon EMR 마스터 노드 간에 트래픽을 라우팅하는 대상 그룹을 설정합니다 AWS 리전.지침은 [Lambda 함수의 대상 그룹 생성](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-target-group.html)(Elastic Load Balancing 설명서)을 참고하십시오. | DevOps | 
| Application Recovery Controller에서 영역 전환을 구성합니다. | 이 단계에서는 Application Recovery Controller의 [영역 전환 기능을](https://docs.aws.amazon.com/r53recovery/latest/dg/arc-zonal-shift.html) 사용하여 트래픽을 다른 가용 영역으로 전환합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html)를 사용하려면 Application Recovery Controller 설명서[의 영역 전환과 AWS CLI 함께를 사용하는 예를](https://docs.aws.amazon.com/r53recovery/latest/dg/getting-started-cli-zonalshift.html) AWS CLI참조하세요. | DevOps | 
| 영역 전환 구성 및 진행 상황을 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | DevOps | 

## 관련 리소스
<a name="multi-az-failover-spark-emr-clusters-arc-resources"></a>
+ AWS CLI 명령:
  + [create-cluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/create-cluster.html)
  + [describe-cluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/describe-cluster.html)
  + [arc-zonal-shift](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/arc-zonal-shift/index.html)
+ 스팟 인스턴스에 대한 Amazon EMR 클러스터 인스턴스 유형 및 모범 사례 구성
+ [IAM의 보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)(IAM 설명서)
+ [인스턴스 프로파일 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)(IAM 설명서)
+ [영역 전환 및 영역 자동 전환을 사용하여 ARC에서 애플리케이션 복구](https://docs.aws.amazon.com/r53recovery/latest/dg/multi-az.html)(Application Recovery Controller 설명서)

# AWS 코드 서비스 및 AWS KMS 다중 리전 키를 사용하여 여러 계정 및 리전에 대한 마이크로서비스의 블루/그린 배포를 관리
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys"></a>

*Balaji Vedagiri, Vanitha Dontireddy, Ashish Kumar, Faisal Shahdad, Vivek Thangamuthu, Anand Krishna Varanasi, Amazon Web Services*

## 요약
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-summary"></a>

이 패턴은 블루/그린 배포 전략에 따라 중앙 AWS 계정에서 여러 워크로드 계정 및 리전으로 글로벌 마이크로서비스 애플리케이션을 배포하는 방법을 설명합니다. 이 패턴은 다음을 지원합니다.
+ 소프트웨어는 중앙 계정에서 개발되는 반면, 워크로드와 애플리케이션은 여러 계정과 AWS 리전에 분산되어 있습니다.
+ 단일 AWS Key Management System(AWS KMS) 다중 리전 키는 재해 복구를 위한 암호화 및 복호화에 사용됩니다.
+ KMS 키는 리전별로 다르며 파이프라인 아티팩트를 위해 세 개의 다른 리전에서 유지 관리하거나 생성해야 합니다. KMS 다중 리전 키는 여러 리전에서 동일한 키 ID를 유지하는 데 도움이 됩니다.
+ Git 워크플로 브랜칭 모델은 두 개의 브랜치(개발 및 메인)로 구현되며 풀 리퀘스트(PR)를 사용하여 코드를 병합합니다. 이 스택에서 배포되는 AWS Lambda 함수는 개발 브랜치에서 메인 브랜치로 PR을 생성합니다. 메인 브랜치에 대한 PR 병합은 지속적 통합 및 지속적 전달(CI/CD) 흐름을 오케스트레이션하고 계정 전체에 스택을 배포하는 AWS CodePipeline 파이프라인을 시작합니다.

이 패턴은 이러한 사용 사례를 보여주기 위해 AWS CloudFormation 스택을 통해 코드형 인프라(IaC) 설정 샘플을 제공합니다. 마이크로서비스의 블루/그린 배포는 AWS CodeDeploy를 사용하여 구현됩니다.

## 사전 조건 및 제한 사항
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정 4개:
  + 코드 파이프라인을 관리하고 AWS CodeCommit 리포지토리를 유지 관리하기 위한 도구 계정.
  + 마이크로서비스 워크로드를 배포하기 위한 세 가지 워크로드(테스트) 계정.
+ 이 패턴은 다음 리전을 사용합니다. 다른 리전을 사용하려면 AWS CodeDeploy 및 AWS KMS 다중 리전 스택을 적절하게 수정해야 합니다.
  + 도구(AWS CodeCommit) 계정: `ap-south-1`
  + 워크로드(테스트) 계정 1: `ap-south-1`
  + 워크로드(테스트) 계정 2: `eu-central-1`
  + 워크로드(테스트) 계정 3: `us-east-1`
+ 각 워크로드 계정의 배포 리전을 위한 Amazon Simple Storage Service(S3) 버킷 3개. (나중에 이 패턴에서 `S3BUCKETNAMETESTACCOUNT1`, `S3BUCKETNAMETESTACCOUNT2 `, `S3BUCKETNAMETESTACCOUNT3 `으로 불립니다.)

  예를 들어 다음과 같이 고유한 버킷 이름을 사용하여 특정 계정 및 리전에 이러한 버킷을 생성할 수 있습니다(*xxxx*를 임의의 숫자로 대체).

  ```
  ##In Test Account 1
  aws s3 mb s3://ecs-codepipeline-xxxx-ap-south-1 --region ap-south-1
  ##In Test Account 2
  aws s3 mb s3://ecs-codepipeline-xxxx-eu-central-1 --region eu-central-1
  ##In Test Account 3
  aws s3 mb s3://ecs-codepipeline-xxxx-us-east-1 --region us-east-1
  
  #Example
  ##In Test Account 1
  aws s3 mb s3://ecs-codepipeline-18903-ap-south-1 --region ap-south-1
  ##In Test Account 2
  aws s3 mb s3://ecs-codepipeline-18903-eu-central-1 --region eu-central-1
  ##In Test Account 3
  aws s3 mb s3://ecs-codepipeline-18903-us-east-1 --region us-east-1
  ```

**제한 사항 **

이 패턴은 AWS CodeBuild 및 기타 구성 파일을 사용하여 샘플 마이크로서비스를 배포합니다. 여러 워크로드 유형(예: 서버리스)이 있는 경우 모든 관련 구성을 업데이트해야 합니다.

## 아키텍처
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-architecture"></a>

**대상 기술 스택 **
+ AWS CloudFormation
+ AWS CodeCommit
+ AWS CodeBuild
+ AWS CodeDeploy
+ AWS CodePipeline

**대상 아키텍처 **

![\[여러 계정 및 리전에 마이크로서비스를 배포하기 위한 대상 아키텍처\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/a144c977-6823-4b08-a215-fae779b3ce7c/images/eedfabdb-f266-4190-b271-5caf7ac9b47b.png)


**자동화 및 규모 조정**

이 설정은 AWS CloudFormation 스택 템플릿(IaC)을 사용하여 자동화됩니다. 여러 환경 및 계정에 맞게 쉽게 확장할 수 있습니다.

## 도구
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-tools"></a>

**서비스**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)을 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, 전체 AWS 계정 및 리전에서 수명 주기 전반에 걸쳐 관리할 수 있습니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 나만의 소스 제어 시스템을 관리할 필요 없이 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 버전 제어 서비스입니다.
+ [AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)는 Amazon Elastic Compute Cloud(Amazon EC2) 또는 온프레미스 인스턴스, AWS Lambda 함수 또는 Amazon Elastic Container Service(Amazon ECS) 서비스에 대한 배포를 자동화합니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.
+ [Amazon Elastic Container Registry(Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)는 안전하고 확장 가능하고 신뢰할 수 있는 관리형 컨테이너 이미지 레지스트리 서비스입니다.
+ [Amazon Elastic Container Service(Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)는 클러스터에서 컨테이너를 실행, 중지 및 관리하는 데 도움이 되는 빠르고 확장 가능한 컨테이너 관리 서비스입니다.
+ [AWS Key Management Service(AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html)를 사용하면 암호화 키를 생성하고 제어하여 데이터를 보호할 수 있습니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.

**추가 도구**
+ [Git](https://git-scm.com/docs)은 AWS CodeCommit 리포지토리와 함께 작동하는 오픈 소스 분산 버전 제어 시스템입니다.
+ [Docker](https://www.docker.com/)는 운영 체제 수준의 가상화를 사용하여 컨테이너에 소프트웨어를 제공하는 서비스형 플랫폼(PaaS) 제품 세트입니다. 이 패턴은 Docker를 사용하여 로컬에서 컨테이너 이미지를 구축하고 테스트합니다.
+ [cfn-lint](https://github.com/aws-cloudformation/cfn-lint)와 [cfn-nag](https://github.com/stelligent/cfn_nag)는 CloudFormation 스택에서 오류 및 보안 문제를 검토하는 데 도움이 되는 오픈 소스 도구입니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub의 [여러 리전 및 계정의 글로벌 블루/그린 배포](https://github.com/aws-samples/ecs-blue-green-global-deployment-with-multiregion-cmk-codepipeline) 리포지토리에서 사용할 수 있습니다.

## 에픽
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-epics"></a>

### 환경 변수 설정
<a name="set-up-environment-variables"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CloudFormation 스택 배포를 위한 환경 변수를 내보냅니다. | 이 패턴에서 나중에 CloudFormation 스택에 입력으로 사용할 환경 변수를 정의합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 

### 인프라용 CloudFormation 스택을 패키징하고 배포
<a name="package-and-deploy-the-cloudformation-stacks-for-the-infrastructure"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리포지토리를 복제합니다. | [샘플 리포지토리](https://github.com/aws-samples/ecs-blue-green-global-deployment-with-multiregion-cmk-codepipeline)를 작업 위치의 새 리포지토리로 복제하세요.<pre>##In work location<br />git clone https://github.com/aws-samples/ecs-blue-green-global-deployment-with-multiregion-cmk-codepipeline.git</pre> | AWS DevOps | 
| CloudFormation 리소스를 패키징하세요. | 이 단계에서는 CloudFormation 템플릿이 참조하는 로컬 아티팩트를 패키징하여 Amazon Virtual Private Cloud(VPC) 및 Application Load Balancer와 같은 서비스에 필요한 인프라 리소스를 생성합니다.템플릿은 코드 리포지토리의 `Infra` 폴더에서 사용할 수 있습니다.<pre>##In TestAccount1##<br />aws cloudformation package \<br />    --template-file mainInfraStack.yaml \<br />    --s3-bucket $S3BUCKETNAMETESTACCOUNT1 \<br />    --s3-prefix infraStack \<br />    --region $TESTACCOUNT1REGION \<br />    --output-template-file infrastructure_${TESTACCOUNT1}.template</pre><pre>##In TestAccount2##<br />aws cloudformation package \<br />    --template-file mainInfraStack.yaml \<br />    --s3-bucket $S3BUCKETNAMETESTACCOUNT2 \<br />    --s3-prefix infraStack \<br />    --region $TESTACCOUNT2REGION \<br />    --output-template-file infrastructure_${TESTACCOUNT2}.template</pre><pre>##In TestAccount3##<br />aws cloudformation package \<br />    --template-file mainInfraStack.yaml \<br />    --s3-bucket $S3BUCKETNAMETESTACCOUNT3 \<br />    --s3-prefix infraStack \<br />    --region $TESTACCOUNT3REGION \<br />    --output-template-file infrastructure_${TESTACCOUNT3}.template</pre> | AWS DevOps | 
| 패키지 템플릿을 검증하세요. | 패키지 템플릿 검증:<pre>aws cloudformation validate-template \<br />    --template-body file://infrastructure_${TESTACCOUNT1}.template<br /><br />aws cloudformation validate-template \<br />    --template-body file://infrastructure_${TESTACCOUNT2}.template<br /><br />aws cloudformation validate-template \<br />    --template-body file://infrastructure_${TESTACCOUNT3}.template</pre> | AWS DevOps | 
| 패키지 파일을 워크로드 계정에 배포하고, | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 

### 샘플 이미지를 푸시하고 Amazon ECS를 확장
<a name="push-a-sample-image-and-scale-amazon-ecs"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Amazon ECR 리포지토리에 샘플 이미지를 푸시합니다. | 샘플(NGINX) 이미지를 `web`이라는 Amazon Elastic Container Registry(Amazon ECR) 리포지토리에 (파라미터에 설정된 대로)푸시합니다. 필요에 따라 이미지를 사용자 지정할 수 있습니다.Amazon ECR에 이미지를 푸시하기 위해 로그인하고 보안 인증 정보를 설정하려면 [Amazon ECR 설명서](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)의 지침을 따르세요.명령은 다음과 같습니다.<pre>  docker pull nginx<br />  docker images<br />  docker tag <imageid> aws_account_id.dkr.ecr.region.amazonaws.com/<web>:latest<br />  docker push <aws_account_id>.dkr.ecr.<region>.amazonaws.com/<web>:tag </pre> | AWS DevOps | 
| Amazon ECS를 확장하고 액세스를 확인합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 

### 코드 서비스 및 리소스 설정
<a name="set-up-code-services-and-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 도구 계정에서 CodeCommit 리포지토리를 생성합니다. | GitHub 리포지토리의 `code` 폴더에 있는 `codecommit.yaml` 템플릿을 사용하여 도구 계정에서 CodeCommit 리포지토리를 생성합니다. 코드를 개발하려는 리전 하나에만 이 리포지토리를 생성해야 합니다.<pre>aws cloudformation deploy --stack-name codecommitrepoStack --parameter-overrides  CodeCommitReponame=$CODECOMMITREPONAME \<br />ToolsAccount=$TOOLSACCOUNT --template-file codecommit.yaml  --region $TOOLSACCOUNTREGION \<br />--capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 
| CodePipeline에서 생성된 아티팩트를 관리하기 위한 S3 버킷을 생성합니다. | GitHub 리포지토리의 `code` 폴더에 있는 `pre-reqs-bucket.yaml` 템플릿을 사용하여 CodePipeline에서 생성된 아티팩트를 관리하기 위한 S3 버킷을 생성합니다. 스택은 세 개의 워크로드(테스트) 및 도구 계정과 리전 모두에 배포되어야 합니다.<pre>aws cloudformation deploy --stack-name pre-reqs-artifacts-bucket --parameter-overrides BucketStartName=$BUCKETSTARTNAME \<br />TestAccount1=$TESTACCOUNT1 TestAccount2=$TESTACCOUNT2 \<br />TestAccount3=$TESTACCOUNT3 CodeCommitAccount=$CODECOMMITACCOUNT ToolsAccount=$TOOLSACCOUNT \<br />--template-file pre-reqs_bucket.yaml --region $TESTACCOUNT1REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />aws cloudformation deploy --stack-name pre-reqs-artifacts-bucket --parameter-overrides BucketStartName=$BUCKETSTARTNAME \<br />TestAccount1=$TESTACCOUNT1 TestAccount2=$TESTACCOUNT2 \<br />TestAccount3=$TESTACCOUNT3 CodeCommitAccount=$CODECOMMITACCOUNT ToolsAccount=$TOOLSACCOUNT \<br />--template-file pre-reqs_bucket.yaml --region $TESTACCOUNT2REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />aws cloudformation deploy --stack-name pre-reqs-artifacts-bucket --parameter-overrides BucketStartName=$BUCKETSTARTNAME \<br />TestAccount1=$TESTACCOUNT1 TestAccount2=$TESTACCOUNT2 \<br />TestAccount3=$TESTACCOUNT3 CodeCommitAccount=$CODECOMMITACCOUNT ToolsAccount=$TOOLSACCOUNT \<br />--template-file pre-reqs_bucket.yaml --region $TESTACCOUNT3REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />aws cloudformation deploy --stack-name pre-reqs-artifacts-bucket --parameter-overrides BucketStartName=$BUCKETSTARTNAME \<br />TestAccount1=$TESTACCOUNT1 TestAccount2=$TESTACCOUNT2 \<br />TestAccount3=$TESTACCOUNT3 CodeCommitAccount=$CODECOMMITACCOUNT ToolsAccount=$TOOLSACCOUNT \<br />--template-file pre-reqs_bucket.yaml --region $TOOLSACCOUNTREGION --capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 
| 멀티 리전 KMS 키를 설정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 
| 도구 계정에서 CodeBuild 프로젝트를 설정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 
| 워크로드 계정에서 CodeDeploy를 설정합니다. | GitHub 리포지토리의 `code` 폴더에 있는 `codedeploy.yaml` 템플릿을 사용하여 세 가지 워크로드 계정 모두에 CodeDeploy를 설정합니다. `mainInfraStack`의 출력에는 Amazon ECS 클러스터의 Amazon 리소스 이름(ARN)과 Application Load Balancer 리스너가 포함됩니다.인프라 스택의 값은 이미 내보내졌으므로 CodeDeploy 스택 템플릿에서 가져와야 합니다.<pre>##WorkloadAccount1##<br />aws cloudformation deploy --stack-name ecscodedeploystack \<br />--parameter-overrides  ToolsAccount=$TOOLSACCOUNT mainInfrastackname=mainInfrastack \<br />--template-file codedeploy.yaml  --region $TESTACCOUNT1REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />##WorkloadAccount2##<br />aws cloudformation deploy --stack-name ecscodedeploystack \<br />--parameter-overrides ToolsAccount=$TOOLSACCOUNT mainInfrastackname=mainInfrastack \<br />--template-file codedeploy.yaml  --region $TESTACCOUNT2REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />##WorkloadAccount3##<br />aws cloudformation deploy --stack-name ecscodedeploystack \<br />--parameter-overrides ToolsAccount=$TOOLSACCOUNT mainInfrastackname=mainInfrastack \<br />--template-file codedeploy.yaml  --region $TESTACCOUNT3REGION --capabilities CAPABILITY_NAMED_IAM</pre> | DevOps | 

### 도구 계정에 CodePipeline 설정
<a name="set-up-codepipeline-in-the-tools-account"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 도구 계정에 코드 파이프라인을 생성하세요. | 도구 계정에서 다음 명령어를 실행합니다.<pre>aws cloudformation deploy --stack-name ecscodepipelinestack --parameter-overrides  \<br />TestAccount1=$TESTACCOUNT1 TestAccount1Region=$TESTACCOUNT1REGION \<br />TestAccount2=$TESTACCOUNT2 TestAccount2Region=$TESTACCOUNT2REGION \<br />TestAccount3=$TESTACCOUNT3 TestAccount3Region=$TESTACCOUNT3REGION \<br />CMKARNTools=$CMKTROOLSARN CMKARN1=$CMKARN1 CMKARN2=$CMKARN2 CMKARN3=$CMKARN3 \<br />CodeCommitRepoName=$CODECOMMITREPONAME BucketStartName=$BUCKETSTARTNAME \<br />--template-file codepipeline.yaml --capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 
| AWS KMS 키 정책 및 S3 버킷 정책에서 CodePipeline 및 CodeBuild 역할에 대한 액세스를 제공합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 

### 파이프라인 직접 호출 및 테스트
<a name="call-and-test-the-pipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CodeCommit 리포지토리에 변경 사항을 푸시합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) |  | 

### 정리
<a name="clean-up"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포된 모든 리소스를 정리합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) |  | 

## 문제 해결
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 리포지토리에 커밋한 변경 사항은 배포되지 않습니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | 

## 관련 리소스
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-resources"></a>
+ [도커 이미지 푸시](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)(Amazon ECR 설명서)
+ [AWS CodeCommit 리포지토리에 연결](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)(AWS CodeCommit 설명서)
+ [AWS CodeBuild의 문제 해결](https://docs.aws.amazon.com/codebuild/latest/userguide/troubleshooting.html)(AWS CodeBuild 설명서)

# AWS CloudFormation과 AWS Config를 사용하여 Amazon ECR 리포지토리에서 와일드카드 권한 모니터링
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config"></a>

*Vikrant Telkar, Wassim Benhallam, Sajid Momin, Amazon Web Services*

## 요약
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-summary"></a>

Amazon Web Services(AWS) Cloud에서 Amazon Elastic Container Registry(Amazon ECR)는 AWS Identity 및 Access Management(IAM)를 사용하여 리소스 기반 권한이 있는 프라이빗 리포지토리를 지원하는 관리형 컨테이너 이미지 레지스트리 서비스입니다.

IAM은 리소스 및 작업 속성 모두에서 "`*`" 와일드카드를 지원하므로 이로 인해 일치하는 여러 항목을 자동으로 더 쉽게 선택할 수 있습니다. 테스트 환경에서는 인증된 모든 AWS 사용자가 `ecr:*` [와일드카드 권한](https://docs.aws.amazon.com/lambda/latest/operatorguide/wildcard-permissions-iam.html)을 사용하여 [리포지토리 정책 설명](https://docs.aws.amazon.com/AmazonECR/latest/userguide/set-repository-policy.html)의 주요 요소에서 Amazon ECR 리포지토리에 액세스하도록 허용할 수 있습니다. `ecr:*` 와일드카드 권한은 프로덕션 데이터에 액세스할 수 없는 개발 계정에서 개발하고 테스트할 때 유용할 수 있습니다.

하지만 `ecr:*` 와일드카드 권한은 심각한 보안 취약성을 유발할 수 있으므로 프로덕션 환경에서 사용하지 않도록 해야 합니다. 이 패턴의 접근 방식을 사용하면 리포지토리 정책 설명에 `ecr:*` 와일드카드 권한이 포함된 Amazon ECR 리포지토리를 식별하는 데 도움을 줍니다.   이 패턴은 AWS Config에서 사용자 지정 규칙을 생성하기 위한 단계와 AWS CloudFormation 템플릿을 제공합니다. 그러면 AWS Lambda 함수가 `ecr:*` 와일드카드 권한에 대한 Amazon ECR 리포지토리 정책 설명을 모니터링합니다. 규정 미준수인 리포지토리 정책 설명을 발견하면 Lambda는 Amazon EventBridge 및 EventBridge에 이벤트를 보내도록 AWS Config에 알린 다음 EventBridge는 Amazon Simple Notification Service(Amazon SNS) 주제를 시작합니다. SNS 주제는 비준수 리포지토리 정책 설명에 대해 이메일로 알려줍니다.

## 사전 조건 및 제한 사항
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정.
+ AWS Command Line Interface(AWS CLI), 설치 및 구성됨. 이에 대한 자세한 내용은 AWS CLI 설명서의 [AWS CLI 설치, 업데이트 및 제거](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)를 참조하세요.
+ 정책 설명이 첨부되어 있는 기존 Amazon ECR 리포지토리가 테스트 환경에 설치 및 구성됩니다. 이에 대한 자세한 내용은 Amazon ECR 설명서의 [프라이빗 리포지토리 생성](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html) 및 [리포지토리 정책 설명 설정](https://docs.aws.amazon.com/AmazonECR/latest/userguide/set-repository-policy.html)을 참조하세요.
+ AWS Config, 원하는 AWS 리전에 구성됩니다. 이에 대한 자세한 내용은 AWS Config 설명서의 [AWS Config 시작하기](https://docs.aws.amazon.com/config/latest/developerguide/getting-started.html)를 참조하세요.
+ `aws-config-cloudformation.template` 파일(첨부), 로컬 시스템에 다운로드됩니다.

 

**제한 사항 **
+ 이 패턴의 솔루션은 리전의 솔루션이며 리소스는 동일한 리전에 생성되어야 합니다. 

## 아키텍처
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-architecture"></a>

다음 다이어그램은 AWS Config가 Amazon ECR 리포지토리 정책 설명을 평가하는 방법을 보여줍니다. 

![\[AWS Config workflow with Lambda, Amazon ECR, EventBridge, SNS, and email notification components.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/01bbf5f8-27aa-4c64-9a03-7fcccc0955b8/images/49bbf14b-0a18-4d4a-86ab-162d37708e01.png)


이 다이어그램은 다음 워크플로우를 보여줍니다.

1. AWS Config는 사용자 지정 규칙을 시작합니다. 

1. 사용자 지정 규칙은 Lambda 함수를 호출하여 Amazon ECR 리포지토리 정책 설명의 규정 준수를 평가합니다. 그런 다음 Lambda 함수는 규정을 준수하지 않는 리포지토리 정책 설명을 식별합니다.

1. Lambda 함수는 규정 미준수 상태를 AWS Config에 전송합니다.

1. AWS Config는 EventBridge에 이벤트를 전송합니다.

1. EventBridge는 규정 미준수 알림을 SNS 주제에 게시합니다.

1. Amazon SNS에서는 귀하 또는 승인된 사용자에게 이메일 알림을 전송합니다.

**자동화 및 규모 조정**

이 패턴의 솔루션은 Amazon ECR 리포지토리 정책 설명을 얼마든지 모니터링할 수 있지만 평가하려는 모든 리소스는 동일한 리전에서 생성되어야 합니다.

## 도구
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)–AWS CloudFormation을 사용하면 AWS 리소스를 모델링 및 설정하고, 빠르고 일관되게 프로비저닝하며, 수명 주기 전반에 걸쳐 관리할 수 있습니다. 템플릿을 사용하여 리소스와 해당 종속성을 설명하고, 리소스를 개별적으로 관리하는 대신 스택으로 함께 시작하고 구성할 수 있습니다. 여러 AWS 계정 및 AWS 리전에서 스택을 관리하고 프로비저닝할 수 있습니다.
+ [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) - AWS Config는 AWS 계정의 AWS 리소스 구성에 대한 세부 정보 보기를 제공합니다. 이러한 보기에는 리소스 간에 어떤 관계가 있는지와 리소스가 과거에 어떻게 구성되었는지도 포함되므로, 시간이 지나면서 구성과 관계가 어떻게 변하는지 확인할 수 있습니다.
+ [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)** **–** **Amazon Elastic Container Registry(Amazon ECR)는 안전하고 확장 가능하고 신뢰할 수 있는 관리형 컨테이너 이미지 레지스트리 서비스입니다. Amazon ECR은 IAM을 사용하여 리소스 기반 권한을 가진 프라이빗 리포지토리를 지원합니다.                                
+ [Amazon EventBridge ](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)– Amazon EventBridge는 애플리케이션을 다양한 소스의 데이터와 연결하는 데 사용할 수 있는 서버리스 이벤트 버스 서비스입니다. EventBridge는 애플리케이션, 서비스형 소프트웨어(SaaS) 애플리케이션 및 AWS 서비스의 실시간 데이터 스트림을 AWS Lambda 함수, API 대상을 사용하는 HTTP 호출 엔드포인트 또는 다른 계정의 이벤트 버스와 같은 대상으로 제공합니다.
+ [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(SNS)는 웹 서버와 이메일 주소를 포함하여 게시자와 클라이언트 간에 메시지를 전달 또는 전송하는 것을 조정하고 관리합니다. 구독자는 구독하는 주제에 게시된 모든 메시지를 수신하며 주제에 대한 모든 구독자는 동일한 메시지를 수신합니다. 

**코드**

이 패턴의 코드는 `aws-config-cloudformation.template` 파일(첨부)에서 확인할 수 있습니다.

## 에픽
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-epics"></a>

### AWS CloudFormation 스택을 생성하려면
<a name="create-the-aws-cloudformation-stack"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS CloudFormation 스택을 생성합니다. | AWS CLI에서 다음 명령을 실행하여 AWS CloudFormation 스택을 생성합니다.<pre>$ aws cloudformation create-stack --stack-name=AWSConfigECR \<br />    --template-body  file://aws-config-cloudformation.template \<br />    --parameters ParameterKey=<email>,ParameterValue=<myemail@example.com> \<br />    --capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 

### AWS Config 사용자 지정 규칙 테스트
<a name="test-the-aws-config-custom-rule"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS Config 사용자 지정 규칙을 테스트합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config.html) | AWS DevOps | 

## 첨부
<a name="attachments-01bbf5f8-27aa-4c64-9a03-7fcccc0955b8"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/01bbf5f8-27aa-4c64-9a03-7fcccc0955b8/attachments/attachment.zip) 파일의 압축을 풉니다.

# AWS CDK 및 GitHub Actions 워크플로를 사용하여 다중 계정 서버리스 배포 최적화
<a name="optimize-multi-account-serverless-deployments"></a>

*Sarat Chandra Pothula 및 VAMSI KRISHNA SUNKAVALLI, Amazon Web Services*

## 요약
<a name="optimize-multi-account-serverless-deployments-summary"></a>

여러 AWS 계정 및 환경에 서버리스 인프라를 배포하는 조직은 코드 복제, 수동 프로세스 및 일관되지 않은 관행과 같은 문제를 겪는 경우가 많습니다. 이 패턴의 솔루션은 Go 및 GitHub Actions 재사용 가능한 워크플로 AWS Cloud Development Kit (AWS CDK) 에서를 사용하여 다중 계정 서버리스 인프라 관리를 간소화하는 방법을 보여줍니다. 이 솔루션은 클라우드 리소스를 코드로 정의하고, 표준화된 지속적 통합/지속적 배포(CI/CD) 프로세스를 구현하고, 재사용 가능한 모듈식 구성 요소를 생성하는 방법을 보여줍니다.

이러한 도구를 사용하면 조직은 교차 계정 리소스를 효율적으로 관리하고, 일관된 배포 파이프라인을 구현하고, 복잡한 서버리스 아키텍처를 간소화할 수 있습니다. 또한이 접근 방식은와 함께 사용하기 위한 표준화된 관행을 적용함으로써 보안 및 규정 준수를 강화 AWS 계정함으로써 궁극적으로 생산성을 개선하고 서버리스 애플리케이션 개발 및 배포의 오류를 줄입니다.

## 사전 조건 및 제한 사항
<a name="optimize-multi-account-serverless-deployments-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ AWS Identity and Access Management (IAM) 배포 프로세스에 대한 [역할과 권한이](https://docs.aws.amazon.com/AmazonECR/latest/userguide/security-iam.html) 있습니다. 여기에는 Amazon Elastic Container Registry(Amazon ECR) 리포지토리에 액세스하고, AWS Lambda 함수 및 대상 전반의 기타 필수 리소스를 생성할 수 있는 권한이 포함됩니다 AWS 계정.
+ AWS Command Line Interface (AWS CLI) 버전 2.9.11 이상, [설치](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) 및 [구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)됨.
+ AWS Cloud Development Kit (AWS CDK) 버전 2.114.1 이상, [설치](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install) 및 [부트스트래핑](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_bootstrap)됨.
+  v1.22 이상이 설치되었습니다.
+ Docker 24.0.6 이상이 [설치](https://docs.docker.com/engine/install/)되었습니다.

**제한 사항 **
+ **언어 호환성 **- Go는 서버리스 애플리케이션에 널리 사용되는 언어입니다. 그러나 Go 외에도는 C\$1, Java, Python 및 TypeScript를 비롯한 다른 프로그래밍 언어를 AWS CDK 지원합니다. 조직에 기존 코드 베이스가 있거나 다른 언어에 대한 전문 지식이 있는 경우 패턴에 설명된 솔루션을 완전히 사용하려면 Go를 조정하거나 학습해야 할 수 있습니다.
+ **학습 곡선 **- AWS CDK Go(조직을 처음 사용하는 경우) 및 GitHub 재사용 가능한 워크플로를 채택하려면 개발자와 DevOps 팀을 위한 학습 곡선이 포함될 수 있습니다. 이러한 기술을 원활하게 채택하고 효과적으로 사용하려면 교육 및 설명서가 필요할 수 있습니다.

## 아키텍처
<a name="optimize-multi-account-serverless-deployments-architecture"></a>

다음 다이어그램은 이 패턴의 워크플로 및 구성 요소를 보여 줍니다.

![\[다중 계정 서버리스 인프라 관리를 위한 AWS CDK 및 GitHub Actions 워크플로의 아키텍처입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/8d61917b-bd27-44fa-ae95-55358aaf8812/images/a4b36793-95c7-42f7-a92f-99b4722c9c64.png)


해결 방법: 다음 단계를 수행합니다.

1. 개발자는 리포지토리를 복제하고, 새 브랜치를 생성하고, 로컬 환경에서 애플리케이션 코드를 변경합니다.

1. 개발자는 이러한 변경 사항을 커밋하고 새 브랜치를 GitHub 리포지토리로 푸시합니다.

1. 개발자는 GitHub 리포지토리에 풀 요청을 생성하여 해당 기능 또는 새 기능 브랜치를 기본 브랜치에 병합하도록 제안합니다.

1. 이 풀 요청은 지속적 통합(CI) GitHub Actions 워크플로를 트리거합니다. 이 패턴의 CI 및 연속 배포(CD) 워크플로는 다양한 프로젝트 또는 리포지토리에서 공유하고 실행할 수 있는 사전 정의된 모듈식 템플릿인 재사용 가능한 워크플로를 사용합니다. 재사용 가능한 워크플로는 CI/CD 프로세스의 표준화와 효율성을 높입니다.

1. CI 워크플로는 필요한 환경을 설정하고, 이미지에 대한 Docker 태그를 생성하고, 애플리케이션 코드를 사용하여 Docker 이미지를 빌드합니다.

1. CI 워크플로는 central AWS 계정 GitHub OIDC 역할을 AWS 사용하여 로 인증합니다. CI 워크플로의 경우 central AWS 계정 GitHub OIDC 역할은 AWS Security Token Service (AWS STS)를 사용하여 임시 자격 증명을 얻습니다. 이러한 자격 증명을 통해 역할은 Docker 이미지를 빌드하고 중앙의 Amazon ECR 리포지토리에 푸시할 수 있습니다 AWS 계정.

1. CI 워크플로는 빌드된 Docker 이미지를 Amazon ECR로 푸시합니다.

1. CI 워크플로는 이미지 태그를 Systems Manager 파라미터 스토어에 저장합니다.

1. CI 워크플로가 성공적으로 완료되면 도커 이미지 태그가 출력됩니다.

1. CD 워크플로를 트리거할 때 개발자는 배포하려는 Docker 이미지의 이미지 태그를 수동으로 입력합니다. 이 이미지 태그는 CI 워크플로 중에 생성되어 Amazon ECR로 푸시된 태그에 해당합니다.

1. 개발자는 CD 재사용 가능한 워크플로를 사용하는 CD 워크플로를 수동으로 트리거합니다.

1. CD 워크플로는 central AWS 계정 GitHub OIDC 역할을 AWS 사용하여를 인증합니다. CD 워크플로의 경우 AWS STS 는 먼저 central AWS 계정 GitHub OIDC 역할을 수임하는 데 사용됩니다. 그런 다음이 역할은 대상 계정 배포에 대한 CDK 부트스트랩 역할을 수임합니다.

1. CD 워크플로는를 사용하여 AWS CloudFormation 템플릿을 합성 AWS CDK 합니다.

1. CD 워크플로는 Lambda 함수에 대해 수동으로 지정된 이미지 태그를 AWS 계정 사용하여 CDK 배포를 사용하여 애플리케이션을 대상에 배포합니다.

## 도구
<a name="optimize-multi-account-serverless-deployments-tools"></a>

**AWS 서비스**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)는 코드로 AWS 클라우드 인프라를 정의하고 프로비저닝하는 데 도움이 되는 소프트웨어 개발 프레임워크입니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, AWS 계정 및의 수명 주기 동안 리소스를 관리할 수 있습니다 AWS 리전. CloudFormation은 AWS CDK 배포 프로세스의 중요한 부분입니다. CDK는 CloudFormation 템플릿을 합성한 다음 CloudFormation을 사용하여 AWS 환경에서 리소스를 생성하거나 업데이트합니다.
+ [Amazon Elastic Container Registry(Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)는 안전하고 확장성이 있고 신뢰할 수 있는 관리형 컨테이너 이미지 레지스트리 서비스입니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)는 구성 데이터 관리 및 보안 암호 관리를 위한 안전한 계층적 스토리지를 제공합니다.

**기타 도구**
+ [Docker](https://www.docker.com/)는 운영 체제 수준의 가상화를 사용하여 컨테이너에 소프트웨어를 제공하는 서비스형 플랫폼(PaaS) 제품 세트입니다.
+ [GitHub Actions](https://docs.github.com/en/actions/writing-workflows/quickstart)는 GitHub 리포지토리와 긴밀하게 통합된 지속적 통합 및 지속적 전달(CI/CD) 플랫폼입니다. GitHub Actions를 사용하여 빌드, 테스트 및 배포 파이프라인을 자동화할 수 있습니다.
+ [Go](https://go.dev/doc/install)는 Google이 지원하는 오픈 소스 프로그래밍 언어입니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [aws-cdk-golang-serverless-cicd-github-actions](https://github.com/aws-samples/aws-cdk-golang-serverless-cicd-github-actions) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="optimize-multi-account-serverless-deployments-best-practices"></a>
+ **모듈식 설계** - AWS CDK 코드를 모듈식의 재사용 가능한 구문 또는 스택으로 구성하여 여러 계정 및 프로젝트에서 코드 재사용 및 유지 관리를 촉진합니다.
+ **문제 분리** - 인프라 코드를 애플리케이션 코드와 분리하여 각 구성 요소를 독립적으로 배포하고 관리할 수 있습니다.
+ **버전 관리 및 변경 불가능** - 인프라를 코드형(IaC)으로 취급하고 버전 관리에 Git을 사용합니다. 기존 리소스를 수정하는 대신 새 리소스를 생성하여 변경 불가능한 인프라 원칙을 수용합니다.
+ **테스트 및 검증** - AWS CDK 코드 및 배포의 정확성과 신뢰성을 지원하는 데 도움이 되도록 단위 테스트, 통합 테스트 및 end-to-end 테스트를 비롯한 포괄적인 테스트 전략을 구현합니다.
+ **보안 및 규정 준수** - 최소 권한 액세스, 보안 통신 및 데이터 암호화와 같은 AWS 보안 모범 사례를 따릅니다. 규정 준수 검사 및 감사 메커니즘을 구현하여 조직 정책 및 규제 요구 사항을 준수하는지 확인합니다. 취약성 검사, 이미지 서명 적용, 조직의 규정 준수 요구 사항 준수와 같은 컨테이너 이미지에 대한 보안 모범 사례를 구현합니다.
+ **모니터링 및 로깅** - 서버리스 애플리케이션 및 인프라의 상태와 성능을 추적하는 모니터링 및 로깅 메커니즘을 설정합니다. AWS X-Ray 모니터링 AWS CloudTrail및 감사 목적으로 Amazon CloudWatch 및와 AWS 서비스 같이를 사용합니다.
+ **자동화 및 CI/CD** - GitHub 재사용 가능한 워크플로 및 기타 CI/CD 도구를 사용하여 빌드, 테스트 및 배포 프로세스를 자동화함으로써 여러 계정에 걸쳐 일관되고 반복 가능한 배포를 지원할 수 있습니다.
+ **환경 관리** - 별도의 환경(예: 개발, 스테이징 및 프로덕션)을 유지 관리합니다. 환경 간에 변경 사항을 홍보하고 프로덕션 배포 전에 적절한 테스트 및 검증을 보장하기 위한 전략을 구현합니다.
+ **문서화 및 협업** - 인프라 코드, 배포 프로세스 및 모범 사례를 문서화하여 팀 내에서 지식 공유 및 협업을 촉진합니다.
+ **비용 최적화** - 리소스 크기 조정, 자동 크기 조정 사용, AWS Budgets 및 같은 비용 최적화 서비스 활용과 같은 AWS 비용 모니터링 및 최적화 전략을 구현합니다 AWS Cost Explorer.
+ **재해 복구 및 백업** - 서버리스 애플리케이션 및 인프라 리소스에 대한 백업 및 복원 메커니즘을 구현하여 재해 복구 시나리오를 계획합니다.
+ **지속적인 개선** - 서버리스 에코시스템의 최신 모범 사례, 보안 권장 사항 및 기술 발전에 맞게 정기적으로 검토하고 사례, 도구 및 프로세스를 업데이트합니다.
+ **보안 태세 개선** - Amazon ECR AWS Lambda및 파라미터 스토어에 대한 인터페이스 VPC 엔드포인트를 구성하여 Virtual Private Cloud(VPC)의 보안 AWS Systems Manager 태세를 개선하는 [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html) 데 사용합니다.

## 에픽
<a name="optimize-multi-account-serverless-deployments-epics"></a>

### 환경 설정
<a name="set-up-the-environments"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 중앙에서 Amazon ECR 리포지토리를 생성합니다 AWS 계정. | 여러 컨테이너 이미지를 공유하려면 Amazon ECR에 대한 교차 계정 액세스를 구성 AWS 계정해야 합니다. 먼저 중앙에 Amazon ECR 리포지토리를 생성합니다 AWS 계정.리포지토리를 생성하려면 다음 명령을 실행합니다.<pre>aws ecr create-repository --repository-name sample-repo</pre>이후 작업에서는 컨테이너 이미지를 사용해야 AWS 계정 하는 다른에 풀 액세스 권한을 부여합니다. | DevOps | 
| Amazon ECR 리포지토리에 교차 계정 권한을 추가합니다. | 중앙의 Amazon ECR 리포지토리에 교차 계정 권한을 추가하려면 다음 코드를 AWS 계정실행합니다.<pre>{<br />  "Version": "2008-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Sid": "LambdaECRImageRetrievalPolicy",<br />      "Effect": "Allow",<br />      "Principal": {<br />        "Service": "lambda.amazonaws.com"<br />      },<br />      "Action": [<br />        "ecr:BatchGetImage",<br />        "ecr:GetDownloadUrlForLayer",<br />      ],<br />      "Condition": {<br />        "StringLike": {<br />          "aws:sourceArn": "arn:aws:lambda:<Target_Region>:<Target_Account_ID>:function:*"<br />        }<br />      }<br />    },<br />    {<br />      "Sid": "new statement",<br />      "Effect": "Allow",<br />      "Principal": {<br />        "AWS": "arn:aws:iam::<Target_Account_ID>:root"<br />        },<br />      "Action": [<br />        "ecr:BatchGetImage",<br />        "ecr:GetDownloadUrlForLayer",<br />      ],<br />    }<br />  ] <br />}</pre> | DevOps | 
| 중앙에서 GitHub OIDC 역할에 대한 역할을 구성합니다 AWS 계정. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | DevOps | 
| 대상의 AWS 환경을 부트스트랩합니다 AWS 계정. | 중앙 계정에서 교차 계정 배포를 AWS 리전 활성화하고 CloudFormation 실행 역할에 최소 권한 원칙을 적용하는 특정 AWS 계정 및에서 CDK 환경을 설정합니다. AWS 환경을 [부트스트랩](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)하려면 다음 명령을 실행합니다.<pre>cdk bootstrap aws://<Target_Account_ID>/<Target_Region> --trust <Central_Account_ID> --cloudformation-execution-policies arn:aws:iam::aws:policy/<Least_Privilege_Policy></pre> | DevOps | 
| 대상 AWS 계정 부트스트랩 역할에 대한 중앙 AWS 계정 OIDC 역할 액세스 권한을 부여합니다. | CDK 부트스트랩은 CDK 배포 프로세스의 AWS 계정 다양한 단계에서 중앙에서 수임하도록 설계된 다음과 같은 IAM 역할을 생성합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html)각 역할에는 최소 권한 원칙에 따라 목적에 맞는 특정 권한이 있습니다. 각 역할 이름`Target_Region`의 `Target_Account_ID` 및는 이러한 역할이 서로 다른 AWS 계정 및 리전에서 고유함을 나타내는 데 도움이 됩니다. 이 접근 방식은 다중 계정, 다중 리전 설정에서 명확한 식별 및 관리를 지원합니다.<pre>Target Account CDK Bootstrap Roles<br />arn:aws:iam::<Target_Account_ID>:role/cdk-deploy-role-<Target_Account_ID>-<Target_Region><br />arn:aws:iam::<Target_Account_ID>:role/cdk-file-publishing-role-<Target_Account_ID>-<Target_Region><br />arn:aws:iam::<Target_Account_ID>:role/cdk-image-publishing-role-<Target_Account_ID>-<Target_Region><br />arn:aws:iam::<Target_Account_ID>:role/cdk-lookup-role-<Target_Account_ID>-<Target_Region></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html)중앙의 OIDC 역할에 대한 권한 정책을 업데이트하려면 다음 코드를 AWS 계정사용합니다.<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Action": "sts:AssumeRole",<br />            "Resource": [<br />                "arn:aws:iam::<Target_Account_ID>:role/cdk-deploy-role-<Target_Account_ID>-<Target_Region>",<br />                "arn:aws:iam::<Target_Account_ID>:role/cdk-file-publishing-role-<Target_Account_ID>-<Target_Region>",<br />                "arn:aws:iam::<Target_Account_ID>:role/cdk-image-publishing-role-<Target_Account_ID>-<Target_Region>",<br />                "arn:aws:iam::<Target_Account_ID>:role/cdk-lookup-role-<Target_Account_ID>-<Target_Region>"<br />            ]<br />        }<br />    ]<br /> }<br /></pre> | DevOps | 

### Docker 이미지를 구축합니다.
<a name="build-the-docker-image"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 프로젝트 리포지토리를 복제합니다. | 다음 명령은 이 패턴의 GitHub 리포지토리를 복제합니다.<pre>git clone https://github.com/aws-samples/aws-cdk-golang-serverless-cicd-github-actions.git</pre> | DevOps | 
| Dockerfile 경로로 이동합니다. | Dockerfile로 이동하려면 다음 명령을 실행합니다.<pre>cd lambda</pre> | DevOps | 
| Amazon ECR 리포지토리로 Docker 인증 | Amazon ECR을 사용하려면 프라이빗 컨테이너 리포지토리에 대한 보안 액세스가 필요합니다. 이러한 방식으로 로그인하면 로컬 시스템 또는 CI/CD 환경의 Docker가 Amazon ECR과 안전하게 상호 작용할 수 있습니다.Amazon ECR로 Docker를 인증하려면 다음 명령을 실행합니다.<pre>aws ecr get-login-password --region <AWS_REGION> | docker login --username AWS --password-stdin <AWS_ACCOUNT_ID>.dkr.ecr.<AWS_REGION>.amazonaws.com</pre>정보와 `AWS_Account_ID` 함께 자리 표시자 `AWS_REGION` 및를 수정합니다. | DevOps | 
| Docker 이미지를 구축합니다. | 도커 이미지를 생성하려면 다음 명령을 실행합니다.<pre>docker build --platform linux/arm64 -t sample-app .</pre> | DevOps | 
| 도커 이미지를 빌드하고 푸시합니다. | 다음 명령을 실행하여 도커 이미지를 Amazon ECR 리포지토리에 푸시합니다.<pre>docker tag sample-app:latest <AWS_ACCOUNT_ID>.dkr.ecr.<AWS_REGION>.amazonaws.com/<ECR_REPOSITORY>:<DOCKER_TAG></pre><pre>docker push <AWS_ACCOUNT_ID>.dkr.ecr.<AWS_REGION>.amazonaws.com/<ECR_REPOSITORY>:<DOCKER_TAG></pre>정보를 사용하여 자리 표시자 `AWS_Account_ID`, `ECR_REPOSITORY`, `AWS_REGION`및 `DOCKER_TAG`를 수정합니다. | DevOps | 

### AWS CDK 앱 배포
<a name="deploy-the-cdk-app"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CDK 스택을 환경별 변수와 합성합니다. | CDK 코드에 정의된 대로 인프라에 대한 CloudFormation 템플릿을 생성하려면 다음 명령을 실행합니다.<pre>ENV=<environment> IMAGETAG=<image_tag> ECR_ARN=<ecr_repo_arn> cdk synth</pre>정보를 사용하여 다음 자리 표시자를 수정합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | DevOps | 
| 스택을 배포합니다. | CDK 스택을에 배포하려면 다음 명령을 AWS 계정실행합니다. `--require-approval never` 플래그는 CDK가 *모든 *변경 사항을 자동으로 승인하고 실행함을 의미합니다. 여기에는 CDK가 일반적으로 수동 검토가 필요한 것으로 플래그를 지정하는 변경 사항(예: IAM 정책 변경 또는 리소스 제거)이 포함됩니다. 프로덕션 환경에서 `--require-approval never` 플래그를 사용하기 전에 CDK 코드와 CI/CD 파이프라인이 잘 테스트되고 안전한지 확인합니다.<pre>ENV=<environment> IMAGETAG=<image_tag> ECR_ARN=<ecr_repo_arn> cdk deploy --require-approval never</pre> | DevOps | 

### GitHub Actions 워크플로를 사용하여 CI/CD 자동화
<a name="automate-ci-cd-using-github-actions-workflows"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 기능 브랜치를 생성하고 변경 사항을 추가합니다. | 이전에 생성한 복제된 리포지토리를 사용하고 기능 브랜치를 생성한 다음 애플리케이션 코드에 변경 사항을 추가합니다. 다음 명령을 사용합니다.<pre>git checkout -b <feature_branch><br />git add .<br />git commit -m "add your changes"<br />git push origin <feature_branch></pre>다음은 변경 사항의 예입니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html)GitHub Actions는 재사용 가능한 워크플로를 사용하고 CI/CD 파이프라인을 트리거합니다. | DevOps | 
| 변경 사항을 병합합니다. | 풀 요청을 생성하고 변경 사항을 기본으로 병합합니다. | DevOps | 

## 문제 해결
<a name="optimize-multi-account-serverless-deployments-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| `AccessDenied` 예를 들어 AWS 계정에 리소스를 배포할 때 오류가 발생합니다`AccessDenied: User not authorized to perform: "sts:AssumeRole"`. | 이 문제를 해결하려면 다음을 수행하여 교차 계정 권한을 확인합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | 
| 오래된 CDK 버전의 `undefined: awscdkStack` 오류와 같이 버전 불일치로 인한 호환성 문제입니다. | 이 문제를 해결하려면 다음을 수행하여 AWS CDK 및 Go의 필수 버전을 사용하고 있는지 확인합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | 
| 예를 들어 잘못된 YAML 구성 또는 `Permission denied` 보호된 브랜치`Error: No such file or directory`로 인한 CI/CD 파이프라인 실패입니다. | GitHub Actions 구성 관련 문제를 해결하려면 재사용 가능한 워크플로가 올바르게 참조되고 구성되어 있는지 확인합니다. | 

## 관련 리소스
<a name="optimize-multi-account-serverless-deployments-resources"></a>

**AWS 리소스**
+ [AWS 보안, 자격 증명 및 규정 준수를 위한 모범 사례](https://aws.amazon.com/architecture/security-identity-compliance/)
+ [AWS CDK 워크숍](https://cdkworkshop.com/60-go.html)
+ [AWS 클라우드 개발 키트 라이브러리](https://pkg.go.dev/github.com/aws/aws-cdk-go/awscdk/v2)
+ [컨테이너 이미지를 사용하여 Lambda 함수 생성](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html)
+ [Amazon Elastic Container Registry의 Identity and Access Management](https://docs.aws.amazon.com/AmazonECR/latest/userguide/security-iam.html)
+ [C\$1에서 AWS CDK 사용하기](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-go.html)

**기타 리소스**
+ [Amazon Web Services에서 OpenID Connect 구성](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)(GitHub 설명서)
+ [Lambda 설명서](https://golang.org/doc/)
+ [GitHub Actions 빠른 시작](https://docs.github.com/en/actions/writing-workflows/quickstart)(GitHub 설명서)
+ [워크플로 재사용](https://docs.github.com/en/actions/sharing-automations/reusing-workflows)(GitHub 설명서)

# GitHub Actions를 사용하여 AWS CloudFormation 템플릿을 기반으로 AWS Service Catalog 제품 프로비저닝
<a name="provision-aws-service-catalog-products-using-github-actions"></a>

*Ashish Bhatt와 Ruchika Modi, Amazon Web Services*

## 요약
<a name="provision-aws-service-catalog-products-using-github-actions-summary"></a>

이 패턴은 [AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html) 제품 및 포트폴리오를 사용하여 팀 AWS 서비스 간에 표준화되고 규정을 준수하는를 프로비저닝하는 간소화된 접근 방식을 조직에 제공합니다.는 기본 네트워크 인프라를 프로비저닝하기 위해 Service Catalog 제품 및 포트폴리오의 필수 구성 요소를 결합하는 데 [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 도움이 됩니다 AWS 클라우드. 또한이 패턴은 [GitHub Actions](https://github.com/features/actions)를 사용하여 코드형 인프라(IaC)를 자동화된 개발 워크플로에 통합하여 DevOps 관행을 촉진합니다.

AWS Service Catalog 를 통해 조직은에서 승인된 IT 서비스를 생성하고 관리하여 표준화 AWS, 중앙 집중식 제어, 셀프 서비스 프로비저닝 및 비용 관리와 같은 이점을 제공할 수 있습니다. GitHub Actions를 통해 Service Catalog 포트폴리오 및 제품의 배포를 자동화함으로써 기업은 다음을 수행할 수 있습니다.
+ 일관되고 반복 가능한 배포를 달성합니다.
+ IaC용 버전 관리를 사용합니다.
+ 클라우드 리소스 관리를 기존 개발 워크플로와 통합합니다.

이 조합은 클라우드 운영을 간소화하고 규정 준수를 적용하며 승인된 서비스의 제공을 가속화하는 동시에 수동 오류를 줄이고 전반적인 효율성을 개선합니다.

## 사전 조건 및 제한 사항
<a name="provision-aws-service-catalog-products-using-github-actions-prereqs"></a>

**사전 조건**
+ 활성 AWS 계정 
+ GitHub 리포지토리의 코드에 액세스할 수 있습니다.
+  AWS CloudFormation 및에 대한 기본 이해 AWS Service Catalog
+ CloudFormation 템플릿을 호스팅하기 위한 Amazon Simple Storage Service(Amazon S3) 버킷
+ GitHub와 간의 연결에 `github-actions` 사용되는 라는 AWS Identity and Access Management (IAM) 역할 AWS

**제한 사항**
+ 이 패턴의 재사용 가능한 코드는 GitHub Actions에서만 테스트되었습니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) 섹션을 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

**제품 버전**

이 패턴의 솔루션은 다음 [GitHub Marketplace](https://github.com/marketplace) 작업과 해당 버전을 사용하여 생성되었습니다.
+ `actions/checkout@v4`
+ `aws-actions/configure-aws-credentials@v2`
+ `aws-actions/aws-cloudformation-github-deploy@v1.2.0`

## 아키텍처
<a name="provision-aws-service-catalog-products-using-github-actions-architecture"></a>

다음 다이어그램은 이 솔루션의 아키텍처를 보여 줍니다.

![\[GitHub Actions를 사용하여 CloudFormation 템플릿을 기반으로 Service Catalog 제품을 프로비저닝합니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/49f82fa7-0c74-4581-bf92-95505dca264c/images/a13c7b41-534e-4a9e-bdca-2974fa40a49a.png)


1. 관리자 또는 플랫폼 엔지니어는 표준화된 CloudFormation 템플릿을 GitHub 리포지토리로 푸시하여 템플릿을 유지합니다. GitHub 리포지토리에는 GitHub Actions를 AWS Service Catalog 사용한 프로비저닝을 자동화하는 워크플로도 포함되어 있습니다.

1. GitHub Actions는 OpenID Connect(OIDC) 공급자를 AWS 클라우드 사용하여 Service Catalog를 프로비저닝하는에 연결하는 워크플로를 트리거합니다.

1. Service Catalog에는 개발자가 표준화된 AWS 리소스를 프로비저닝하는 데 직접 사용할 수 있는 포트폴리오와 제품이 포함되어 있습니다. 이 패턴은 Virtual Private Cloud(VPCs), 서브넷, NAT 및 인터넷 게이트웨이, 라우팅 테이블과 같은 AWS 리소스를 번들링합니다.

1. 개발자가 Service Catalog 제품을 생성하면 Service Catalog는 이를 사전 구성되고 표준화된 AWS 리소스로 변환합니다. 따라서 개발자는 개별 리소스를 프로비저닝하고 수동으로 구성할 필요가 없으므로 시간을 절약할 수 있습니다.

## 도구
<a name="provision-aws-service-catalog-products-using-github-actions-tools"></a>

**AWS 서비스**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, AWS 계정 및의 수명 주기 동안 리소스를 관리할 수 있습니다 AWS 리전. 이는 제품 유형 중 하나로 쉽게 사용할 수 있는 코드형 인프라(IaC) 서비스입니다 AWS Service Catalog.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 액세스를 인증하고 사용할 수 있는 권한을 부여받은 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다.
+ [AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/getstarted.html)는 승인된 IT 서비스의 카탈로그를 중앙에서 관리할 수 있도록 지원합니다 AWS. 최종 사용자는 조직에서 규정한 제약에 따라, 필요에 따라 승인된 IT 서비스만 신속하게 배포할 수 있습니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.

**기타**
+ [GitHub Actions](https://docs.github.com/en/actions)는 GitHub 리포지토리와 긴밀하게 통합된 지속적 통합 및 지속적 전달(CI/CD) 플랫폼입니다. GitHub Actions를 사용하여 빌드, 테스트 및 배포 파이프라인을 자동화할 수 있습니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub의 [service-catalog-with-github-actions](https://github.com/aws-samples/service-catalog-with-github-actions) 리포지토리에서 사용할 수 있습니다. 코드 리포지토리에는 다음 파일이 포함되어 있습니다.
+ `github/workflows`:
  + `e2e-test.yaml` -이 파일은 [재사용 가능한 워크플로](https://docs.github.com/en/actions/sharing-automations/reusing-workflows)인 `workflow.yaml`을 직접적으로 호출합니다. 이 워크플로는 브랜치에 커밋 및 푸시가 발생하는 즉시 트리거됩니다.
  + `workflow.yaml` -이 파일에는이 솔루션의 재사용 가능한 워크플로가 포함되어 있으며 트리거`workflow_call`로 로 구성됩니다. 재사용 가능한 워크플로로서 `workflow.yaml`은 다른 워크플로에서 직접적으로 호출할 수 있습니다.
+ `templates`:
  + `servicecatalog-portfolio.yaml` -이 CloudFormation 템플릿에는 Service Catalog 포트폴리오 및 Service Catalog 제품을 프로비저닝하는 리소스가 포함되어 있습니다. 템플릿에는 Service Catalog 포트폴리오 및 제품을 프로비저닝하는 데 사용되는 파라미터 세트가 포함되어 있습니다. 하나의 파라미터는 템플릿`vpc.yaml`이 업로드되는 Amazon S3 파일 URL을 허용합니다. 이 패턴에는 AWS 리소스를 프로비저닝할 `vpc.yaml` 파일이 포함되어 있지만 파라미터 S3 파일 URL을 구성에 사용할 수도 있습니다.
  + `vpc.yaml` -이 CloudFormation 템플릿에는 Service Catalog 제품에 추가할 AWS 리소스가 포함되어 있습니다. AWS 리소스에는 VPCs, 서브넷, 인터넷 게이트웨이, NAT 게이트웨이 및 라우팅 테이블이 포함됩니다. `vpc.yaml` 템플릿은 서비스 카탈로그 제품 및 포트폴리오 템플릿과 함께 CloudFormation 템플릿을 사용하는 방법의 예입니다.

## 모범 사례
<a name="provision-aws-service-catalog-products-using-github-actions-best-practices"></a>
+  AWS Service Catalog 설명서의에 [대한 보안 모범 사례를 AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/security-best-practices.html) 참조하세요.
+ [GitHub 설명서의 GitHub 작업에 대한 보안 강화](https://docs.github.com/en/actions/security-for-github-actions/security-guides/security-hardening-for-github-actions)를 참조하세요. GitHub 

## 에픽
<a name="provision-aws-service-catalog-products-using-github-actions-epics"></a>

### 로컬 워크스테이션 설정
<a name="set-up-local-workstation"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 로컬 워크스테이션에 Git을 설정합니다. | 로컬 워크스테이션에 Git을 설치하고 구성하려면 Git 설명서의 [시작하기 - Git 설치](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 지침을 사용합니다. | 앱 개발자 | 
| GitHub 프로젝트 리포지토리를 복제합니다. | GitHub 프로젝트 리포지토리를 복제하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | DevOps 엔지니어 | 

### OIDC 공급자 설정
<a name="set-up-the-oidc-provider"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| OIDC 공급자를 구성합니다. |  AWS 자격 증명을 수명이 긴 GitHub 보안 암호로 저장할 필요 AWS없이 GitHub Actions 워크플로가의 리소스에 액세스할 수 있도록 하는 OpenID Connect(OIDC) 공급자를 생성합니다. 지침은 GitHub 설명서의 [Amazon Web Services에서 OpenID Connect 구성](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)을 참조하세요.OIDC 공급자가 구성되면 [사전 요구](#provision-aws-service-catalog-products-using-github-actions-prereqs) 사항의 앞부분에서 `github-actions`언급한 IAM 역할의 신뢰 정책이 업데이트됩니다. | AWS 관리자, AWS DevOps, 일반 AWS | 

### GitHub 작업 파이프라인을 트리거하여 Service Catalog 포트폴리오 및 제품 배포
<a name="trigger-github-actions-pipeline-to-deploy-sc-portfolio-and-products"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `e2e-test.yaml` 업데이트 | `e2e-test.yaml` 파일은에서 재사용 가능한 워크플로를 트리거합니다`workflow.yaml`. 에서 다음 입력 파라미터의 값을 업데이트하고 검증합니다`e2e-test.yaml`.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | DevOps 엔지니어 | 

### 배포를 검증합니다.
<a name="validate-deployment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Service Catalog 리소스를 검증합니다. | Service Catalog 리소스를 검증하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | DevOps | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CloudFormation 스택을 삭제합니다. | CloudFormation 스택을 삭제하려면 다음 명령을 실행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html)자세한 내용은 CloudFormation 설명서의 [AWS CloudFormation 콘솔에서 스택 삭제](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html)를 참조하십시오. | AWS 관리자, DevOps 엔지니어 | 

## 문제 해결
<a name="provision-aws-service-catalog-products-using-github-actions-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| `e2e-test``Can't find 'action.yml', 'action.yaml' or 'Dockerfile' under '*/home/runner/work/service-catalog-with-github-actions/service-catalog-with-github-actions``Did you forget to run actions/checkout before running your local action?` | 올바른 리포지토리 설정이 활성화되어 있는지 확인하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | 

## 관련 리소스
<a name="provision-aws-service-catalog-products-using-github-actions-resources"></a>

**AWS 설명서**
+ [Service Catalog 개요](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/what-is_concepts.html)

**기타 리소스**
+ [워크플로를 트리거하는 이벤트 정보](https://docs.github.com/en/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows#about-events-that-trigger-workflows)(GitHub 설명서)
+ [워크플로 재사용](https://docs.github.com/en/actions/sharing-automations/reusing-workflows)(GitHub 설명서)

## 추가 정보
<a name="provision-aws-service-catalog-products-using-github-actions-additional"></a>

에[픽](#provision-aws-service-catalog-products-using-github-actions-epics)과 관련된 스크린샷을 보려면이 패턴의 GitHub 리포지토리에 있는 **이미지 **폴더로 이동합니다. 다음 스크린샷을 사용할 수 있습니다.
+ [AWS Service Catalog 포트폴리오, 관리 섹션](https://github.com/aws-samples/service-catalog-with-github-actions/blob/main/images/SC_portfolio.png)
+ [AWS Service Catalog 제품, 관리 섹션](https://github.com/aws-samples/service-catalog-with-github-actions/blob/main/images/SC_Product.png)
+ [AWS Service Catalog 제품, 사용자/프로비저닝 섹션](https://github.com/aws-samples/service-catalog-with-github-actions/blob/main/images/SC_Product_User.png)

# 역할 벤딩 머신 솔루션을 배포하여 최소 권한 IAM 역할 프로비저닝
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution"></a>

*Benjamin Morris, Nima Fotouhi, Aman Kaur Gandhi, Chad Moon, Amazon Web Services*

## 요약
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-summary"></a>

파이프라인에 대한 범위 초과 AWS Identity and Access Management (IAM) 역할 권한은 조직에 불필요한 리스크를 초래할 수 있습니다. 개발자는 개발 중에 광범위한 권한을 부여하지만 코드 문제 해결 후 권한 범위를 좁히지 않는 경우가 있습니다. 이로 인해 강력한 역할이 비즈니스 요구 없이 존재하며 보안 엔지니어가 검토하지 않았을 수 있는 문제가 발생합니다.

이 패턴은이 문제에 대한 해결책, 즉 역할 벤딩 머신(RVM)을 제공합니다. RVM은 안전한 중앙 집중식 배포 모델을 사용하여 개발자의 노력을 최소화하면서 개별 GitHub 리포지토리의 파이프라인에 최소 권한 IAM 역할을 프로비저닝하는 방법을 보여줍니다. RVM은 중앙 솔루션이므로 필요한 검토자가 변경 사항을 승인하도록 보안 팀을 구성할 수 있습니다. 이 접근 방식을 사용하면 보안이 과도하게 권한이 부여된 파이프라인 역할 요청을 거부할 수 있습니다.

RVM은 Terraform 코드를 입력으로 받아 파이프라인 지원 IAM 역할을 출력으로 생성합니다. 필수 입력은 AWS 계정 ID, GitHub 리포지토리 이름 및 권한 정책입니다. RVM은 이러한 입력을 사용하여 역할의 신뢰 정책 및 권한 정책을 생성합니다. 결과 신뢰 정책은 지정된 GitHub 리포지토리가 역할을 수임하고 파이프라인 작업에 사용할 수 있도록 허용합니다.

RVM은 IAM 역할(부트스트랩 중에 구성됨)을 사용합니다. 이 역할에는 조직의 각 계정에서 role-provisioning-role을 수임할 수 있는 권한이 있습니다. 역할은 AWS Control Tower Account Factory for Terraform(AFT) 또는 AWS CloudFormation StackSets를 통해 구성됩니다. role-provisioning-roles는 실제로 개발자를 위한 파이프라인 역할을 생성하는 역할입니다.

## 사전 조건 및 제한 사항
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ GitHub 작업을 통해 코드형 인프라(IaC)를 배포하는 데 사용되는 GitHub 조직입니다. (GitHub Enterprise/Premium/Ultimate는 필요하지 *않습니다*** **.)
+ 다중 계정 AWS 환경. 이 환경은 참여할 필요가 없습니다 AWS Organizations.
+ 모든에 IAM 역할을 배포하는 메커니즘입니다 AWS 계정 (예: AFT 또는 CloudFormation StackSets).
+ Terraform 버전 1.3 이상 [설치 및 구성](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)
+ Terraform AWS Provider 버전 4 이상이 [설치](https://github.com/hashicorp/terraform-provider-aws/releases) 및 [구성](https://developer.hashicorp.com/terraform/language/providers/configuration)되었습니다.

**제한 사항 **
+ 이 패턴의 코드는 GitHub Actions 및 Terraform에 고유합니다. 그러나 패턴의 일반적인 개념은 다른 지속적 통합 및 전달(CI/CD) 프레임워크에서 재사용할 수 있습니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전별 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)를 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-architecture"></a>

이 다이어그램은 이 패턴의 워크플로우를 보여줍니다.

![\[GitHub 작업을 사용하여 IAM 역할 생성 및 배포를 자동화하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/215c590e-0c84-411d-be6e-b1739f1e19d2/images/82fcdc9f-9576-4e7c-b7fe-b45046ba79d2.png)


역할 자동 판매기의 일반적인 사용에 대한 워크플로는 다음 단계로 구성됩니다.

1. 개발자는 새로 요청된 IAM 역할에 대한 Terraform 코드가 포함된 코드를 RVM GitHub 리포지토리로 푸시합니다. 이 작업은 RVM GitHub Actions 파이프라인을 트리거합니다.

1. 파이프라인은 OpenID Connect(OIDC) 신뢰 정책을 사용하여 RVM 역할 수임 역할을 수임합니다.

1. RVM 파이프라인이 실행되면 개발자의 새 IAM 역할을 프로비저닝하는 계정에서 RVM 워크플로 역할을 수임합니다. (RDM 워크플로 역할은 AFT 또는 CloudFormation StackSets.)

1. RVM은 적절한 권한과 신뢰로 개발자의 IAM 역할을 생성하므로 다른 애플리케이션 파이프라인에서 역할을 수임할 수 있습니다.

1. 앱 개발자는이 RVM 프로비저닝 역할을 수임하도록 앱 파이프라인을 구성할 수 있습니다.

생성된 역할에는 개발자가 요청한 권한과 `ReadOnlyAccess` 정책이 포함됩니다. 역할은 개발자가 지정한 리포지토리의 `main`브랜치에 대해 실행되는 파이프라인에서만 수임할 수 있습니다. 이 접근 방식은 역할을 사용하기 위해 브랜치 보호 및 검토가 필요할 수 있도록 하는 데 도움이 됩니다.

**자동화 및 규모 조정**

최소 권한 권한은 프로비저닝되는 각 역할에 대한 세부 정보에 주의를 기울여야 합니다. 이 모델은 이러한 역할을 생성하는 데 필요한 복잡성을 줄여 개발자가 추가 학습이나 노력 없이 필요한 역할을 생성할 수 있도록 합니다.

## 도구
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-tools"></a>

**AWS 서비스**
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 액세스를 인증하고 사용할 수 있는 권한을 부여받은 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다.
+ [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)는 여러을 생성하여 중앙에서 관리하는 조직 AWS 계정 으로 통합하는 데 도움이 되는 계정 관리 서비스입니다.

**기타 도구**
+ [Git](https://git-scm.com/docs)은 오픈 소스 분산 버전 제어 시스템입니다. 여기에는 [조직 계정을](https://docs.github.com/en/get-started/learning-about-github/types-of-github-accounts#organization-accounts) 생성하는 기능이 포함됩니다.
+ [GitHub Actions](https://docs.github.com/en/actions/writing-workflows/quickstart)는 GitHub 리포지토리와 긴밀하게 통합된 지속적 통합 및 지속적 전달(CI/CD) 플랫폼입니다. GitHub Actions를 사용하여 빌드, 테스트 및 배포 파이프라인을 자동화할 수 있습니다.
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [gfs-mainframe-patterns](https://github.com/aws-samples/role-vending-machine) 저장소에서 사용할 수 있습니다.

## 모범 사례
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-best-practices"></a>
+ **올바른 방법을 쉽고 어려운 방법으로 만들기 **- 올바른 작업을 쉽게 수행할 수 있습니다. 개발자가 RVM 프로비저닝 프로세스에 어려움을 겪고 있는 경우 다른 수단을 통해 역할을 생성하려고 할 수 있으며, 이는 RVM의 핵심 특성을 약화시킵니다. 보안 팀이 RVM을 안전하고 효과적으로 사용하는 방법에 대한 명확한 지침을 제공하는지 확인하세요.

  또한 개발자가 잘못된 일을 하기 어렵게 만들어야 합니다. 서비스 제어 정책(SCPs) 또는 권한 경계를 사용하여 다른 역할을 생성할 수 있는 역할을 제한합니다. 이 접근 방식은 역할 생성을 RVM 및 기타 신뢰할 수 있는 소스로만 제한하는 데 도움이 될 수 있습니다.
+ **좋은 예시 제공** - 불가피하게 일부 개발자는 RVM 리포지토리의 기존 역할을 새 역할에 권한을 부여하기 위한 비공식 템플릿으로 조정합니다. 복사할 수 있는 최소 권한 예시가 있는 경우 개발자가 광범위하고 와일드카드가 많은 권한을 요청할 위험을 줄일 수 있습니다. 와일드카드가 많은 권한이 높은 역할로 시작하는 경우 시간이 지남에 따라이 문제가 곱해질 수 있습니다.
+ **명명 규칙 및 조건 사용 **- 개발자가 애플리케이션이 생성할 모든 리소스 이름을 알지 못하더라도 명명 규칙을 사용하여 역할 권한을 제한해야 합니다. 예를 들어 Amazon S3 버킷을 생성하는 경우 리소스 키의 값은 해당 이름과 일치하는 버킷 이외의 권한이 `arn:aws:s3:::myorg-myapp-dev-*` 역할에 없도록와 같을 수 있습니다. IAM 정책을 통해 명명 규칙을 적용하면 명명 규칙 준수를 개선할 수 있는 추가적인 이점이 있습니다. 일치하지 않는 리소스는 생성할 수 없기 때문에 이러한 개선이 발생합니다.
+ **풀 요청(PR) 검토 필요** - RVM 솔루션의 가치는 새 파이프라인 역할을 검토할 수 있는 중앙 위치를 생성하는 것입니다. 그러나이 설계는 안전한 고품질 코드가 RVM에 커밋되도록 하는 데 도움이 되는 가드레일이 있는 경우에만 유용합니다. 코드를 배포하는 데 사용되는 브랜치(예: `main`)를 직접 푸시로부터 보호하고 해당 브랜치를 대상으로 하는 병합 요청에 대한 승인이 필요합니다.
+ **읽기 전용 역할 구성 -** 기본적으로 RVM은 요청된 각 역할의 `readonly` 버전을 프로비저닝합니다. 이 역할은 파이프라인 워크플로와 같이 데이터를 쓰지 않는 CI/CD `terraform plan` 파이프라인에서 사용할 수 있습니다. 이 접근 방식은 읽기 전용 워크플로가 잘못 작동하는 경우 원치 않는 변경을 방지하는 데 도움이 됩니다.

  기본적으로 AWS 관리형 `ReadOnlyAccess` 정책은 읽기 전용 역할과 읽기-쓰기 역할 모두에 연결됩니다. 이 정책은 필요한 권한을 결정할 때 반복의 필요성을 줄이지만 일부 조직에서는 지나치게 허용적일 수 있습니다. 원하는 경우 Terraform 코드에서 정책을 제거할 수 있습니다.
+ 최소 권한 원칙을 준수하고 작업을 수행하는 데 필요한 최소 권한을 부여하세요. 자세한 내용은 IAM 설명서의 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv) 및 [보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)를 참조하세요.

## 에픽
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-epics"></a>

### 환경 준비
<a name="prepare-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 샘플 리포지토리를 GitHub 조직에 복사합니다. | 니즈에 맞게 조정할 수 있도록 이 패턴의 리포지토리를 [복제](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)하거나 이 리포지토리를 GitHub 조직에 [포크](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo)합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html) | DevOps 엔지니어 | 
| RVM에 AWS 계정 대한를 결정합니다. | RVM에 AWS 계정 사용할 인프라 배포를 결정합니다. 관리 또는 루트 계정을 사용하지 마세요. | 클라우드 아키텍트 | 
| (선택 사항) 조직의 파이프라인이 PRs 생성하도록 허용합니다. | 이 단계는 `generate_providers_and_account_vars` 워크플로가 PRs을 생성하도록 허용하려는 경우에만 필요합니다.조직의 파이프라인이 PRs을 생성하도록 허용하려면 다음 단계를 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html)자세한 내용은 GitHub 문서의 [Signing up for a new GitHub account](https://docs.github.com/en/enterprise-server@3.10/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository#preventing-github-actions-from-creating-or-approving-pull-requests)를 참조하십시오. | DevOps 엔지니어 | 
| RVM 계정에 읽기 전용 권한을 부여합니다. | 관리 계정에서 RVM 계정에 읽기 전용 권한을 부여하는 위임 정책을 생성합니다. 이렇게 `generate_providers_and_account_vars.py` 하면 스크립트가 실행될 때 RVM GitHub 워크플로가 AWS 조직의 계정 목록을 동적으로 가져올 수 있습니다.다음 코드를 사용하고를 2단계에서 선택한 AWS 계정 ID`<YOUR RVM Account ID>`로 바꿉니다.<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Sid": "Statement",<br />      "Effect": "Allow",<br />      "Principal": {<br />        "AWS": "arn:aws:iam::<YOUR RVM Account ID>:root"<br />      },<br />      "Action": [<br />        "organizations:ListAccounts",<br />        "organizations:DescribeOrganization",<br />        "organizations:DescribeOrganizationalUnit",<br />        "organizations:ListRoots",<br />        "organizations:ListAWSServiceAccessForOrganization",<br />        "organizations:ListDelegatedAdministrators"<br />      ],<br />      "Resource": "*"<br />    }<br />  ]<br />}</pre> | 클라우드 관리자 | 
| 샘플 리포지토리에서 기본값을 업데이트합니다. | 특정 환경에서 작동하도록 RVM을 구성하려면 다음을 AWS 리전수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html) | DevOps 엔지니어 | 

### 인프라 초기화
<a name="initialize-infrastructure"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| RVM 리포지토리를 부트스트랩합니다. | 이 단계는 RVM 파이프라인 자체에서 사용하는 OIDC 신뢰 및 IAM 역할을 생성하여 다른 역할의 운영 및 판매를 시작하는 데 필요합니다.RVM 계정의 컨텍스트에서 `scripts/bootstrap` 디렉터리에서 `terraform apply` 명령을 수동으로 실행합니다. 변수 설명서에 따라 필요한 값을 입력합니다. | DevOps 엔지니어 | 

### 기본 연산 구성
<a name="configure-operations"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 모든 계정에 `github-workflow-rvm` 및 `github-workflow-rvm-readonly` 역할을 배포합니다. | AFT 또는 StackSets와 같이 조직의 관행에 맞는 배포 방법을 선택합니다. 이 방법을 사용하여 `scripts/assumed_role/main.tf` 파일의 두 IAM 역할(기본 이름 `github-workflow-rvm` 및 `github-workflow-rvm-readonly`)을 RVM이 파이프라인 역할을 생성할 수 있게 하려는 각 계정에 배포합니다.이러한 IAM 역할에는 RVM 계정의 역할 수임 역할(또는 이에 `readonly` 상응하는 역할)이 이를 수임하도록 허용하는 신뢰 정책이 있습니다. 또한 역할에는와 일치하는 역할을 읽고 쓸 수 있도록 허용하는 IAM 권한 정책이 있습니다(`readonly`역할을 사용하지 않는 경우). `github-workflow-role-*`  | 관리자 | 
| 워크플로를 실행합니다. | 파이프라인 역할을 생성할 준비가 되도록 RVM을 구성하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html)워크플로가 완료되면 RVM은 다음을 수행할 준비가 된 것입니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html) | DevOps 엔지니어 | 

## 문제 해결
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| RVM을 사용하여 역할을 생성했지만 GitHub가 이를 수임할 수 없습니다. | GitHub 리포지토리의 이름이 `github_workflow_roles` 모듈에 제공된 이름과 일치하는지 확인합니다. 역할은 하나의 리포지토리만 수임할 수 있도록 범위가 지정됩니다.마찬가지로 GitHub 파이프라인에 사용된 브랜치가 `github_workflow_roles` 모듈에 제공된 브랜치의 이름과 일치하는지 확인합니다. 일반적으로 쓰기 권한이 있는 RVM 생성 역할은 `main`브랜치로 범위가 지정된 워크플로(즉,에서 가져온 배포)에서만 사용할 수 있습니다`main`. | 
| 특정 리소스를 읽을 권한이 없기 때문에 읽기 전용 역할이 파이프라인을 실행하지 못하고 있습니다. | `ReadOnlyAccess` 정책은 광범위한 읽기 전용 권한을 제공하지만 정책에는 일부 읽기 작업(예: 특정 AWS Security Hub CSPM 작업)이 없습니다.`github-workflow-roles` 모듈의 `inline_policy_readonly` 파라미터를 사용하여 특정 작업 권한을 추가할 수 있습니다. | 

## 관련 리소스
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-resources"></a>
+ [AWS CloudFormation StackSets 사용 모범 사례](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-bestpractices.html)
+ [여러 계정을 사용하여 AWS 환경 구성](https://docs.aws.amazon.com/whitepapers/latest/organizing-your-aws-environment/organizing-your-aws-environment.html)
+ [AWS Control Tower Account Factory for Terraform(AFT) 개요](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html)
+ [정책 모범 사례](https://docs.aws.amazon.com/codepipeline/latest/userguide/security_iam_service-with-iam-policy-best-practices.html) 

## 추가 정보
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-additional"></a>

**GitHub 환경 사용**

GitHub 환경은 역할 액세스를 위한 브랜치 기반 제한에 대한 대체 접근 방식입니다. GitHub 환경을 사용하려는 경우 IAM 신뢰 정책의 추가 조건에 대한 구문의 예는 다음과 같습니다. 이 구문은 GitHub 작업이 `Production` 환경에서 실행 중인 경우에만 역할을 사용할 수 있도록 지정합니다.

```
"StringLike": {
    "token.actions.githubusercontent.com:sub": "repo:octo-org/octo-repo:environment:Production"
}
```

예시 구문은 다음 자리 표시자 값을 사용합니다.
+ `octo-org`는 GitHub 조직 이름입니다.
+ `octo-repo` 리포지토리의 이름입니다.
+ `Production`는 특정 GitHub 환경 이름입니다.

# Amazon CloudWatch 지표를 CSV 파일에 게시
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file"></a>

*Abdullahi Olaoye, Amazon Web Services*

## 요약
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-summary"></a>

이 패턴은 Python 스크립트를 사용하여 Amazon CloudWatch 지표를 검색하고 측정치 정보를 쉼표로 구분된 값(CSV) 파일로 변환하여 가독성을 높입니다. 이 스크립트는 지표를 검색해야 하는 AWS 서비스를 필수 인수로 사용합니다. AWS 리전 및 AWS 보안 인증 프로필을 선택적 인수로 지정할 수 있습니다. 이러한 인수를 지정하지 않는 경우 스크립트는 스크립트가 실행되는 워크스테이션에 구성된 기본 리전 및 프로필을 사용합니다. 스크립트가 실행되면 동일한 디렉터리에 CSV 파일이 생성되어 저장됩니다.

이 패턴으로 제공된 스크립트 및 관련 파일은 *첨부* 섹션을 참조하세요.

## 사전 조건 및 제한 사항
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-prereqs"></a>

**사전 조건 **
+ Python 3.x
+ AWS Command Line Interface(AWS CLI)

**제한 사항 **

이 스크립트는 다음 AWS 서비스를 지원합니다.
+ AWS Lambda
+ Amazon Elastic Compute Cloud(Amazon EC2)
  + 기본적으로 스크립트는 Amazon Elastic Block Store(Amazon EBS) 볼륨 지표를 수집하지 않습니다. Amazon EBS 지표를 수집하려면 첨부된 `metrics.yaml` 파일을 수정해야 합니다.
+ Amazon Relational Database Service(Amazon RDS)
  + 하지만 스크립트는 Amazon Aurora를 지원하지 않습니다.
+ Application Load Balancer
+ Network Load Balancer
+ Amazon API Gateway

## 도구
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-tools"></a>
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)는 DevOps 엔지니어, 개발자, 사이트 신뢰성 엔지니어(SRE) 및 IT 관리자를 위해 구축된 모니터링 서비스입니다. CloudWatch는 애플리케이션을 모니터링하고 시스템 전반의 성능 변경 사항에 대응하며, 리소스 사용률을 최적화하고, 운영 상태에 대한 통합된 뷰를 확보하는 데 필요한 데이터와 실행 가능한 통찰력을 제공합니다. CloudWatch는 로그, 지표 및 이벤트의 형태로 모니터링 및 운영 데이터를 수집하고, AWS 및 온프레미스 서버에서 실행되는 AWS 리소스, 애플리케이션 및 서비스에 대한 통합된 뷰를 제공합니다.

## 에픽
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-epics"></a>

### 사전 조건 설치 및 구성
<a name="install-and-configure-the-prerequisites"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 사전 조건을 설치합니다. | 다음 명령을 실행합니다.<pre>$ pip3 install -r requirements.txt</pre> | 개발자 | 
| CLI를 구성합니다. | 다음 명령을 실행합니다. <pre>$ aws configure</pre> | 개발자 | 

### Python 스크립트 구성
<a name="configure-the-python-script"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 스크립트를 엽니다. | 스크립트의 기본 구성을 변경하려면 `metrics.yaml`을(를) 엽니다. | 개발자 | 
| 스크립트 기간을 설정합니다. | 이는 가져오는 기간입니다. 기본 기간은 5분(300초)입니다. 기간을 변경할 수 있지만 다음 제한 사항에 유의하세요. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/publish-amazon-cloudwatch-metrics-to-a-csv-file.html)그렇지 않으면 API 작업에서 데이터 포인트를 반환하지 않습니다. | 개발자 | 
| 스크립트 시간을 설정합니다. | 이 값은 가져오고자 하는 지표 시간을 지정합니다. 기본값은 1시간입니다. 며칠 간의 지표를 검색하려면 값을 시간 단위로 제공합니다. 예를 들어, 2일의 경우 48을 지정합니다. | 개발자 | 
| 스크립트의 통계 값을 변경합니다. | (선택 사항) 글로벌 통계 값은 `Average`이며, 이는 특정 통계 값이 할당되지 않은 지표를 가져올 때 사용됩니다. 스크립트는 통계 값 `Maximum`, `SampleCount` 및 `Sum`을(를) 지원합니다. | 개발자 | 

### Python 스크립트 실행
<a name="run-the-python-script"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 스크립트 실행. | 다음 명령을 사용합니다. <pre>$ python3 cwreport.py <service> </pre>서비스 값 목록과 선택적 `region ` 및 `profile ` 파라미터를 보려면 다음 명령을 실행합니다.<pre> $ python3 cwreport.py -h</pre>선택적 파라미터에 대한 자세한 내용은 *추가 정보* 섹션을 참조하세요. | 개발자 | 

## 관련 리소스
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-resources"></a>
+ [AWS CLI 구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ [Amazon CloudWatch 지표 사용](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html)
+ [Amazon CloudWatch 설명서](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)
+ [EC2 CloudWatch 지표](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/viewing_metrics_with_cloudwatch.html#ec2-cloudwatch-metrics)
+ [AWS Lambda 지표](https://docs.aws.amazon.com/lambda/latest/operatorguide/logging-metrics.html)
+ [Amazon RDS 지표](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-metrics.html#rds-cw-metrics-instance)
+ [Application Load Balancer 지표](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html)
+ [Network Load Balancer 지표](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-cloudwatch-metrics.html)
+ [Amazon API Gateway 지표](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-metrics-and-dimensions.html)

## 추가 정보
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-additional"></a>

**스크립트 사용**

```
$ python3 cwreport.py -h
```

**예제 구문**

```
python3 cwreport.py <service> <--region=Optional Region> <--profile=Optional credential profile>
```

**파라미터**
+ **서비스(필수)** - 스크립트를 실행하려는 서비스입니다. 스크립트는 현재 AWS Lambda, Amazon EC2, Amazon RDS, Application Load Balancer, Network Load Balancer 및 API Gateway 서비스를 지원합니다.
+ **리전(선택 사항)** - 지표를 가져올 AWS 리전입니다. 기본 리전은 `ap-southeast-1`입니다.
+ **프로필(선택 사항)** ‒ 사용할 AWS CLI의 명명된 프로필입니다. 이 파라미터를 지정하지 않으면 구성된 기본 보안 인증 프로필이 사용됩니다.

**예시**
+ 기본 리전 `ap-southeast-1` 및 기본 구성 보안 인증 정보를 사용하여 Amazon EC2 지표를 가져오려면: `$ python3 cwreport.py ec2`
+ 리전을 지정하고 API Gateway 지표를 가져오려면: `$ python3 cwreport.py apigateway --region us-east-1`
+ AWS 프로필을 지정하고 Amazon EC2 지표를 가져오려면: `$ python3 cwreport.py ec2 --profile testprofile`
+ Amazon EC2 지표를 가져올 리전과 프로필을 모두 지정하려면: `$ python3 cwreport.py ec2 --region us-east-1 --profile testprofile`

## 첨부
<a name="attachments-0a915a9d-2eef-4da1-8283-3cf4a115b3b2"></a>

이 문서와 관련된 추가 콘텐츠에 액세스하려면 [attachment.zip](samples/p-attach/0a915a9d-2eef-4da1-8283-3cf4a115b3b2/attachments/attachment.zip) 파일의 압축을 풉니다.

# AWS Lambda 자동화 AWS Managed Microsoft AD 를 사용하여 AWS 계정 에서의 Amazon EC2 항목 제거
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad"></a>

*Dr. Rahul Sharad Gaikwad and Tamilselvan P, Amazon Web Services*

## 요약
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-summary"></a>

Active Directory(AD)는 도메인 정보와 네트워크 서비스와의 사용자 상호 작용을 관리하는 Microsoft 스크립팅 도구입니다. 관리형 서비스 제공업체(MSPs) 사이에서 직원 자격 증명 및 액세스 권한을 관리하는 데 널리 사용됩니다. AD 공격자는 비활성 계정을 사용하여 조직을 해킹할 수 있으므로 비활성 계정을 찾아 일상적인 유지 관리 일정에 따라 비활성화하는 것이 중요합니다. 를 사용하면 Microsoft Active Directory를 관리형 서비스로 실행할 AWS Directory Service for Microsoft Active Directory수 있습니다. 이 패턴은 비활성 계정을 빠르게 찾고 제거하도록 AWS Lambda 자동화를 구성하는 데 도움이 될 수 있습니다.

조직에 다음 시나리오가 적용되는 경우이 패턴이 도움이 될 수 있습니다.
+ **중앙 집중식 AD 관리** - 조직에 AWS 계정각각 고유한 AD 배포가 있는 여러 개가 있는 경우 모든 계정에서 사용자 계정과 액세스 권한을 일관되게 관리하는 것이 어려울 수 있습니다. 계정 간 AD 정리 솔루션을 사용하면 중앙 집중식 방식으로 모든 AD 인스턴스에서 비활성 계정을 비활성화하거나 제거할 수 있습니다.
+ **AD 재구성 또는 마이그레이션** - 조직에서 AD 배포를 재구성하거나 마이그레이션하려는 경우 계정 간 AD 정리 솔루션을 사용하면 환경을 준비하는 데 도움이 될 수 있습니다. 솔루션은 불필요하거나 비활성인 계정을 제거하고, 마이그레이션 프로세스를 간소화하고, 잠재적 충돌 또는 문제를 줄이는 데 도움이 될 수 있습니다.

이 패턴을 사용하면 다음과 같은 이점을 얻을 수 있습니다.
+ 데이터베이스 및 서버 성능을 개선하고 비활성 계정에서 보안 취약성을 수정합니다.
+ AD 서버가 클라우드에서 호스팅되는 경우 비활성 계정을 제거하면 성능을 개선하는 동시에 스토리지 비용도 절감할 수 있습니다. 대역폭 요금과 컴퓨팅 리소스가 모두 떨어질 수 있으므로 월별 청구서가 감소할 수 있습니다.
+ 깨끗한 Active Directory를 사용하여 잠재적 공격자를 대피시킵니다.

## 사전 조건 및 제한 사항
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-prereqs"></a>

**사전 조건 **
+ 활성 상위 계정 AWS 계정 과 하나 이상의 하위 계정. 이 패턴에서 *상위 계정*은 Active Directory가 생성되는 곳입니다. *하위 계정*은 Windows 서버를 호스팅하고 상위 계정 Active Directory를 통해 조인됩니다.
+ 로컬 워크스테이션에 Git 설치 [https://git-scm.com/book/en/v2/Getting-Started-Installing-Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 및 구성.
+ Terraform은 로컬 워크스테이션에 [설치](https://learn.hashicorp.com/tutorials/terraform/install-cli) 및 구성되어 있습니다.
+ AWS Managed Microsoft AD 디렉터리는 상위 계정에 구성되고 모든 하위 계정과 공유됩니다. 자세한 내용은 *AWS Directory Service 관리 안내서*의 [자습서: 원활한 EC2 도메인 조인을 위한 AWS Managed Microsoft AD 디렉터리 공유](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_tutorial_directory_sharing.html)를 참조하세요.
+ 가상 프라이빗 클라우드(VPC) 피어링 연결 또는 AWS Directory Service (상위 계정)의 VPC와 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스(하위 계정)의 VPC 간에 사용할 수 있는 AWS Transit Gateway 연결입니다. 디렉터리 소유자와 디렉터리 소비자 계정간 VPC 피어링 연결 구성
+ 모든 상위 및 하위 계정에서 `EC2WindowsUserdata` 스크립트로 구성된 Windows 시스템입니다. 스크립트 파일은이 패턴의 [코드 리포지토리](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/tree/main/multiple-account-cleanup) 루트에서 사용할 수 있습니다.
+ 상위 계정에서 AWS Lambda 함수를 사용할 수 있도록 신뢰 정책으로 구성된 각 하위 계정에서 사용할 수 있는 교차 계정 AWS Identity and Access Management (IAM) 역할입니다. 자세한 내용은 [Amazon EventBridge 사용 설명서의 Amazon EventBridge AWS 계정 에서 사이의 이벤트 전송 및 수신](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEvents-CrossAccountEventDelivery.html)을 참조하세요. * EventBridge *
+ 상위 계정의 AWS Systems Manager 파라미터 스토어에서 사용할 수 있는 보안 암호 값은 다음과 같습니다.
  + `domainJoinUser` - 디렉터리 서비스의 사용자 이름
  + `domainJoinPassword` - 디렉터리 서비스의 암호

  보안 암호에 대한 자세한 내용은 *AWS Secrets Manager 사용 설명서*의 [AWS Secrets Manager 보안 암호 생성을](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html) 참조하세요.

**제한 사항 **
+ 하위 계정에서 리소스 생성은 Terraform으로 자동화되지 않습니다. 를 사용하여 AWS Management Console다음 리소스를 수동으로 생성해야 합니다.
  + Amazon EC2 종료 이벤트를 상위 계정으로 전송하는 Amazon EventBridge 규칙
  + 신뢰 정책이 있는 하위 계정에서 Amazon EC2 교차 계정 역할 생성
  + 하나 이상의 Transit Gateway 피어링 연결
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) 섹션을 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

**제품 버전**
+ [Terraform 버전 1.1.9 이상](https://developer.hashicorp.com/terraform/install)
+ [Terraform AWS Provider 버전 3.0 이상](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-3-upgrade)

## 아키텍처
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-architecture"></a>

다음 다이어그램은 솔루션의 상위 수준 아키텍처와 주요 구성 요소를 보여줍니다.

![\[Lambda 자동화를 사용하여 AWS 계정 전체에서 EC2 항목을 제거하는 프로세스입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/c397d873-e10d-44b6-8352-5f1380ab94ca/images/bd6c80a7-e490-47db-bd47-165314e1ea8a.png)


다음 다이어그램에서 프로세스를 보여 줍니다.

1. 하위 계정에서 EventBridge 규칙은 모든 Amazon EC2 종료 이벤트를 수집합니다. 규칙은 이러한 이벤트를 상위 계정에 있는 EventBridge로 보냅니다.

1. 상위 계정에서 EventBridge는 모든 이벤트를 수집하고 Lambda 함수를 트리거하는 규칙을 포함합니다`ADcleanup-Lambda`.

1. 상위 계정은 상위 또는 하위 계정에서 종료 이벤트를 수신하고 Lambda 함수를 트리거합니다.

1. Lambda 함수는 Python boto 모듈을 사용하여 Amazon EC2 Auto Scaling 그룹을 직접적으로 호출하고 임의의 인스턴스 ID를 가져옵니다. 인스턴스 ID는 Systems Manager 명령을 실행하는 데 사용됩니다.

1. Lambda 함수는 boto 모듈을 사용하여 Amazon EC2를 다시 직접적으로 호출합니다. Lambda 함수는 실행 중인 Windows 서버의 프라이빗 IP 주소를 가져와 임시 변수에 저장합니다. 5.1 및 5.2단계에서는 실행 중인 Windows EC2 인스턴스가 하위 계정에서 수집됩니다.

1. Lambda 함수는 Systems Manager를 다시 직접적으로 호출하여 AWS Directory Service에 연결된 컴퓨터 정보를 가져옵니다.

1.  AWS Systems Manager 문서는 Amazon EC2 Windows 서버에서 PowerShell 명령을 실행하여 AD에 연결된 컴퓨터의 프라이빗 IP 주소를 가져오는 데 도움이 됩니다. (Systems Manager 문서는 4단계에서 얻은 인스턴스 ID를 사용합니다.)

1. AD 도메인 사용자 이름과 암호는 AWS Systems Manager Parameter Store에 저장됩니다. AWS Lambda Systems Manager는 Parameter Store를 호출하고 AD에 연결하는 데 사용할 사용자 이름과 암호 값을 가져옵니다.

1. Systems Manager 문서를 사용하면 4단계에서 앞서 얻은 인스턴스 ID를 사용하여 Amazon EC2 Windows 서버에서 PowerShell 스크립트가 실행됩니다.

1. Amazon EC2는 PowerShell 명령을 AWS Directory Service 사용하여에 연결하고 사용 중이거나 비활성 상태인 컴퓨터를 제거합니다.

## 도구
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-tools"></a>

**AWS 서비스**
+ [AWS Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/what_is.html)는 Amazon Elastic Compute Cloud(Amazon EC2), SQL Server용 Amazon Relational Database Service(RDS), Windows File Server용 Amazon FSx AWS 서비스 등 다른와 함께 Microsoft Active Directory(AD)를 사용하는 여러 가지 방법을 제공합니다.
+ [AWS Directory Service for Microsoft Active Directory](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_microsoft_ad.html)를 사용하면 디렉터리 인식 워크로드 및 AWS 리소스가에서 Microsoft Active Directory를 사용할 수 있습니다 AWS 클라우드.
+ [Amazon Elastic Compute Cloud(Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)는 AWS 클라우드에서 확장 가능한 컴퓨팅 용량을 제공합니다. 필요한 만큼 가상 서버를 시작하고 빠르게 스케일 업하거나 스케일 다운할 수 있습니다.
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)는 애플리케이션을 다양한 소스의 실시간 데이터와 연결할 수 있는 서버리스 이벤트 버스 서비스입니다. 예를 들어 AWS Lambda 함수, API 대상을 사용하는 HTTP 호출 엔드포인트 또는 다른의 이벤트 버스 등이 있습니다 AWS 계정.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS 리소스에 대한 액세스를 인증하고 사용할 수 있는 권한을 부여받은 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다. IAM을 사용하면의 서비스 및 리소스에 액세스할 수 있는 사용자 또는 대상을 지정하고 AWS, 세분화된 권한을 중앙에서 관리하고, 액세스를 분석하여 권한을 세분화할 수 있습니다 AWS.
+ [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 리소스를 대규모로 안전하게 관리하는 데 도움이 됩니다.
+ [AWS Systems Manager 문서는](https://docs.aws.amazon.com/systems-manager/latest/userguide/documents.html) Systems Manager가 관리형 인스턴스에서 수행하는 작업을 정의합니다. Systems Manager에는 런타임에 파라미터를 지정하여 사용할 수 있는 사전 구성 문서가 100개 이상 포함되어 있습니다.
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)는의 기능이며 구성 데이터 관리 AWS Systems Manager 및 보안 암호 관리를 위한 안전한 계층적 스토리지를 제공합니다.

**기타 도구**
+ [HashiCorp Terraform](https://www.terraform.io/docs)은 코드를 사용하여 클라우드 인프라 및 리소스를 프로비저닝하고 관리하는 데 도움이 되는 코드형 인프라(IaC) 도구입니다.
+ [PowerShell](https://learn.microsoft.com/en-us/powershell/)은 Windows, Linux 및 macOS에서 실행되는 마이크로소프트 자동화 및 구성 관리 프로그램입니다.
+ [Python](https://www.python.org/)은 범용 컴퓨터 프로그래밍 언어입니다.

**코드 리포지토리**

이 패턴의 코드는 [aws-codepipeline-terraform-cicdsamples](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/tree/main/multiple-account-cleanup) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-best-practices"></a>
+ **도메인을 자동 조인** Directory Service 도메인의 일부가 될 Windows 인스턴스를 시작할 때 나중에 인스턴스를 수동으로 추가하는 대신 인스턴스 생성 프로세스 중에 도메인에 조인합니다. 새로운 인스턴스를 시작할 때 [**Domain join directory**]에 대한 올바른 디렉터리를 선택하기만 하면 도메인을 자동으로 조인할 수 있습니다. 자세한 내용은 *Directory Service 관리 안내서*의 [ Amazon EC2 Windows 인스턴스를 AWS Managed Microsoft AD Active Directory에 원활하게 조인을 참조하세요](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/launching_instance.html).
+ **사용하지 않는 계정을 삭제합니다. ** AD에서 사용한 적이 없는 계정을 찾는 것이 일반적입니다. 시스템에 남아 있는 비활성화된 계정 또는 비활성 계정과 마찬가지로, 무시된 미사용 계정은 AD 시스템의 속도를 늦추거나 조직을 데이터 침해에 취약하게 만들 수 있습니다.
+ **Active Directory 정리를 자동화합니다. ** 보안 리스크를 완화하고 더 이상 사용되지 않는 계정이 AD 성능에 영향을 미치지 않도록 AD 정리를 정기적으로 수행해야 합니다. 스크립트를 작성하여 대부분의 AD 관리 및 정리 작업을 수행할 수 있습니다. 예시 작업에는 비활성화 및 비활성 계정 제거, 빈 및 비활성 그룹 삭제, 만료된 사용자 계정 및 암호 찾기가 포함됩니다.

## 에픽
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-epics"></a>

### 하위 계정 설정
<a name="set-up-child-accounts"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 하위 계정에서 교차 계정 역할을 생성합니다. | 하위 계정에서 교차 계정 역할을 생성하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 엔지니어 | 
| 하위 계정에서 이벤트 규칙을 생성합니다. | 각 하위 계정에 대한 EventBridge 규칙을 생성하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html)자세한 내용을 알아보려면 Amazon EventBridge 사용 설명서**의 [이벤트에 응답하는 Amazon EventBridge 규칙 생성](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule.html)을 참조하세요. | DevOps 엔지니어 | 
| EC2 인스턴스를 생성하고 AD에 조인합니다. | Windows용 EC2 인스턴스를 생성하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 엔지니어 | 

### 로컬 워크스테이션 설정
<a name="set-up-the-local-workstation"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 프로젝트 폴더를 생성하고 파일을 추가합니다. | 리포지토리를 복제하고 프로젝트 폴더를 생성하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 엔지니어 | 
| `adcleanup.zip` 파일을 빌드합니다. | 다음 명령을 실행하여 파일 압축을 해제합니다.`zip -r adcleanup.zip lambda_function.py` | DevOps 엔지니어 | 

### Terraform을 사용하여 대상 아키텍처 프로비저닝
<a name="provision-the-target-architecture-using-the-terraform-configuration"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Terraform 변수 값을 입력합니다. | 하위 계정의 경우 `terraform.tfvars` 파일에 다음 `arn` 변수 값을 문자열 유형으로 제공합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 엔지니어 | 
| Terraform 구성을 초기화합니다. | 다음 명령을 입력하여 Terraform 구성 파일이 포함된 작업 디렉토리를 초기화합니다.`terraform init` | DevOps 엔지니어 | 
| 변경 사항을 미리 봅니다. | 인프라가 배포되기 전에 Terraform이 인프라에 적용할 변경 사항을 미리 볼 수 있습니다. Terraform이 필요에 따라 변경할 것인지 확인하려면 다음 명령을 실행합니다.`terraform plan —-var-file=examples/terraform.tfvars` | DevOps 엔지니어 | 
| 제안된 작업을 실행합니다. | `terraform plan` 명령의 결과가 예상과 일치하는지 확인하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 엔지니어 | 

### 배포 확인
<a name="verify-the-deployment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Lambda 함수를 생성 및 테스트합니다. | 배포가 성공적으로 수행되었는지 확인하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) 함수의 출력이 결과입니다. | DevOps 엔지니어 | 
| 상위 계정에서 EventBridge 규칙 실행 결과를 봅니다. | 상위 계정의 Amazon EC2 종료 이벤트를 기반으로 하는 EventBridge 규칙의 결과를 보려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html)CloudWatch 콘솔의 **로그 그룹** 페이지에는 Lambda 함수의 결과가 표시됩니다. | DevOps 엔지니어 | 
| 하위 계정에서 EventBridge 규칙 실행 결과를 봅니다. | 하위 계정의 Amazon EC2 종료 이벤트를 기반으로 하는 EventBridge 규칙의 결과를 보려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html)CloudWatch 콘솔의 **로그 그룹** 페이지에는 Lambda 함수의 결과가 표시됩니다. | DevOps 엔지니어 | 

### 사용 후 인프라 정리
<a name="clean-up-infrastructure-after-use"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 인프라를 정리합니다. | 생성한 인프라를 정리하려면 다음 명령을 사용합니다.`terraform destroy``destroy` 명령을 확인하려면를 입력합니다`yes`. | DevOps 엔지니어 | 
| 정리 후를 확인합니다. | 리소스가 성공적으로 제거되었는지 확인합니다. | DevOps 엔지니어 | 

## 문제 해결
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
|  AWS Directory Service (상위 계정)과 Amazon EC2 인스턴스(하위 계정) 간의 연결 문제 - VPC 피어링을 사용할 수 있더라도 하위 계정의 컴퓨터를 AD에 조인할 수 없습니다. | VPCs에 라우팅을 추가합니다. 지침은 AWS Directory Service 설명서[의 디렉터리 소유자와 디렉터리 소비자 계정 간의 VPC 피어링 연결 구성을](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1_setup_networking.html#step1_configure_owner_account_vpc) 참조하세요. | 

## 관련 리소스
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-resources"></a>

**AWS 설명서**
+ [Amazon EventBridge 및 AWS Identity and Access Management](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-iam.html)
+ [Systems Manager에 필요한 인스턴스 권한 구성](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)
+ [에 대한 자격 증명 및 액세스 관리 Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/iam_auth_access.html)
+ [Lambda에 대한 자격 증명 기반 IAM 정책](https://docs.aws.amazon.com/lambda/latest/dg/access-control-identity-based.html)
+ [Amazon EC2 Windows 인스턴스를 AWS Managed Microsoft AD Active Directory에 수동으로 조인](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/join_windows_instance.html)
+ [AWS Lambda 자동화를 AWS 계정AWS Managed Microsoft AD 사용하여 동일한에서 Amazon EC2 항목 제거](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html)

**기타 리소스**
+ [AWS 공급자](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)(Terraform 설명서)
+ [백엔드 구성](https://developer.hashicorp.com/terraform/language/backend)(Terraform 설명서)
+ [Terraform 설치](https://learn.hashicorp.com/tutorials/terraform/install-cli)(Terraform 설명서)
+ [Python boto 모듈(Python 패키지 인덱스 ](https://pypi.org/project/boto/)리포지토리)
+ [Terraform 바이너리 다운로드](https://www.terraform.io/downloads)(Terraform 설명서)

# AWS Lambda 자동화를 AWS 계정 AWS Managed Microsoft AD 사용하여 동일한에서 Amazon EC2 항목 제거
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad"></a>

*Dr. Rahul Sharad Gaikwad and Tamilselvan P, Amazon Web Services*

## 요약
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-summary"></a>

Active Directory(AD)는 도메인 정보와 네트워크 서비스와의 사용자 상호 작용을 관리하는 Microsoft 스크립팅 도구입니다. 관리형 서비스 제공업체(MSPs) 사이에서 직원 자격 증명 및 액세스 권한을 관리하는 데 널리 사용됩니다. AD 공격자는 비활성 계정을 사용하여 조직을 해킹할 수 있으므로 비활성 계정을 찾아 일상적인 유지 관리 일정에 따라 비활성화하는 것이 중요합니다. 를 사용하면 Microsoft Active Directory를 관리형 서비스로 실행할 AWS Directory Service for Microsoft Active Directory수 있습니다.

이 패턴은 비활성 계정을 빠르게 찾고 제거하도록 AWS Lambda 자동화를 구성하는 데 도움이 될 수 있습니다. 이 패턴을 사용하면 다음과 같은 이점을 얻을 수 있습니다.
+ 데이터베이스 및 서버 성능을 개선하고 비활성 계정에서 보안 취약성을 수정합니다.
+ AD 서버가 클라우드에서 호스팅되는 경우 비활성 계정을 제거하면 성능을 개선하는 동시에 스토리지 비용도 절감할 수 있습니다. 대역폭 요금과 컴퓨팅 리소스가 모두 떨어질 수 있으므로 월별 청구서가 감소할 수 있습니다.
+ 깨끗한 Active Directory를 사용하여 잠재적 공격자를 대피시킵니다.

## 사전 조건 및 제한 사항
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ 로컬 워크스테이션에 Git 설치 [https://git-scm.com/book/en/v2/Getting-Started-Installing-Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 및 구성.
+ Terraform은 로컬 워크스테이션에 [설치](https://learn.hashicorp.com/tutorials/terraform/install-cli) 및 구성되어 있습니다.
+ Active Directory 모듈이 있는 Windows 컴퓨터(`ActiveDirectory`).
+ 의 디렉터리 AWS Managed Microsoft AD 와 [AWS Systems Manager Parameter Store의 파라미터에 저장된 자격 증명입니다.](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-create-console.html)
+ AWS Identity and Access Management [도구](#remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-tools)에 AWS 서비스 나열된에 대한 권한이 있는 (IAM) 역할입니다*.* 관련 리소스 추가에 대한 자세한 내용은 섹션을 참조하세요.

**제한 사항 **
+ 이 패턴은 교차 계정 설정을 지원하지 않습니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) 섹션을 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

**제품 버전**
+ [Terraform 버전 1.1.9 이상](https://developer.hashicorp.com/terraform/install)
+ [Terraform AWS Provider 버전 4.0 이상](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-3-upgrade)

## 아키텍처
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-architecture"></a>

다음 다이어그램은 이 패턴의 워크플로 및 구성 요소를 보여 줍니다.

![\[Lambda 자동화를 사용하여 관리형 Microsoft AD에서 EC2 항목을 제거하는 프로세스입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/6b50dcc5-4f4b-4eea-85a7-04cebc9f7454/images/b7fc5962-bfb8-4f5a-968e-7487b1d48c4f.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. Amazon EventBridge는 cron 표현식을 기반으로 AWS Lambda 함수를 트리거합니다. (이 패턴의 경우 cron 표현식 일정은 하루에 한 번입니다.)

1. 필요한 IAM 역할 및 정책은 Terraform을 AWS Lambda 통해 생성되고에 연결됩니다.

1.  AWS Lambda 함수는 Python boto 모듈을 사용하여 실행되고 Amazon Elastic Compute Cloud(Amazon EC2) Auto Scaling 그룹을 호출합니다. Lambda 함수는 임의의 인스턴스 ID를 가져옵니다. 인스턴스 ID는 AWS Systems Manager 명령을 실행하는 데 사용됩니다.

1. AWS Lambda 는 boto 모듈을 사용하여 Amazon EC2를 다시 호출하고 실행 중인 Windows 서버의 프라이빗 IP 주소를 가져와 임시 변수에 저장합니다.

1. AWS Lambda 는 Systems Manager를 다시 호출하여 연결된 컴퓨터 정보를 가져옵니다 Directory Service.

1.  AWS Systems Manager 문서는 Amazon EC2 Windows 서버에서 PowerShell 스크립트를 실행하여 AD와 연결된 컴퓨터의 프라이빗 IP 주소를 가져오는 데 도움이 됩니다.

1. AD 도메인 사용자 이름과 암호는 AWS Systems Manager Parameter Store에 저장됩니다. AWS Lambda Systems Manager는 Parameter Store를 호출하고 AD를 연결하는 데 사용할 사용자 이름과 암호 값을 가져옵니다.

1. Systems Manager 문서를 사용하면 3단계에서 앞서 얻은 인스턴스 ID를 사용하여 Amazon EC2 Windows 서버에서 PowerShell 스크립트가 실행됩니다.

1. Amazon EC2는 PowerShell 명령을 Directory Service 사용하여 연결하고 사용 중이거나 비활성 상태인 컴퓨터를 제거합니다.

## 도구
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-tools"></a>

**서비스**
+ [AWS Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/what_is.html)는 Amazon Elastic Compute Cloud(Amazon EC2), SQL Server용 Amazon Relational Database Service(RDS), Windows File Server용 Amazon FSx AWS 서비스 등 다른와 함께 Microsoft Active Directory(AD)를 사용하는 여러 가지 방법을 제공합니다.
+ [AWS Directory Service for Microsoft Active Directory](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_microsoft_ad.html)를 사용하면 디렉터리 인식 워크로드 및 AWS 리소스가에서 Microsoft Active Directory를 사용할 수 있습니다 AWS 클라우드.
+ [Amazon Elastic Compute Cloud(Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)는 AWS 클라우드에서 확장 가능한 컴퓨팅 용량을 제공합니다. 필요한 만큼 가상 서버를 시작하고 빠르게 스케일 업하거나 스케일 다운할 수 있습니다.
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)는 애플리케이션을 다양한 소스의 실시간 데이터와 연결할 수 있는 서버리스 이벤트 버스 서비스입니다. 예를 들어 AWS Lambda 함수, API 대상을 사용하는 HTTP 호출 엔드포인트 또는 다른의 이벤트 버스 등이 있습니다 AWS 계정.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)는 AWS리소스에 대한 액세스를 인증하고 사용할 수 있는 권한을 부여받은 사용자를 제어하여 리소스에 대한 액세스를 안전하게 관리하는 데 도움이 됩니다. IAM을 사용하면의 서비스 및 리소스에 액세스할 수 있는 사용자 또는 대상을 지정하고 AWS, 세분화된 권한을 중앙에서 관리하고, 액세스를 분석하여 권한을 세분화할 수 있습니다 AWS.
+ [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 리소스를 대규모로 안전하게 관리하는 데 도움이 됩니다.
+ [AWS Systems Manager 문서는](https://docs.aws.amazon.com/systems-manager/latest/userguide/documents.html) Systems Manager가 관리형 인스턴스에서 수행하는 작업을 정의합니다. Systems Manager에는 런타임에 파라미터를 지정하여 사용할 수 있는 사전 구성 문서가 100개 이상 포함되어 있습니다.
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)는의 기능이며 구성 데이터 관리 AWS Systems Manager 및 보안 암호 관리를 위한 안전한 계층적 스토리지를 제공합니다.

**기타 도구**
+ [HashiCorp Terraform](https://www.terraform.io/docs)은 코드를 사용하여 클라우드 인프라 및 리소스를 프로비저닝하고 관리하는 데 도움이 되는 오픈 소스 코드형 인프라(IaC) 도구입니다.
+ [PowerShell](https://learn.microsoft.com/en-us/powershell/)은 Windows, Linux 및 macOS에서 실행되는 마이크로소프트 자동화 및 구성 관리 프로그램입니다.
+ [Python](https://www.python.org/)은 범용 컴퓨터 프로그래밍 언어입니다.

**코드 리포지토리**

이 패턴의 코드는 [Terraform을 사용한 GitHub AWS WAF 자동화](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-best-practices"></a>
+ **도메인을 자동 조인** Directory Service 도메인의 일부가 될 Windows 인스턴스를 시작할 때 나중에 인스턴스를 수동으로 추가하는 대신 인스턴스 생성 프로세스 중에 도메인에 조인합니다. 새로운 인스턴스를 시작할 때 [**Domain join directory**]에 대한 올바른 디렉터리를 선택하기만 하면 도메인을 자동으로 조인할 수 있습니다. 자세한 내용은 *Directory Service 관리 안내서*의 [ Amazon EC2 Windows 인스턴스를 AWS Managed Microsoft AD Active Directory에 원활하게 조인을 참조하세요](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/launching_instance.html).
+ **사용하지 않는 계정을 삭제합니다. ** AD에서 사용한 적이 없는 계정을 찾는 것이 일반적입니다. 시스템에 남아 있는 비활성화된 계정 또는 비활성 계정과 마찬가지로, 무시된 미사용 계정은 AD 시스템의 속도를 늦추거나 조직을 데이터 침해에 취약하게 만들 수 있습니다.
+ **Active Directory 정리를 자동화합니다. ** 보안 리스크를 완화하고 더 이상 사용되지 않는 계정이 AD 성능에 영향을 미치지 않도록 AD 정리를 정기적으로 수행해야 합니다. 스크립트를 작성하여 대부분의 AD 관리 및 정리 작업을 수행할 수 있습니다. 예시 작업에는 비활성화 및 비활성 계정 제거, 빈 및 비활성 그룹 삭제, 만료된 사용자 계정 및 암호 찾기가 포함됩니다.

## 에픽
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-epics"></a>

### 환경을 설정합니다
<a name="set-up-your-environment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 프로젝트 폴더를 생성하고 파일을 추가합니다. | 리포지토리를 복제하고 프로젝트 폴더를 생성하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html) | DevOps 엔지니어 | 

### Terraform을 사용하여 대상 아키텍처 프로비저닝
<a name="provision-the-target-architecture-by-using-the-terraform-configuration"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Terraform 구성을 초기화합니다. | 다음 명령을 입력하여 Terraform 구성 파일이 포함된 작업 디렉토리를 초기화합니다.`terraform init` | DevOps 엔지니어 | 
| 변경 사항을 미리 봅니다. | 인프라가 배포되기 전에 Terraform이 인프라에 적용할 변경 사항을 미리 볼 수 있습니다. Terraform이 필요에 따라 변경할 것인지 확인하려면 다음 명령을 실행합니다.`terraform plan` | DevOps 엔지니어 | 
| 제안된 작업을 실행합니다. | `terraform plan` 명령의 결과가 예상대로인지 확인하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html) | DevOps 엔지니어 | 
| 인프라를 정리합니다. | 생성한 인프라를 정리하려면 다음 명령을 사용합니다.`terraform destroy`삭제 명령을 확인하려면를 입력합니다`yes`. | DevOps 엔지니어 | 

### 배포 확인
<a name="verify-the-deployment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Lambda 함수를 생성 및 테스트합니다. | 배포가 성공적으로 수행되었는지 확인하려면 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html) 함수의 출력이 결과입니다. | DevOps 엔지니어 | 
| Lambda 함수의 결과를 봅니다. | 이 패턴에서 EventBridge 규칙은 하루에 한 번 Lambda 함수를 실행합니다. Lambda 함수 결과는 다음과 같습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html)CloudWatch 콘솔의 **로그 그룹** 페이지에는 Lambda 함수의 결과가 표시됩니다. | DevOps 엔지니어 | 

### 사용 후 인프라 정리
<a name="clean-up-infrastructure-after-use"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 인프라 정리 | 생성한 인프라를 정리하려면 다음 명령을 사용합니다.`terraform destroy`삭제 명령을 확인하려면를 입력합니다`yes`. | DevOps 엔지니어 | 
| 정리 후를 확인합니다. | 리소스가 성공적으로 제거되었는지 확인합니다. | DevOps 엔지니어 | 

## 문제 해결
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| AD 컴퓨터를 제거하려고 하면 “액세스 거부됨” 메시지가 표시됩니다. 기본적으로 작업은 AD 서비스의 일부로 연결된 두 개의 프라이빗 IP 주소를 제거하려고 하기 때문에 AD 컴퓨터를 제거할 수 없습니다. | 이 오류를 방지하려면 AD 컴퓨터 출력과 Windows를 실행하는 시스템의 출력 간의 차이를 나열할 때 다음 Python 작업을 사용하여 처음 두 컴퓨터를 무시합니다.<pre>Difference = Difference[2:]</pre> | 
| Lambda는 Windows 서버에서 PowerShell 스크립트를 실행할 때 기본적으로 Active Directory 모듈을 사용할 수 있을 것으로 예상합니다. 모듈을 사용할 수 없는 경우 Lambda 함수는 "Get-AdComputer is not installed on instance"라는 오류를 생성합니다. | 이 오류를 방지하려면 EC2 인스턴스의 사용자 데이터를 사용하여 필요한 모듈을 설치합니다. 이 패턴의 GitHub 리포지토리에 있는 [EC2WindowsUserdata](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/blob/main/EC2WindowsUserdata) 스크립트를 사용합니다. | 

## 관련 리소스
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-resources"></a>

**AWS 설명서**
+ [Amazon EventBridge 및 AWS Identity and Access Management](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-iam.html)
+ [Systems Manager에 필요한 인스턴스 권한 구성](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)
+ [에 대한 자격 증명 및 액세스 관리 Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/iam_auth_access.html)
+ [Amazon EC2 Windows 인스턴스를 AWS Managed Microsoft AD Active Directory에 수동으로 조인](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/join_windows_instance.html)
+ [에서 자격 증명 기반 IAM 정책 작업 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/access-control-identity-based.html)

**기타 리소스**
+ [AWS 공급자](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)(Terraform 설명서)
+ [백엔드 구성](https://developer.hashicorp.com/terraform/language/backend)(Terraform 설명서)
+ [Terraform 설치](https://learn.hashicorp.com/tutorials/terraform/install-cli)(Terraform 설명서)
+ [Python boto 모듈(Python 패키지 인덱스 ](https://pypi.org/project/boto/)리포지토리)
+ [Terraform 바이너리 다운로드](https://www.terraform.io/downloads)(Terraform 설명서)

# pytest 프레임워크를 AWS Glue 사용하여에서 Python ETL 작업에 대한 단위 테스트 실행
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework"></a>

*Praveen Kumar Jeyarajan, Vaidy Sankaran, Amazon Web Services*

## 요약
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-summary"></a>

 AWS Glue [로컬 개발 환경에서](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html)의 Python 추출, 변환 및 로드(ETL) 작업에 대한 단위 테스트를 실행할 수 있지만 DevOps 파이프라인에서 이러한 테스트를 복제하는 것은 어렵고 시간이 많이 걸릴 수 있습니다. 단위 테스트는 AWS 기술 스택에서 메인프레임 ETL 프로세스를 현대화할 때 특히 어려울 수 있습니다. 이 패턴은 기존 기능을 그대로 유지하고, 새 기능을 출시할 때 주요 애플리케이션 기능이 중단되지 않도록 하고, 고품질 소프트웨어를 유지하면서 유닛 테스트를 간소화하는 방법을 보여줍니다. 이 패턴의 단계 및 코드 샘플을 사용하여 pytest 프레임워크를 AWS Glue 사용하여에서 Python ETL 작업에 대한 단위 테스트를 실행할 수 있습니다 AWS CodePipeline. 이 패턴을 사용하여 여러 AWS Glue 작업을 테스트하고 배포할 수도 있습니다.

## 사전 조건 및 제한 사항
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정
+ Amazon ECR 퍼블릭 갤러리에서 다운로드한 AWS Glue 라이브러리용 Amazon Elastic Container Registry(Amazon ECR) 이미지 URI [https://gallery.ecr.aws/glue/aws-glue-libs](https://gallery.ecr.aws/glue/aws-glue-libs)
+ 대상 AWS 계정 및에 대한 프로필이 있는 Bash 터미널(모든 운영 체제에서) AWS 리전
+ [Python 3.10](https://www.python.org/downloads/) 이상
+ [Pytest](https://github.com/pytest-dev/pytest)
+ 테스트용 [Moto](https://github.com/getmoto/moto) Python 라이브러리 AWS 서비스

## 아키텍처
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-architecture"></a>

다음 다이어그램은 Python을 기반으로 하는 AWS Glue ETL 프로세스에 대한 단위 테스트를 일반적인 엔터프라이즈급 AWS DevOps 파이프라인에 통합하는 방법을 설명합니다.

![\[AWS Glue ETL 프로세스의 유닛 테스트를 실시합니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/82781ca8-4da0-4df0-bf23-32992fece231/images/6286dafc-f1e0-4967-beed-4dedc6047c10.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 소스 단계에서는 버전이 지정된 Amazon Simple Storage Service(Amazon S3) 버킷을 AWS CodePipeline 사용하여 소스 코드 자산을 저장하고 관리합니다. 이러한 자산에는 샘플 Python ETL 작업(`sample.py`), 단위 테스트 파일(`test_sample.py`) 및 AWS CloudFormation 템플릿이 포함됩니다. 그런 다음 CodePipeline은 추가 처리를 위해 최신 코드를 기본 브랜치에서 AWS CodeBuild 프로젝트로 전송합니다.

1. 빌드 및 게시 단계에서는 AWS Glue 퍼블릭 Amazon ECR 이미지를 사용하여 이전 소스 단계의 최신 코드를 단위 테스트합니다. 그런 다음 테스트 보고서가 CodeBuild 보고서 그룹에 게시됩니다. AWS Glue 라이브러리용 퍼블릭 Amazon ECR 리포지토리의 컨테이너 이미지에는 AWS Glue 로컬에서 [PySpark 기반](https://spark.apache.org/docs/latest/api/python/) ETL 작업을 실행하고 단위 테스트하는 데 필요한 모든 바이너리가 포함되어 있습니다. 퍼블릭 컨테이너 리포지토리에는 AWS Glue에서 지원하는 버전마다 하나씩, 총 3개의 이미지 태그가 있습니다. 데모를 위해 이 패턴은 `glue_libs_4.0.0_image_01` 이미지 태그를 사용합니다. CodeBuild에서 이 컨테이너 이미지를 런타임 이미지로 사용하려면 사용하려는 이미지 태그에 해당하는 이미지 URI를 복사한 다음 `TestBuild` 리소스의 GitHub 리포지토리에서 `pipeline.yml` 파일을 업데이트하십시오.

1. 배포 단계에서 CodeBuild 프로젝트가 시작되고 모든 테스트를 통과하면 Amazon S3 버킷에 코드를 게시합니다.

1. 사용자는 `deploy` 폴더의 CloudFormation 템플릿을 사용하여 AWS Glue 작업을 배포합니다.

## 도구
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-tools"></a>

**AWS 서비스**
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.
+ [Amazon Elastic Container Registry(Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)는 안전하고 확장성이 있고 신뢰할 수 있는 관리형 컨테이너 이미지 레지스트리 서비스입니다.
+ [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)는 업계 최고의 확장성, 데이터 가용성, 보안 및 성능을 제공하는 객체 스토리지 서비스입니다.

**기타 도구**
+ [Python](https://www.python.org/)은 높은 수준의, 해석된 범용 프로그래밍 언어입니다.
+ [Moto](https://github.com/getmoto/moto)는 테스트를 위한 Python 라이브러리입니다 AWS 서비스.
+ [Pytest](https://github.com/pytest-dev/pytest)는 애플리케이션 및 라이브러리의 복잡한 기능 테스트를 지원하도록 규모가 조정되는 소규모 유닛 테스트를 작성하기 위한 프레임워크입니다.
+ 용 [Python ETL 라이브러리](https://github.com/awslabs/aws-glue-libs) AWS Glue 는 PySpark 배치 작업의 로컬 개발에 사용되는 Python 라이브러리용 리포지토리입니다 AWS Glue.

**코드 리포지토리**

이 패턴의 코드는 GitHub [aws-glue-jobs-unit-testing](https://github.com/aws-samples/aws-glue-jobs-unit-testing) 리포지토리에서 사용할 수 있습니다. 리포지토리에는 다음 리소스가 포함됩니다.
+ `src` 폴더의 샘플 Python 기반 AWS Glue 작업
+ `tests` 폴더의 관련 유닛 테스트 사례(pytest 프레임워크를 사용하여 구축됨)
+ `deploy` 폴더에 있는 CloudFormation 템플릿(YAML로 작성)

## 모범 사례
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-best-practices"></a>

**코드파이프라인 리소스 보안**

CodePipeline의 파이프라인에 연결하는 소스 리포지토리에 대해 암호화 및 인증을 사용하는 것이 가장 좋습니다. 자세한 내용은 CodePipeline 설명서의 [보안 모범 사례](https://docs.aws.amazon.com/codepipeline/latest/userguide/security-best-practices.html)를 참조하십시오.

**CodePipeline 리소스 모니터링 및 로깅**

 AWS 로깅 기능을 사용하여 계정에서 사용자가 수행하는 작업과 사용하는 리소스를 결정하는 것이 가장 좋습니다. 로그 파일은 다음을 보여 줍니다.
+ 작업의 시간과 날짜
+ 작업의 소스 IP 주소
+ 부족한 권한으로 인해 실패한 작업

로깅 기능은 AWS CloudTrail 및 Amazon CloudWatch Events에서 사용할 수 있습니다. CloudTrail을 사용하여에 의해 또는를 대신하여 수행된 AWS API 호출 및 관련 이벤트를 로깅할 수 있습니다 AWS 계정. 자세한 내용은 CodePipeline 설명서의 [AWS CloudTrail을 사용한 CodePipeline API 직접 호출 로깅](https://docs.aws.amazon.com/codepipeline/latest/userguide/monitoring-cloudtrail-logs.html)을 참조하십시오.

CloudWatch Events를 사용하여에서 실행되는 AWS 클라우드 리소스 및 애플리케이션을 모니터링할 수 있습니다 AWS. CloudWatch Events에서 알림을 생성할 수도 있습니다. 자세한 내용은 CodePipeline 설명서의 [CodePipeline 이벤트 모니터링](https://docs.aws.amazon.com/codepipeline/latest/userguide/detect-state-changes-cloudwatch-events.html)을 참조하십시오.

## 에픽
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-epics"></a>

### 소스 코드 배포
<a name="deploy-the-source-code"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 배포할 코드 아카이브를 준비하십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html) | DevOps 엔지니어 | 
| CloudFormation 스택을 생성하십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html)이 스택은 Amazon S3를 소스로 사용하여 CodePipeline 보기를 생성합니다. 위 단계에서 파이프라인은 **aws-glue-unit-test-pipeline**입니다. | AWS DevOps, DevOps 엔지니어 | 

### 유닛 테스트 실행
<a name="run-the-unit-tests"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 파이프라인에서 유닛 테스트를 실행하십시오. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html) | AWS DevOps, DevOps 엔지니어 | 

### 모든 AWS 리소스 정리
<a name="clean-up-all-aws-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 환경에서 리소스를 정리합니다. | 추가 인프라 비용을 피하려면 이 패턴에 제공된 예제를 시험해 본 후 스택을 삭제해야 합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html) | AWS DevOps, DevOps 엔지니어 | 

## 문제 해결
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| CodePipeline 서비스 역할은 Amazon S3 버킷에 액세스할 수 없습니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html) | 
| CodePipeline이 Amazon S3 버킷의 버전이 지정되지 않았다는 오류를 반환합니다. | CodePipeline을 사용하려면 소스 Amazon S3 버킷의 버전을 지정해야 합니다. Amazon S3 버킷에서 버전 관리를 활성홥니다. 지침은 [버킷에서 버전 관리 활성화](https://docs.aws.amazon.com/AmazonS3/latest/userguide/manage-versioning-examples.html)를 참조하세요. | 

## 관련 리소스
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-resources"></a>
+ [AWS Glue](https://aws.amazon.com/glue/)
+ [로컬에서 AWS Glue 작업 개발 및 테스트](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html)
+ [용 AWS CloudFormation AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/populate-with-cloudformation-templates.html)

## 추가 정보
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-additional"></a>

또한 AWS Command Line Interface ()를 사용하여 AWS CloudFormation 템플릿을 배포할 수 있습니다AWS CLI. 자세한 내용은 CloudFormation 설명서에서 [변형이 포함된 템플릿을 빠르게 배포](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-deploy.html)를 참조하세요.

# AWS CodePipeline 및 AWS CDK를 사용하여 CI/CD 파이프라인 설정하기
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk"></a>

*Konstantin Zarudaev, Yasha Dabas, Lars Kinder, Cizer Pereira, Amazon Web Services*

## 홈
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-summary"></a>

지속적 통합 및 지속적 전달(CI/CD)을 통해 소프트웨어 구축 및 릴리스 프로세스를 자동화하면 반복 가능한 구축을 지원하고 사용자에게 새로운 기능을 신속하게 제공할 수 있습니다. 각 코드 변경을 쉽고 빠르게 테스트할 수 있으며 소프트웨어를 릴리스하기 전에 버그를 발견하고 수정할 수 있습니다. 스테이징 및 릴리스 프로세스를 통해 각 변경 사항을 실행하여 애플리케이션 또는 인프라 코드의 품질을 확인할 수 있습니다. CI/CD는 애플리케이션 개발 팀이 코드 변경을 더 자주, 안정적으로 제공할 수 있도록 지원하는 문화, 운영 원칙, [관행](https://aws.amazon.com/devops/#cicd)을 구현합니다. 이 구현을 *CI/CD 파이프라인*이라고도 합니다.

이 패턴은 Amazon Web Service(AWS)에서 AWS CodeCommit와 함께 재사용 가능한 지속적 통합 및 지속적 전달(CI/CD) 파이프라인을 정의합니다. AWS CodePipeline 파이프라인은 [AWS 클라우드 개발 키트(AWS CDK) v2](https://aws.amazon.com/cdk/)를 사용하여 작성되었습니다.

AWS CodePipeline을 사용하면 AWS Management Console, AWS Command Line Interface(AWS CLI), AWS CloudFormation 또는 AWS SDK를 통해 소프트웨어 릴리스 프로세스의 여러 단계를 모델링할 수 있습니다. 이 패턴은 AWS CDK를 사용하여 CodePipeline과 해당 구성 요소를 구현하는 방법을 보여줍니다. 라이브러리 구성 외에도 AWS CDK에는 AWS CDK 앱과 상호 작용하는 기본 도구인 툴킷(CLI 명령 `cdk`)이 포함되어 있습니다. 다른 기능 중에서도 이 툴킷은 하나 이상의 스택을 CloudFormation 템플릿으로 변환하여 AWS 계정에 배포하는 기능을 제공합니다.

파이프라인에는 타사 라이브러리의 보안을 검증하기 위한 테스트가 포함되어 있으며, 지정된 환경에서 신속하고 자동화된 릴리스를 보장하는 데 도움이 됩니다. 검증 프로세스를 통해 애플리케이션의 전반적인 보안을 강화할 수 있습니다.

이 패턴의 목적은 배포하는 리소스가 DevOps 모범 사례를 준수하도록 하는 동시에 CI/CD 파이프라인 사용을 가속화하여 코드를 배포하는 것입니다. [예제 코드](https://github.com/aws-samples/aws-codepipeline-cicd)를 구현하면 린팅, 테스트, 보안 검사, 배포 및 배포 후 프로세스가 포함된 [AWS CodePipeline](https://aws.amazon.com/codepipeline/)을 갖게 됩니다. 이 패턴에는 Makefile 단계도 포함됩니다. 개발자는 Makefile을 사용하여 CI/CD 단계를 로컬에서 재현하고 개발 프로세스의 속도를 높일 수 있습니다.

## 사전 조건 및 제한 사항
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정
+ 기본적인 이해는 다음과 같습니다.
  + AWS CDK
  + AWS CloudFormation
  + AWS CodePipeline
  + TypeScript

**제한 사항 **

이 패턴은 TypeScript용 [AWS CDK](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)만 사용합니다. AWS CDK에서 지원하는 다른 언어는 다루지 않습니다.

**제품 버전**

다음 도구의 최신 버전을 사용합니다.
+ AWS Command Line Interface(AWS CLI)
+ cfn\$1nag
+ git-remote-codecommit
+ Node.js

## 아키텍처
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-architecture"></a>

**대상 기술 스택**
+ AWS CDK
+ AWS CloudFormation
+ AWS CodeCommit
+ AWS CodePipeline

**대상 아키텍처**

파이프라인은 AWS CodeCommit 리포지토리(`SampleRepository`)의 변경에 의해 트리거됩니다. 처음에는 CodePipeline이 아티팩트를 구축하고, 자체 업데이트하고, 배포 프로세스를 시작합니다. 그 결과로 생성되는 파이프라인은 솔루션을 세 개의 독립적인 환경에 배포합니다.
+ 개발 — 활성 개발 환경에서의 3단계 코드 검사
+ 테스트 — 통합 및 회귀 테스트 환경
+ Prod – 프로덕션 환경

개발 단계에 포함되는 세 단계는 린팅, 보안 및 유닛 테스트입니다. 이러한 단계는 병렬로 실행되어 프로세스 속도를 높입니다. 파이프라인이 작동하는 아티팩트만 제공하도록 하기 위해 프로세스의 한 단계가 실패할 때마다 파이프라인 실행이 중지됩니다. 개발 단계 배포 후 파이프라인은 검증 테스트를 실행하여 결과를 확인합니다. 성공하면 파이프라인은 배포 후 검증이 포함된 테스트 환경에 아티팩트를 배포합니다. 마지막 단계는 아티팩트를 프로덕션 환경에 배포하는 것입니다.

다음 다이어그램은 CodeCommit 리포지토리에서 CodePipeline이 수행하는 구축 및 업데이트 프로세스, 세 가지 개발 환경 단계, 세 환경 각각에서의 후속 배포 및 검증에 이르는 워크플로우를 보여줍니다.

![\[개발 환경에는 린팅, 보안 및 단위 테스트가 포함되며, 모두 배포와 검증을 포함합니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/d617e735-8624-4722-8a3d-073bcc356328/images/92504aac-03e3-4c95-b225-74505f8dd136.png)


## 도구
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-tools"></a>

**서비스**
+ [AWS Cloud Development Kit(AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)는 AWS 클라우드 인프라를 코드로 정의하고 프로비저닝하는 데 도움이 되는 소프트웨어 개발 프레임워크입니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)을 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, 전체 AWS 계정 및 리전에서 수명 주기 전반에 걸쳐 관리할 수 있습니다. 이 패턴에서는 CloudFormation 템플릿을 사용하여 CodeCommit 리포지토리와 CodePipeline CI/CD 파이프라인을 생성할 수 있습니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 나만의 원본 제어 시스템을 관리할 필요 없이 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 버전 제어 서비스입니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화하는 데 도움이 되는 CI/CD 서비스입니다.
+ [AWS Command Line Interface(AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 쉘에서 명령을 사용하여 AWS 서비스와 상호 작용할 수 있는 오픈 소스 도구입니다.

**기타 도구**
+ [cfn\$1nag](https://github.com/stelligent/cfn_nag)는 CloudFormation 템플릿에서 패턴을 찾아 잠재적인 보안 문제를 파악하는 오픈 소스 도구입니다.
+ [git-remote-codecommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-git-remote-codecommit.html)은 Git을 확장하여 CodeCommit 리포지토리에서 코드를 푸시하고 끌어오는 유틸리티입니다.
+ [Node.js](https://nodejs.org/en/docs/)는 확장 가능한 네트워크 애플리케이션 구축을 위해 설계된 이벤트 기반 JavaScript 런타임 환경입니다.

**코드**

이 패턴의 코드는 [CI/CD 관행이 포함된 AWS CodePipeline](https://github.com/aws-samples/aws-codepipeline-cicd) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-best-practices"></a>

AWS Identity 및 Access Management(IAM) 정책과 같은 리소스를 검토하여 해당 정책이 조직의 모범 사례에 부합하는지 확인합니다.

## 에픽
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-epics"></a>

### 도구 설치
<a name="install-tools"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| macOS 또는 Linux에 도구를 설치합니다. | MacOS 또는 Linux를 사용하는 경우, 선호하는 터미널에서 다음 명령을 실행하거나 [Linux용 Homebrew](https://docs.brew.sh/Homebrew-on-Linux)를 사용하여 도구를 설치할 수 있습니다.<pre>brew install<br />brew install git-remote-codecommit<br />brew install ruby brew-gem<br />brew-gem install cfn-nag</pre> | DevOps 엔지니어 | 
| AWS CLI를 설정합니다. | AWS CLI를 설정하려면, 운영 체제에 대한 지침을 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html) | DevOps 엔지니어 | 

### 초기 배포 설정
<a name="set-up-the-initial-deployment"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 코드를 다운로드하거나 복제합니다. | 이 패턴에서 사용되는 코드를 가져오려면 다음 중 하나를 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html)<pre>git clone --depth 1 https://github.com/aws-samples/aws-codepipeline-cicd.git</pre>복제된 리포지토리에서 `.git` 디렉터리를 제거합니다.<pre>cd ./aws-codepipeline-cicd<br />rm -rf ./.git</pre>나중에 새로 생성된 AWS CodeCommit 리포지토리를 원격 오리진으로 사용하게 됩니다. | DevOps 엔지니어 | 
| AWS 계정에 연결합니다. | 임시 보안 토큰 또는 랜딩 존 인증을 사용하여 연결할 수 있습니다. 올바른 계정과 AWS 리전을 사용하고 있는지 확인하려면 다음 명령을 실행하십시오.<pre>AWS_REGION="eu-west-1"<br />ACCOUNT_NUMBER=$(aws sts get-caller-identity --query Account --output text)<br />echo "${ACCOUNT_NUMBER}"</pre> | DevOps 엔지니어 | 
| 환경을 부트스트랩합니다. | AWS CDK 환경을 부트스트랩하려면 다음 명령을 실행합니다.<pre>npm install<br />npm run cdk bootstrap "aws://${ACCOUNT_NUMBER}/${AWS_REGION}"</pre>환경을 성공적으로 부트스트랩한 후에는 다음 출력이 표시되어야 합니다.<pre>⏳  Bootstrapping environment aws://{account}/{region}...<br />✅  Environment aws://{account}/{region} bootstrapped</pre>AWS CDK 부트스트래핑에 대한 자세한 내용은 [AWS CDK 설명서](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)를 참조하세요. | DevOps 엔지니어 | 
| 템플릿을 합성합니다. | AWS CDK 앱을 합성하려면 `cdk synth` 명령을 사용합니다.<pre>npm run cdk synth</pre>다음과 같이 출력되어야 합니다.<pre>Successfully synthesized to <path-to-directory>/aws-codepipeline-cicd/cdk.out<br />Supply a stack id (CodePipeline, Dev-MainStack) to display its template.</pre> | DevOps 엔지니어 | 
| CodePipeline 스택을 배포합니다. | 이제 CloudFormation 템플릿을 부트스트랩하고 합성했으므로 배포할 수 있습니다. 배포를 통해 CodePipeline 파이프라인 및 CodeCommit 리포지토리가 생성되며, 이 리포지토리는 파이프라인의 소스 및 트리거가 됩니다.<pre>npm run cdk -- deploy CodePipeline --require-approval never</pre>명령을 실행한 후 CodePipeline 스택과 출력 정보가 성공적으로 배포된 것을 확인할 수 있습니다. `CodePipeline.RepositoryName`는 AWS 계정의 CodeCommit 리포지토리 이름을 제공합니다.<pre>CodePipeline: deploying...<br />CodePipeline: creating CloudFormation changeset...<br />✅  CodePipeline<br />Outputs:<br />CodePipeline.RepositoryName = SampleRepository<br />Stack ARN:<br />arn:aws:cloudformation:REGION:ACCOUNT-ID:stack/CodePipeline/STACK-ID</pre> | DevOps 엔지니어 | 
| 원격 CodeCommit 리포지토리 및 브랜치를 설정합니다. | 배포에 성공하면 CodePipeline이 파이프라인의 첫 번째 실행을 시작합니다. 이 실행은 [AWS CodePipeline 콘솔](https://eu-west-1.console.aws.amazon.com/codesuite/codepipeline/pipelines)에서 찾을 수 있습니다. AWS CDK와 CodeCommit은 기본 브랜치를 시작하지 않으므로 이 초기 파이프라인 실행은 실패하고 다음과 같은 오류 메시지를 반환합니다.<pre>The action failed because no branch named main was found in the selected AWS CodeCommit repository SampleRepository. Make sure you are using the correct branch name, and then try again. Error: null</pre>이 오류를 수정하려면 원격 오리진을 `SampleRepository`로 설정하고 필요한 `main` 브랜치를 생성하십시오.<pre>RepoName=$(aws cloudformation describe-stacks --stack-name CodePipeline --query "Stacks[0].Outputs[?OutputKey=='RepositoryName'].OutputValue" --output text)<br />echo "${RepoName}"<br />#<br />git init<br />git branch -m master main<br />git remote add origin codecommit://${RepoName}<br />git add .<br />git commit -m "Initial commit"<br />git push -u origin main</pre> | DevOps 엔지니어 | 

### 배포된 CodePipeline 파이프라인 테스트
<a name="test-the-deployed-codepipeline-pipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 파이프라인을 활성화하려면 변경 사항을 커밋하십시오. | 초기 배포에 성공하면 `SampleRepository`의 `main` 브랜치를 소스 브랜치로 사용하는 완전한 CI/CD 파이프라인을 갖추어야 합니다. `main` 브랜치에 변경 사항을 커밋하는 즉시 파이프라인은 다음과 같은 일련의 작업을 시작하고 실행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html) | DevOps 엔지니어 | 

### Makefile을 사용하여 로컬에서 테스트합니다.
<a name="test-locally-by-using-a-makefile"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Makefile을 사용하여 개발 프로세스를 실행합니다. | `make` 명령을 사용하여 전체 파이프라인을 로컬에서 실행하거나 개별 단계를 실행할 수 있습니다(예: `make linting`).`make`를 사용하여 테스트하려면 다음 작업을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html) | 앱 개발자, DevOps 엔지니어 | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS CDK 앱 리소스를 삭제합니다. | AWS CDK 앱을 정리하려면 다음 명령을 실행합니다.<pre>cdk destroy --all</pre>부트스트래핑 중에 생성된 Amazon Simple Storage Service(Amazon S3) 버킷은 자동으로 삭제되지 않는다는 점을 유의해 주십시오. 삭제를 허용하는 보존 정책이 필요하거나 AWS 계정에서 수동으로 삭제해야 합니다. | DevOps 엔지니어 | 

## 문제 해결
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 템플릿이 예상대로 작동하지 않습니다. | 문제가 발생하여 템플릿이 작동하지 않으면 다음 사항을 확인해야 합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html) | 

## 관련 리소스
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-resources"></a>
+ [IAM Identity Center에서 일반 작업 시작](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html)
+ [AWS CodePipeline 설명서](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)
+ [AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/home.html)

# Terraform을 사용하여 엔터프라이즈 규모로 중앙 집중식 로깅 설정
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform"></a>

*Aarti Rajput, Yashwant Patel, Nishtha Yadav, Amazon Web Services*

## 요약
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-summary"></a>

중앙 집중식 로깅은 조직의 운영, 보안 및 규정 준수에 대한 가시성을 제공하므로 조직의 클라우드 인프라에 매우 중요합니다. 조직이 여러 계정에서 AWS 환경을 확장함에 따라 구조화된 로그 관리 전략은 보안 운영을 실행하고 감사 요구 사항을 충족하며 운영 우수성을 달성하기 위한 기본이 됩니다.

이 패턴은 여러 AWS 계정 및 서비스의 로그를 중앙 집중화하여 복잡한 AWS 배포에서 엔터프라이즈 규모의 로깅 관리를 가능하게 하는 확장 가능하고 안전한 프레임워크를 제공합니다. 솔루션은 일관되고 반복 가능한 배포를 보장하고 수동 구성을 최소화하는 HashiCorp의 코드형 인프라(IaC) 도구인 Terraform을 사용하여 자동화됩니다. Amazon CloudWatch Logs, Amazon Data Firehose 및 Amazon Simple Storage Service(Amazon S3)를 결합하여 다음을 제공하는 강력한 로그 집계 및 분석 파이프라인을 구현할 수 있습니다.
+ 에서 조직 전체의 중앙 집중식 로그 관리 AWS Organizations
+ 기본 보안 제어를 사용한 자동 로그 수집
+ 확장 가능한 로그 처리 및 내구성 있는 스토리지
+ 간소화된 규정 준수 보고 및 감사 추적
+ 실시간 운영 인사이트 및 모니터링

이 솔루션은 CloudWatch Logs를 통해 Amazon Elastic Kubernetes Service(Amazon EKS) 컨테이너, AWS Lambda 함수 및 Amazon Relational Database Service(Amazon RDS) 데이터베이스 인스턴스에서 로그를 수집합니다. CloudWatch 구독 필터를 사용하여 이러한 로그를 전용 로깅 계정에 자동으로 전달합니다. Firehose는 장기 스토리지용 Amazon S3에 대한 높은 처리량의 로그 스트리밍 파이프라인을 관리합니다. Amazon Simple Queue Service(Amazon SQS)는 객체 생성 시 Amazon S3 이벤트 알림을 수신하도록 구성됩니다. 이를 통해 다음을 포함한 분석 서비스와 통합할 수 있습니다.
+ 로그 검색, 시각화 및 실시간 분석을 위한 Amazon OpenSearch Service
+ SQL 기반 쿼리를 위한 Amazon Athena
+ 대규모 처리를 위한 Amazon EMR
+ 사용자 지정 변환을 위한 Lambda
+ 대시보드용 Amazon Quick Sight

모든 데이터는 AWS Key Management Service (AWS KMS)를 사용하여 암호화되며, 환경 간에 일관된 구성을 위해 Terraform을 사용하여 전체 인프라가 배포됩니다.

이러한 중앙 집중식 로깅 접근 방식을 통해 조직은 보안 태세를 개선하고, 규정 준수 요구 사항을 유지하고, AWS 인프라 전반의 운영 효율성을 최적화할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-prereqs"></a>

**사전 조건 **
+ [AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/getting-started-with-control-tower.html)를 사용하여 구축된 조직의 랜딩 존
+ [필수 계정으로 배포 및 구성된 Account Factory for Terraform(AFT)](https://docs.aws.amazon.com/controltower/latest/userguide/aft-getting-started.html)
+ 인프라 프로비저닝을 위한 [Terraform](https://developer.hashicorp.com/terraform/downloads) 
+ 교차 계정 액세스를 위한 [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started.html) 역할 및 정책

설정 AWS Control Tower, AFT 및 애플리케이션 계정 설정에 대한 지침은 [에픽 섹션을 참조하세요](#set-up-centralized-logging-at-enterprise-scale-by-using-terraform-epics).

**필수 계정**

의 조직은 다음 계정을 포함해야 AWS Organizations 합니다.
+ **애플리케이션 계정** - AWS 서비스 (Amazon EKS, Lambda 및 Amazon RDS)가 실행되고 로그를 생성하는 하나 이상의 소스 계정
+ **로그 아카이브 계정** - 중앙 집중식 로그 스토리지 및 관리를 위한 전용 계정

**제품 버전**
+ [AWS Control Tower 버전 3.1](https://docs.aws.amazon.com/controltower/latest/userguide/2023-all.html#lz-3-1) 이상
+ [Terraform 버전 0.15.0](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) 이상

## 아키텍처
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-architecture"></a>

다음 다이어그램은 여러 애플리케이션 계정의 로그를 수집, 처리 및 전용 로그 아카이브 계정으로 저장하기 위한 확장 가능한 솔루션을 제공하는 AWS 중앙 집중식 로깅 아키텍처를 보여줍니다. 이 아키텍처는 Amazon RDS AWS 서비스, Amazon EKS 및 Lambda를 포함한의 로그를 효율적으로 처리하고 간소화된 프로세스를 통해 로그 아카이브 계정의 리전 S3 버킷으로 라우팅합니다.

![\[여러 애플리케이션 계정에서 로그를 수집하기 위한 AWS 중앙 집중식 로깅 아키텍처.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/9fc71a10-65d6-437b-9128-cc27bda11af4/images/2e916040-0f11-4712-a8dd-31c95194ce5d.png)


워크플로에는 다음 5가지 프로세스가 포함됩니다.

1. **로그 흐름 프로세스**
   + 로그 흐름 프로세스는 애플리케이션 계정에서 시작되며, 여기서는 일반, 오류, 감사, Amazon RDS의 느린 쿼리 로그, Amazon EKS의 컨트롤 플레인 로그, Lambda의 함수 실행 및 오류 로그와 같은 다양한 유형의 로그를 AWS 서비스 생성합니다.
   + CloudWatch는 초기 수집 지점 역할을 합니다. 각 애플리케이션 계정 내의 로그 그룹 수준에서 이러한 로그를 수집합니다.
   + CloudWatch에서 [구독 필터](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Subscriptions.html)는 중앙 계정으로 전달해야 하는 로그를 결정합니다. 이러한 필터를 사용하면 로그 전달을 세부적으로 제어할 수 있으므로 정확한 로그 패턴을 지정하거나 중앙 집중화를 위한 전체 로그 스트림을 지정할 수 있습니다.

1. **교차 계정 로그 전송**
   + 로그는 로그 아카이브 계정으로 이동합니다. CloudWatch 구독 필터는 교차 계정 전송을 용이하게 하고 리전 컨텍스트를 보존합니다.
   + 아키텍처는 다양한 로그 소스를 효율적으로 처리하여 최적의 성능과 확장성을 보장하기 위해 여러 병렬 스트림을 설정합니다.

1. **로그 아카이브 계정의 로그 처리**
   + 로그 아카이브 계정에서 Firehose는 수신 로그 스트림을 처리합니다.
   + 각 리전에서는 필요에 따라 로그를 변환, 변환 또는 보강할 수 있는 전용 Firehose 전송 스트림을 유지합니다.
   + 이러한 Firehose 스트림은 처리된 로그를 로그 아카이브 계정의 S3 버킷으로 전송합니다. 이 버킷은 데이터 주권 요구 사항을 유지하기 위해 소스 애플리케이션 계정과 동일한 리전(다이어그램의 리전 A)에 있습니다.

1. **알림 및 추가 워크플로**
   + 로그가 대상 S3 버킷에 도달하면 아키텍처는 Amazon SQS를 사용하여 알림 시스템을 구현합니다.
   + 리전 SQS 대기열은 비동기 처리를 활성화하고 저장된 로그를 기반으로 추가 워크플로, 분석 또는 알림 시스템을 트리거하도로 지원합니다.

1. **AWS KMS 보안을 위한**

   아키텍처는 보안 AWS KMS 용를 통합합니다.는 S3 버킷에 대한 암호화 키를 AWS KMS 제공합니다. 이렇게 하면 저장된 모든 로그가 저장 데이터 암호화를 유지하면서, 데이터 레지던시 요구 사항을 충족하도록 리전 암호화를 유지할 수 있습니다.

## 도구
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-tools"></a>

**AWS 서비스**
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)는 모니터링 및 운영 데이터를 로그, 지표 및 이벤트 형태로 수집하는 모니터링 및 관찰성 서비스입니다. AWS 및 온프레미스 서버에서 실행되는 AWS 리소스, 애플리케이션 및 서비스에 대한 통합 보기를 제공합니다.
+ [CloudWatch Logs 구독 필터](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html)는 수신 로그 이벤트의 패턴과 일치하고 추가 처리 또는 분석을 위해 일치하는 로그 이벤트를 지정된 AWS 리소스에 전달하는 표현식입니다.
+ [AWS Control Tower Account Factory For Terraform(AFT)](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html)은에서 계정을 프로비저닝하고 사용자 지정하는 데 도움이 되는 Terraform 파이프라인을 설정합니다 AWS Control Tower. AFT는 Terraform 기반 계정 프로비저닝을 제공하는 동시에 계정을 관리할 수 있습니다 AWS Control Tower.
+ [Amazon Data Firehose](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html)는 Amazon S3, Amazon Redshift, Amazon OpenSearch Service 등의 대상으로 실시간 스트리밍 데이터를 전송하는 완전관리형 서비스입니다. 데이터 처리량에 일치하도록 자동으로 확장되므로 지속적인 관리가 필요하지 않습니다.
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)는 Kubernetes를 사용하여 컨테이너화된 애플리케이션을 쉽게 배포, 관리 및 확장할 수 있는 관리형 컨테이너 오케스트레이션 서비스입니다. 이 서비스는 Kubernetes 컨트롤 플레인 노드의 가용성과 확장성을 자동으로 관리합니다.
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html)는 데이터를 암호화하기 위한 암호화 키를 생성하고 제어합니다.는 이러한 서비스와 함께 저장하는 데이터를 보호하는 AWS 서비스 데 도움이 되도록 다른와 AWS KMS 통합합니다.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)는 서버를 프로비저닝하거나 관리하지 않고도 코드를 실행할 수 있는 서버리스 컴퓨팅 서비스입니다. 각 트리거에 대한 응답으로 코드를 실행하여 애플리케이션을 자동으로 확장하고 사용한 컴퓨팅 시간에 대해서만 요금이 청구됩니다.
+ [Amazon Relational Database Service(Amazon RDS)](https://docs.aws.amazon.com/AmazonRDS/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)는 확장성, 데이터 가용성, 보안 및 성능을 제공하는 클라우드 기반 객체 스토리지 서비스입니다. 이로써 웹을 통해 어디서든 원하는 양의 데이터를 저장하고 검색할 수 있습니다.

**기타 도구**
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.

**코드**

이 패턴의 코드는 GitHub [중앙 집중식 로깅](https://github.com/aws-samples/sample-centralised-logging-at-enterprise-scale-using-terraform) 리포지토리에서 확인할 수 있습니다.

## 모범 사례
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-best-practices"></a>
+ [AWS 계정 의 단일 조직에서 여러을 AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts.html) 사용합니다. 이 방법을 사용하면 계정 간에 중앙 집중식 관리 및 표준화된 로깅이 가능해집니다.
+ [버전 관리, 수명 주기 정책 및 리전 간 복제를 사용하여 S3 버킷](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html)을 구성합니다. 보안 및 규정 준수를 위해 암호화 및 액세스 로깅을 구현합니다.
+ 표준 타임스탬프 및 필드와 함께 [JSON 형식을 사용하여 일반적인 로깅 표준](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_AnalyzeLogData-discoverable-fields.html)을 구현합니다. 손쉬운 추적과 분석을 위해 일관된 접두사 구조와 상관관계 ID를 사용합니다.
+ [AWS KMS 암호화 및 최소 권한 액세스를 통해 보안 제어를](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-best-practices.html) 활성화합니다. 보안 강화를 위해 AWS CloudTrail 모니터링 및 정기적인 키 교체를 유지합니다.
+ 전송 추적을 위한 [CloudWatch 지표 및 알림](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html)을 설정합니다. 자동 알림을 통해 비용과 성능을 모니터링합니다.
+ 규정 준수 요구 사항을 충족하도록 [Amazon S3 보존 정책](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html)을 구성하고 Amazon S3 서버 액세스 로깅을 활성화하여 S3 버킷에 대한 모든 요청을 추적할 수 있습니다. S3 버킷 정책 및 수명 주기 규칙에 대한 설명서를 유지 관리합니다. 액세스 로그, 버킷 권한 및 스토리지 구성을 정기적으로 검토하여 규정 준수 및 [보안 모범 사례](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-best-practices.html)를 보장합니다.

## 에픽
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-epics"></a>

### 설정 AWS Control Tower, AFT 및 애플리케이션 계정
<a name="set-up-ctowerlong-aft-and-application-accounts"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AFT를 사용하여 AWS Control Tower 환경을 설정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | 관리자 | 
| 조직의 공유를 활성화합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | 관리자 | 
| 애플리케이션 계정을 확인하거나 프로비저닝합니다. | 사용 사례에 맞게 새 애플리케이션 계정을 프로비저닝하려면 AFT를 통해 계정을 생성합니다. 자세한 내용은 AWS Control Tower 설명서의 [AFT를 사용하여 새 계정 프로비저닝](https://docs.aws.amazon.com/controltower/latest/userguide/aft-provision-account.html)을 참조하세요. | 관리자 | 

### 애플리케이션 계정에 대한 구성 파일 설정
<a name="set-up-configuration-files-for-application-accounts"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `Application_account` 폴더 콘텐츠를 `aft-account-customizations` 리포지토리에 복사합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 
| 애플리케이션 계정 설정을 위한 입력 파라미터를 검토하고 편집합니다. | 이 단계에서는 CloudWatch 로그 그룹, CloudWatch CloudWatch 구독 필터, IAM 역할 및 정책, Amazon RDS, Amazon EKS 및 Lambda 함수에 대한 구성 세부 정보를 비롯하여 애플리케이션 계정에서 리소스를 생성하기 위한 구성 파일을 설정합니다.`aft-account-customizations` 리포지토리의 `Application_account` 폴더에서 조직의 요구 사항에 따라 `terraform.tfvars` 파일의 입력 파라미터를 구성합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 

### 로그 아카이브 계정에 대한 구성 파일 설정
<a name="set-up-configuration-files-for-the-log-archive-account"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| `Log_archive_account` 폴더 콘텐츠를 `aft-account-customizations` 리포지토리에 복사합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 
| 로그 아카이브 계정 설정을 위한 입력 파라미터를 검토하고 편집합니다. | 이 단계에서는 Firehose 전송 스트림, S3 버킷, SQS 대기열, IAM 역할 및 정책을 비롯하여, 로그 아카이브 계정에서 리소스를 생성하기 위한 구성 파일을 설정합니다.`aft-account-customizations` 리포지토리의 `Log_archive_account` 폴더에서, 조직의 요구 사항에 따라 `terraform.tfvars` 파일의 입력 파라미터를 구성합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 

### Terraform 명령을 실행하여 리소스 프로비저닝
<a name="run-terraform-commands-to-provision-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 옵션 1 - AFT에서 Terraform 구성 파일을 배포합니다. | AFT에서 구성이 변경된 코드를 GitHub `aft-account-customizations` 리포지토리로 푸시하면 AFT 파이프라인이 트리거됩니다. AFT는 변경 사항을 자동으로 감지하고 계정 사용자 지정 프로세스를 시작합니다.Terraform(`terraform.tfvars`) 파일을 변경한 후 변경 사항을 커밋하고 `aft-account-customizations` 리포지토리로 푸시합니다.<pre>$ git add *<br />$ git commit -m "update message"<br />$ git push origin main</pre>다른 브랜치(예: `dev`)를 사용하는 경우 `main`를 브랜치 이름으로 바꿉니다. | DevOps 엔지니어 | 
| 옵션 2 - Terraform 구성 파일을 수동으로 배포합니다. | AFT를 사용하지 않거나 솔루션을 수동으로 배포하려는 경우, `Application_account` 및 `Log_archive_account` 폴더에서 다음 Terraform 명령을 사용할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 

### 리소스 검증
<a name="validate-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 구독 필터를 확인합니다. | 구독 필터가 애플리케이션 계정 로그 그룹에서 로그 아카이브 계정으로 로그를 올바르게 전달하는지 확인하려면:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 
| Firehose 스트림을 확인합니다. | 로그 아카이브 계정의 Firehose 스트림이 애플리케이션 로그를 성공적으로 처리하는지 확인하려면:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 
| 중앙 집중식 S3 버킷을 검증합니다. | 중앙 집중식 S3 버킷이 로그를 올바르게 수신하고 구성하는지 확인하려면:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 
| SQS 대기열을 검증합니다. | SQS 대기열이 새 로그 파일에 대한 알림을 수신하는지 확인하려면:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 

### 리소스 정리
<a name="clean-up-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 옵션 1 - AFT에서 Terraform 구성 파일을 폐기합니다. | Terraform 구성 파일을 제거하고 변경 사항을 푸시하면 AFT가 리소스 제거 프로세스를 자동으로 시작합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 
| 옵션 2 - Terraform 리소스를 수동으로 정리합니다. | AFT를 사용하지 않거나 리소스를 수동으로 정리하려는 경우 `Application_account` 및 `Log_archive_account` 폴더에서 다음 Terraform 명령을 사용합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 엔지니어 | 

## 문제 해결
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| CloudWatch Logs 대상이 생성되지 않았거나 비활성 상태입니다. | 다음 사항을 검증합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | 
| 구독 필터가 실패했거나 보류 중 상태로 멈췄습니다. | 다음을 확인하세요.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | 
| Firehose 전송 스트림에는 수신 레코드가 표시되지 않습니다. | 다음을 확인합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | 

## 관련 리소스
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-resources"></a>
+ [Terraform 인프라 설정](https://developer.hashicorp.com/terraform/tutorials/aws-get-started)(Terraform 설명서)
+ [AWS Control Tower Account Factory for Terraform(AFT) 배포](https://docs.aws.amazon.com/controltower/latest/userguide/aft-getting-started.html)(AWS Control Tower 문서)
+ [IAM 자습서: IAM 역할을 AWS 계정 사용하여 간 액세스 위임](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)(IAMdocumentation)

# cert-manager 및 Let's Encrypt를 사용하여 Amazon EKS의 애플리케이션에 대한 종단 간 암호화 설정
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt"></a>

*Mahendra Revanasiddappa, Vasanth Jeyaraj, Amazon Web Services*

## 요약
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-summary"></a>

종단 간 암호화 구현은 복잡할 수 있으며 마이크로서비스 아키텍처의 각 자산에 대한 인증서를 관리해야 합니다. Network Load Balancer 또는 Amazon API Gateway를 이용하여 Amazon Web Services(AWS) 네트워크 엣지에서 전송 계층 보안(TLS) 연결을 종료할 수 있지만 일부 조직에서는 종단 간 암호화가 필요합니다.

이 패턴은 인그레스에 NGINX Ingress Controller를 사용합니다. Kubernetes 인그레스를 생성할 때 인그레스 리소스가 Network Load Balancer를 사용하기 때문입니다. Network Load Balancer는 클라이언트 인증서 업로드를 허용하지 않습니다. 따라서 Kubernetes 인그레스로는 상호 TLS를 달성할 수 없습니다.

이 패턴은 애플리케이션의 모든 마이크로서비스 간에 상호 인증이 필요한 조직을 위한 것입니다. 상호 TLS는 사용자 이름이나 암호를 유지 관리하는 부담을 줄이고 턴키 보안 프레임워크를 사용할 수도 있습니다. 이 패턴의 접근 방식은 조직에 연결된 디바이스 수가 많거나 엄격한 보안 지침을 준수해야 하는 경우에 적합합니다.

이 패턴을 이용하면 Amazon Elastic Kubernetes Service(Amazon EKS)에서 실행되는 애플리케이션에 대한 종단 간 암호화를 구현하여 조직의 보안 태세를 강화할 수 있습니다. 이 패턴은 GitHub [End-to-end encryption on Amazon EKS](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme) 리포지토리에서 샘플 애플리케이션과 코드를 제공하여 Amazon EKS에서 종단 간 암호화를 사용하여 마이크로서비스가 어떻게 실행되는지 보여 줍니다. 이 패턴의 접근 방식은 [Let's Encrypt](https://letsencrypt.org/)를 인증 기관(CA)으로 사용하는 Kubernetes의 추가 기능인 [cert-manager](https://cert-manager.io/docs/)를 사용합니다. Let's Encrypt는 인증서 관리를 위한 비용 효율적인 솔루션으로 90일 동안 유효한 무료 인증서를 제공합니다. Cert-manager는 Amazon EKS에 새 마이크로서비스를 배포할 때 인증서의 온디맨드 프로비저닝 및 교체를 자동화합니다. 

**대상**

이 패턴은 Kubernetes, TLS, Amazon Route 53 및 도메인 이름 시스템(DNS) 사용 경험이 있는 사용자에게 권장됩니다.

## 사전 조건 및 제한 사항
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정.
+ 기존 Amazon EKS 클러스터.
+ macOS, Linux 또는 Windows에 설치 및 구성된 AWS Command Line Interface(AWS CLI) 버전 1.7 이상.
+ Amazon EKS 클러스터에 액세스하도록 설치 및 구성된 `kubectl` 명령줄 유틸리티. 이에 대한 자세한 내용은 Amazon EKS 설명서의 [kubectl 설치](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)를 참조하세요.
+ 애플리케이션을 테스트하기 위한 기존 DNS 이름. 이에 대한 자세한 내용은 Amazon Route 53 설명서의 [Amazon Route 53을 사용하여 도메인 이름 등록](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar.html)을 참조하세요. 
+ 로컬 컴퓨터에 설치된 [Helm](https://docs.aws.amazon.com/eks/latest/userguide/helm.html) 최신 버전. 이에 대한 자세한 내용은 Amazon EKS 설명서의 [Amazon EKS에 Helm 사용](https://docs.aws.amazon.com/eks/latest/userguide/helm.html) 및 GitHub [Helm](https://github.com/helm/helm) 리포지토리를 참조하세요. 
+ 로컬 시스템에 복제된 GitHub [End-to-end encryption on Amazon EKS](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme) 리포지토리. 
+ 복제된 GitHub [End-to-end encryption on Amazon EKS](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme) 리포지토리의 `policy.json` 및 `trustpolicy.json` 파일에서 다음 값을 바꿉니다.
  + `<account number>`-솔루션을 배포하려는 계정의 AWS 계정 ID로 바꿉니다. 
  + `<zone id>`-도메인 이름의 Route 53 영역 ID로 바꿉니다. 
  + `<node_group_role>`-Amazon EKS 노드와 연결된 AWS Identity and Access Management(IAM) 역할의 이름으로 바꿉니다.
  + `<namespace>`-NGINX Ingress Controller와 샘플 애플리케이션을 배포하는 Kubernetes 네임스페이스로 바꿉니다.
  + `<application-domain-name>`-Route 53의 DNS 도메인 이름으로 바꿉니다.

**제한 사항 **
+ 이 패턴은 인증서를 교체하는 방법을 설명하지 않으며 Amazon EKS의 마이크로서비스에서 인증서를 사용하는 방법만 설명합니다. 

## 아키텍처
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-architecture"></a>

다음 다이어그램은 이 패턴의 워크플로 및 구성 요소를 보여 줍니다.

![\[cert-manager 및 Let's Encrypt를 사용하여 Amazon EKS의 애플리케이션에 대한 암호화를 설정하는 워크플로\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/9aa3ee9e-73db-41f5-a467-b5c47fef496e/images/40692ede-6fb3-474e-8c9e-85c51529e8ad.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. 클라이언트는 DNS 이름으로 애플리케이션 액세스 요청을 보냅니다.

1. Route 53 레코드는 Network Load Balancer에 대한 CNAME입니다.

1. Network Load Balancer는 TLS 리스너로 구성된 NGINX Ingress Controller로 요청을 전달합니다. NGINX Ingress Controller와 Network Load Balancer 간의 통신은 HTTPS 프로토콜을 따릅니다.

1. NGINX Ingress Controller는 애플리케이션 서비스에 대한 클라이언트의 요청에 따라 경로 기반 라우팅을 수행합니다.

1. 애플리케이션 서비스는 애플리케이션 포드로 요청을 전달합니다. 애플리케이션은 보안 암호를 호출하여 동일한 인증서를 사용하도록 설계되었습니다.

1. 포드는 cert-manager 인증서를 사용하여 샘플 애플리케이션을 실행합니다. NGINX Ingress Controller와 포드 간의 통신은 HTTPS를 사용합니다.


| 
| 
| 참고: Cert-manager는 자체 네임스페이스에서 실행됩니다. Kubernetes 클러스터 역할을 사용하여 인증서를 특정 네임스페이스에 보안 암호로 프로비저닝합니다. 해당 네임스페이스를 애플리케이션 포드 및 NGINX Ingress Controller에 연결할 수 있습니다. | 
| --- |

## 도구
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-tools"></a>

**서비스**
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)는 자체 Kubernetes 컨트롤 플레인이나 노드를 설치, 운영 및 유지 관리할 필요 없이 AWS에서 Kubernetes를 실행하는 데 사용할 수 있는 관리형 서비스입니다.
+ [Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)은 여러 대상, 컨테이너 및 IP 주소에 걸쳐 수신되는 트래픽을 자동으로 분산합니다.
+ [AWS Identity and Access Management(IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)를 이용하면 사용자에 대해 인증 및 권한 부여를 제어함으로써 AWS 리소스에 대한 액세스를 안전하게 관리할 수 있습니다.
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html)는 가용성과 확장성이 뛰어난 DNS 웹 서비스입니다.

**기타 도구**
+ [cert-manager](https://cert-manager.io/docs/installation/supported-releases/)는 인증서를 요청하고 Kubernetes 컨테이너에 배포하며 인증서 갱신을 자동화하는 Kubernetes의 추가 기능입니다.
+ [NGINX Ingress Controller](https://kubernetes.github.io/ingress-nginx/)는 Kubernetes 및 컨테이너화된 환경의 클라우드 네이티브 앱을 위한 트래픽 관리 솔루션입니다.

## 에픽
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-epics"></a>

### Route 53을 사용하여 퍼블릭 호스팅 영역 생성 및 구성
<a name="create-and-configure-a-public-hosted-zone-with-route-53"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Route 53에서 퍼블릭 호스팅 영역을 생성합니다. | AWS Management Console에 로그인하여 Amazon Route 53 콘솔을 열고 **호스팅 영역**을 선택한 다음 **호스팅 영역 생성**을 선택합니다. 퍼블릭 호스팅 영역을 생성하고 영역 ID를 기록합니다. 이에 대한 자세한 내용은 Amazon Route 53 설명서의 [퍼블릭 호스팅 영역 생성](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingHostedZone.html)을 참조하세요.ACME DNS01에서는 DNS 공급자를 사용하여 cert-manager가 인증서를 발급하도록 챌린지를 게시합니다. 이 챌린지는 해당 도메인 이름의 TXT 레코드에 특정 값을 입력하여 도메인 이름의 DNS 제어 권한이 사용자에게 있음을 증명하도록 요청합니다. Let’s Encrypt가 ACME 클라이언트에게 토큰을 제공한 후 클라이언트는 해당 토큰과 계정 키에서 파생된 TXT 레코드를 생성하여 해당 레코드를 `_acme-challenge.<YOURDOMAIN>`에 저장합니다. 그런 다음 Let's Encrypt는 해당 레코드에 대해 DNS를 쿼리합니다. 일치하는 항목을 찾으면 인증서 발급을 진행할 수 있습니다. | AWS DevOps | 

### cert-manager가 퍼블릭 호스팅 영역에 액세스할 수 있도록 IAM 역할 구성
<a name="configure-an-iam-role-to-allow-cert-manager-to-access-the-public-hosted-zone"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| cert-manager를 위한 IAM 정책을 생성합니다. | cert-manager에게 사용자가 Route 53 도메인을 소유하고 있는지 확인할 수 있는 권한을 제공하려면 IAM 정책이 필요합니다. `policy.json` 샘플 IAM 정책은 복제된 GitHub [End-to-end encryption on Amazon EKS](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme) 리포지토리의 `1-IAMRole` 디렉터리에 제공됩니다.AWS CLI에 다음 명령을 입력하여 IAM 정책을 생성합니다.<pre>aws iam create-policy \<br />  --policy-name PolicyForCertManager \<br />  --policy-document file://policy.json</pre> | AWS DevOps | 
| cert-manager를 위한 IAM 역할을 생성합니다. | IAM 정책을 생성한 후에는 IAM 역할을 생성해야 합니다. `trustpolicy.json` 샘플 IAM 역할은 `1-IAMRole` 디렉터리에 제공됩니다.AWS CLI에 다음 명령을 입력하여 IAM 역할을 생성합니다.<pre>aws iam create-role \<br />  --role-name RoleForCertManager \<br />  --assume-role-policy-document file://trustpolicy.json</pre> | AWS DevOps | 
| 정책을 역할에 연결합니다. | AWS CLI에 다음 명령을 입력하여 IAM 정책을 IAM 역할에 연결합니다. `AWS_ACCOUNT_ID`를 AWS 계정의 ID로 바꿉니다.<pre>aws iam attach-role-policy \<br />  --policy-arn arn:aws:iam::AWS_ACCOUNT_ID:policy/PolicyForCertManager \<br />  --role-name RoleForCertManager</pre> | AWS DevOps | 

### Amazon EKS에서 NGINX Ingress Controller 설정
<a name="set-up-the-nginx-ingress-controller-in-amazon-eks"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| NGINX Ingress Controller를 배포합니다. | Helm을 사용하여 `nginx-ingress` 최신 버전을 설치합니다. 배포하기 전에 요구 사항에 따라 `nginx-ingress` 구성을 수정할 수 있습니다. 이 패턴은 주석이 달린 내부 Network Load Balancer를 사용하며 이를 `5-Nginx-Ingress-Controller` 디렉터리에서 사용할 수 있습니다. `5-Nginx-Ingress-Controller` 디렉터리에서 다음 Helm 명령을 실행하여 NGINX Ingress Controller를 설치합니다.`helm install test-nginx nginx-stable/nginx-ingress  -f  5-Nginx-Ingress-Controller/values_internal_nlb.yaml` | AWS DevOps | 
| NGINX Ingress Controller가 설치되어 있는지 확인합니다. | `helm list` 명령을 입력합니다. 출력에 NGINX Ingress Controller가 설치되어 있음이 표시되어야 합니다. | AWS DevOps | 
| Route 53 A 레코드를 생성합니다. | A 레코드는 NGINX Ingress Controller에서 생성한 Network Load Balancer를 가리킵니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt.html) | AWS DevOps | 

### Amazon EKS에서 NGINX VirtualServer 설정
<a name="set-up-nginx-virtualserver-on-amazon-eks"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| NGINX VirtualServer를 배포합니다. | NGINX VirtualServer 리소스는 인그레스 리소스 대신 사용할 수 있는 로드 밸런싱 구성입니다. NGINX VirtualServer 리소스를 생성하기 위한 구성은 `6-Nginx-Virtual-Server` 디렉터리의 `nginx_virtualserver.yaml` 파일에서 사용할 수 있습니다. `kubectl`에 다음 명령을 입력하여 NGINX VirtualServer 리소스를 생성합니다.`kubectl apply -f  nginx_virtualserver.yaml``nginx_virtualserver.yaml` 파일에서 애플리케이션 도메인 이름, 인증서 보안 암호 및 애플리케이션 서비스 이름을 업데이트해야 합니다. | DevOps | 
| NGINX VirtualServer가 생성되었는지 확인합니다. | `kubectl`에 다음 명령을 입력하여 NGINX VirtualServer 리소스가 성공적으로 생성되었는지 확인합니다.`kubectl get virtualserver``Host` 열이 애플리케이션의 도메인 이름과 일치하는지 확인하세요. | DevOps | 
| TLS가 활성화된 상태로 NGINX 웹 서버를 배포합니다. | 이 패턴은 TLS가 활성화된 NGINX 웹 서버를 종단 간 암호화를 테스트하기 위한 애플리케이션으로 사용합니다. 테스트 애플리케이션을 배포하는 데 필요한 구성 파일은 `demo-webserver` 디렉터리에서 사용할 수 있습니다. `kubectl`에 다음 명령을 입력하여 테스트 애플리케이션을 배포합니다.`kubectl apply -f nginx-tls-ap.yaml` | AWS DevOps | 
| 테스트 애플리케이션 리소스가 생성되었는지 확인합니다. | `kubectl`에 다음 명령을 입력하여 테스트 애플리케이션에 필요한 리소스가 생성되었는지 확인합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt.html) | DevOps | 
| 애플리케이션을 검증합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt.html) | AWS DevOps | 

## 관련 리소스
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-resources"></a>

**AWS 리소스**
+ [Amazon Route 53 콘솔을 사용하여 레코드 생성](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)(Amazon Route 53 설명서)
+ [Using a Network Load Balancer with the NGINX ingress controller on Amazon EKS](https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/)(AWS Blog 게시물)

**기타 리소스**
+ [Route 53](https://cert-manager.io/docs/configuration/acme/dns01/route53/)(cert-manager 설명서)
+ [Configuring DNS01 Challenge Provider](https://cert-manager.io/docs/configuration/acme/dns01/)(cert-manager 설명서)
+ [Let’s encrypt DNS 챌린지](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge)(Let’s Encrypt 설명서)

# Flux를 사용하여 Amazon EKS 멀티 테넌트 애플리케이션 배포 간소화
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux"></a>

*Nadeem Rahaman, Aditya Ambati, Aniket Dekate, Shrikant Patil, Amazon Web Services*

## 요약
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-summary"></a>

제품 및 서비스를 제공하는 많은 회사는 내부 비즈니스 기능 간에 데이터 장벽을 유지하는 데 필요한 데이터 규제 산업입니다. 이 패턴은 Amazon Elastic Kubernetes Service(Amazon EKS)의 다중 테넌시 기능을 사용하여 단일 Amazon EKS 클러스터를 공유하는 테넌트 또는 사용자 간에 논리적 및 물리적 격리를 달성하는 데이터 플랫폼을 구축하는 방법을 설명합니다. 이 패턴은 다음 접근 방식을 통해 격리를 제공합니다.
+ Kubernetes 네임스페이스 격리
+ 역할 기반 액세스 제어(RBAC)
+ 네트워크 정책
+ 리소스 할당량
+ AWS Identity and Access Management 서비스 계정에 대한 (IAM) 역할(IRSA)

또한이 솔루션은 애플리케이션을 배포할 때 Flux를 사용하여 테넌트 구성을 변경할 수 없도록 유지합니다. 구성에 Flux `kustomization.yaml` 파일이 포함된 테넌트 리포지토리를 지정하여 테넌트 애플리케이션을 배포할 수 있습니다.

이 패턴은 다음을 구현합니다.
+ Terraform 스크립트를 수동으로 배포하여 생성되는 리포지 AWS CodeCommit 토리, AWS CodeBuild 프로젝트 및 AWS CodePipeline 파이프라인입니다.
+ 테넌트를 호스팅하는 데 필요한 네트워크 및 컴퓨팅 구성 요소입니다. 이는 Terraform을 사용하여 CodePipeline 및 CodeBuild를 통해 생성됩니다.
+ 테넌트 네임스페이스, 네트워크 정책 및 리소스 할당량은 Helm 차트를 통해 구성됩니다.
+ Flux를 사용하여 배포된 서로 다른 테넌트에 속하는 애플리케이션.

고유한 요구 사항 및 보안 고려 사항에 따라 멀티테넌시를 위한 자체 아키텍처를 신중하게 계획하고 구축하는 것이 좋습니다. 이 패턴은 구현의 시작점을 제공합니다.

## 사전 조건 및 제한 사항
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정
+ AWS Command Line Interface (AWS CLI) 버전 2.11.4 이상, [설치](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)됨
+ 로컬 시스템에 설치된 [Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) 버전 0.12 이상
+ [Terraform AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest) 버전 3.0.0 이상
+ [Kubernetes Provider](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs) 버전 2.10 이상
+ [Helm Provider](https://registry.terraform.io/providers/hashicorp/helm/latest/docs) 버전 2.8.0 이상
+ [Kubectl Provider](https://registry.terraform.io/providers/gavinbunney/kubectl/latest/docs) 버전 1.14 이상

**제한 사항 **
+ **Terraform 수동 배포에 대한 종속성: ** CodeCommit 리포지토리, CodeBuild 프로젝트 및 CodePipeline 파이프라인 생성을 포함한 워크플로의 초기 설정은 수동 Terraform 배포를 사용합니다. 이로 인해 인프라 변경에 대한 수동 개입이 필요하므로 자동화 및 확장성 측면에서 잠재적 제한이 발생합니다.
+ **CodeCommit 리포지토리 종속성: **워크플로는 CodeCommit 리포지토리를 소스 코드 관리 솔루션으로 사용하며 긴밀하게 연결됩니다 AWS 서비스.

## 아키텍처
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-architecture"></a>

**대상 아키텍처 **

이 패턴은 다음 다이어그램과 같이 세 개의 모듈을 배포하여 데이터 플랫폼의 파이프라인, 네트워크 및 컴퓨팅 인프라를 구축합니다.

*파이프라인 아키텍처:*

![\[Amazon EKS 멀티 테넌트 아키텍처를 위한 파이프라인 인프라\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/97b700a7-74b6-4f9d-b53a-76de42409a8e/images/76a4a23d-4275-427a-ae36-51c9a3803128.png)


*네트워크 아키텍처:*

![\[Amazon EKS 멀티 테넌트 아키텍처를 위한 네트워크 인프라\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/97b700a7-74b6-4f9d-b53a-76de42409a8e/images/e542249a-19a3-4c99-b6f5-fdf80fee4edf.png)


*컴퓨팅 아키텍처:*

![\[Amazon EKS 멀티 테넌트 아키텍처를 위한 컴퓨팅 인프라\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/97b700a7-74b6-4f9d-b53a-76de42409a8e/images/91bd1ca8-17f0-433c-8600-4c8e6c474e31.png)


## 도구
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-tools"></a>

**AWS 서비스**
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 나만의 소스 제어 시스템을 관리할 필요 없이 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 버전 제어 서비스입니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)를 사용하면 자체 Kubernetes 컨트롤 플레인 또는 노드를 설치하거나 유지 관리할 필요 AWS 없이에서 Kubernetes를 실행할 수 있습니다.
+ [AWS Transit Gateway](https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html)는 Virtual Private Cloud(VPC)와 온프레미스 네트워크를 연결하는 중앙 허브입니다.
+ [Amazon Virtual Private Cloud(Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)를 사용하면 정의한 가상 네트워크에서 AWS 리소스를 시작할 수 있습니다. 이 가상 네트워크는 AWS의 확장 가능한 인프라를 사용한다는 이점과 함께 고객의 자체 데이터 센터에서 운영하는 기존 네트워크와 유사합니다.

**기타 도구**
+ [Cilium 네트워크 정책은](https://cilium.io/use-cases/network-policy/#:~:text=Cilium%20implements%20Kubernetes%20Network%20Policies,%2C%20Kafka%2C%20gRPC%2C%20etc.) Kubernetes L3 및 L4 네트워킹 정책을 지원합니다. L7 정책으로 확장하여 HTTP, Kafka, gRPC 및 기타 유사한 프로토콜에 대한 API 수준 보안을 제공할 수 있습니다.
+ [Flux](https://fluxcd.io/)는 Kubernetes에서 애플리케이션 배포를 자동화하는 Git 기반 지속적 전송(CD) 도구입니다.
+ [Helm](https://helm.sh/docs/)은 Kubernetes 클러스터에서 애플리케이션을 설치하고 관리하는 데 도움이 되는 Kubernetes용 소스 패키지 관리자입니다.
+ [Terraform](https://www.terraform.io/)은 HashiCorp의 코드형 인프라(IaC) 도구로, 클라우드 및 온프레미스 리소스를 생성하고 관리하는 데 도움이 됩니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [EKS Multi-Tenancy Terraform Solution](https://github.com/aws-samples/aws-eks-multitenancy-deployment) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-best-practices"></a>

이 구현 사용에 대한 지침과 모범 사례는 다음을 참조하세요.
+ [Amazon EKS 다중 테넌시 모범 사례](https://aws.github.io/aws-eks-best-practices/security/docs/multitenancy/)
+ [Flux 설명서](https://fluxcd.io/flux/get-started/)

## 에픽
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-epics"></a>

### Terraform 빌드, 테스트 및 배포 단계를 위한 파이프라인 생성
<a name="create-pipelines-for-terraform-build-test-and-deploy-stages"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 프로젝트 리포지토리를 복제합니다. | 터미널 창에서 다음 명령을 실행하여 GitHub [EKS Multi-Tenancy Terraform Solution](https://github.com/aws-samples/aws-eks-multitenancy-deployment) 리포지토리를 복제합니다.<pre>git clone https://github.com/aws-samples/aws-eks-multitenancy-deployment.git</pre> | DevOps | 
| Terraform S3 버킷과 Amazon DynamoDB를 부트스트랩합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | DevOps | 
| `run.sh` 및 `locals.tf` 파일을 업데이트합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | DevOps | 
| 파이프라인 모듈을 배포합니다. | 파이프라인 리소스를 생성하려면 다음 Terraform 명령을 수동으로 실행합니다. 이러한 명령을 자동으로 실행하기 위한 오케스트레이션은 없습니다.<pre>./run.sh -m pipeline -e demo -r <AWS_REGION> -t init<br />./run.sh -m pipeline -e demo -r <AWS_REGION> -t plan<br />./run.sh -m pipeline -e demo -r <AWS_REGION> -t apply</pre> | DevOps | 

### 네트워크 인프라 생성
<a name="create-the-network-infrastructure"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 파이프라인을 시작합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html)이 첫 번째 실행 후 CodeCommit 리포지토리 기본 브랜치에 변경 사항을 커밋할 때마다 파이프라인이 자동으로 시작됩니다.파이프라인에는 다음 [단계가](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html#concepts-stages) 포함됩니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | DevOps | 
| 네트워크 모듈을 통해 생성된 리소스를 검증합니다. | 파이프라인이 성공적으로 배포된 후 다음 AWS 리소스가 생성되었는지 확인합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | DevOps | 

### 컴퓨팅 인프라 생성
<a name="create-the-compute-infrastructure"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CodeBuild 프로젝트가 VPC에 액세스할 수 `locals.tf` 있도록 업데이트합니다. | Amazon EKS 프라이빗 클러스터에 대한 추가 기능을 배포하려면 CodeBuild 프로젝트를 Amazon EKS VPC에 연결해야 합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | DevOps | 
| `buildspec` 파일을 업데이트하여 컴퓨팅 모듈을 빌드합니다. | `templates` 폴더의 모든 `buildspec` YAML 파일에서 `TF_MODULE_TO_BUILD` 변수 값을에서 `network`로 설정합니다`compute`.<pre>TF_MODULE_TO_BUILD: "compute"</pre> | DevOps | 
| 테넌트 관리 차트 Helm의 `values` 파일을 업데이트합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | DevOps | 
| 컴퓨팅 리소스를 검증합니다. | 이전 단계에서 파일을 업데이트하면 CodePipeline이 자동으로 시작됩니다. 컴퓨팅 인프라에 대해 다음 AWS 리소스를 생성했는지 확인합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | DevOps | 

### 테넌트 관리 및 기타 리소스 확인
<a name="check-tenant-management-and-other-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| Kubernetes에서 테넌트 관리 리소스를 검증합니다. | 다음 명령을 실행하여 Helm의 도움을 받아 테넌트 관리 리소스가 성공적으로 생성되었는지 확인합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | DevOps | 
| 테넌트 애플리케이션 배포를 확인합니다. | 다음 명령을 실행하여 테넌트 애플리케이션이 배포되었는지 확인합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) |  | 

## 문제 해결
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 다음과 비슷한 오류 메시지가 표시됩니다.`Failed to checkout and determine revision: unable to clone unknown error: You have successfully authenticated over SSH. You can use Git to interact with AWS CodeCommit.` | 문제를 해결하려면 다음 단계를 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | 

## 관련 리소스
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-resources"></a>
+ [Terraform용 Amazon EKS 블루프린트](https://github.com/aws-ia/terraform-aws-eks-blueprints)
+ [Amazon EKS 모범 사례 가이드, 다중 테넌시 섹션](https://aws.github.io/aws-eks-best-practices/security/docs/multitenancy/)
+ [Flux 웹 사이트](https://fluxcd.io/)
+ [Helm 웹 사이트](https://helm.sh/)

## 추가 정보
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-additional"></a>

다음은 테넌트 애플리케이션을 배포하기 위한 리포지토리 구조의 예입니다.

```
applications
sample_tenant_app
├── README.md
├── base
│   ├── configmap.yaml
│   ├── deployment.yaml
│   ├── ingress.yaml
│   ├── kustomization.yaml
│   └── service.yaml
└── overlays
    ├── tenant-1
    │   ├── configmap.yaml
    │   ├── deployment.yaml
    │   └── kustomization.yaml
    └── tenant-2
        ├── configmap.yaml
        └── kustomization.yaml
```

# 자동화된 워크플로를 사용하여 Amazon Lex 봇 개발 및 배포 간소화
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow"></a>

*Balaji Panneerselvam, Attila Dancso, Pavan Dusanapudi, Anand Jumnani 및 James O'Hara, Amazon Web Services*

## 요약
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-summary"></a>

Amazon Lex 대화형 봇을 개발하고 배포하는 것은 여러 기능, 개발자 및 환경을 관리하려고 할 때 어려울 수 있습니다. 코드형 인프라(IaC) 원칙을 사용하는 자동화된 워크플로는 프로세스를 간소화하는 데 도움이 될 수 있습니다. 이 패턴은 Amazon Lex 개발자의 생산성을 개선하고 다음과 같은 방법으로 효율적인 봇 수명 주기 관리를 가능하게 할 수 있습니다.
+ **여러 기능의 동시 개발 활성화** - 자동화된 워크플로를 통해 개발자는 별도의 브랜치에서 다양한 기능을 병렬로 작업할 수 있습니다. 그런 다음 다른 작업을 차단하지 않고 변경 사항을 병합하고 배포할 수 있습니다.
+ **Amazon Lex 콘솔 UI 사용** - 개발자는 사용자 친화적인 Amazon Lex 콘솔을 사용하여 봇을 빌드하고 테스트할 수 있습니다. 그런 다음 배포를 위한 인프라 코드에 봇이 설명되어 있습니다.
+ **환경 간 봇 승격** - 워크플로는 개발 및 테스트와 같은 하위 환경에서 프로덕션까지 봇 버전 승격을 자동화합니다. 이 접근 방식은 수동 프로모션의 리스크와 오버헤드를 줄입니다.
+ **버전 관리 유지** - Amazon Lex 서비스를 통해서만 관리하는 것이 아니라 Git에서 봇 정의를 관리하면 버전 관리 및 감사 추적을 이용할 수 있습니다. AWS Management Console 또는 APIs만 사용하여 저장된 봇을 수정하는 경우와 달리 변경 사항은 개별 개발자에게 추적됩니다 AWS.

Amazon Lex 봇 릴리스 프로세스를 자동화하면 팀은 리스크와 노력을 줄이면서 기능을 더 빠르게 제공할 수 있습니다. 봇은 Amazon Lex 콘솔에서 격리되지 않고 버전 관리를 유지합니다.

## 사전 조건 및 제한 사항
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-prereqs"></a>

**사전 조건**
+ 워크플로에는 계정 관리 및 교차 계정 액세스 구성이 필요한 다양한 환경(개발, 프로덕션 및 DevOps)에 AWS 계정 대한 여러가 포함됩니다.
+ 배포 환경 또는 파이프라인에서 Python 3.9를 사용할 수 있습니다.
+ 소스 제어를 위해 로컬 워크스테이션에 [설치](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 및 구성된 Git입니다.
+ AWS Command Line Interface 명령줄 또는 Python을 사용하여 인증하도록 [설치](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) 및 구성된 (AWS CLI)

**제한 사항**
+ **리포지토리 액세스** - 워크플로는 지속적 통합 및 지속적 전달(CI/CD) 파이프라인에 소스 코드 리포지토리에 변경 사항을 커밋하는 데 필요한 권한이 있다고 가정합니다.
+ **초기 봇 버전 **- 도구를 사용하려면 AWS CloudFormation 템플릿을 사용하여 초기 버전의 봇을 배포해야 합니다. 자동화된 워크플로를 인수하려면 먼저 봇의 첫 번째 반복을 생성하고 리포지토리에 커밋해야 합니다.
+ **병합 충돌** - 워크플로는 동시 개발을 활성화하는 것을 목표로 하지만 다른 브랜치의 변경 사항을 통합할 때 병합 충돌이 발생할 수 있습니다. 봇 구성의 충돌을 해결하려면 수동 개입이 필요할 수 있습니다.

**제품 버전**
+ [Python 3.9](https://www.python.org/downloads/) 이상
+ [AWS CDK v2 2.124.0](https://docs.aws.amazon.com/cdk/api/versions.html) 이상
+ [AWS SDK for Python (Boto3)](https://docs.aws.amazon.com/pythonsdk/)1.28 이상

## 아키텍처
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-architecture"></a>

다음 다이어그램은 솔루션의 상위 수준 아키텍처와 주요 구성 요소를 보여줍니다.

![\[Amazon Lex 봇의 개발 및 배포를 자동화하는 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/3c7f9d16-9708-43c4-afa6-9d804d6b9dad/images/cdc73e82-a777-4e88-8bf8-a73c9bacb47f.png)


주요 구성 요소에 포함되는 사항들은 다음과 같습니다.
+ **Lex 봇 리포지**토리 - Amazon Lex 봇에 대한 IaC 정의를 저장하는 Git 리포지토리입니다.
+ **DevOps** - 개발 및 배포 프로세스를 위한 CI/CD 파이프라인 및 관련 리소스를 수용하는 AWS 계정 전용 입니다.
+ **파이프라인** - 새 봇 생성, 봇 정의 내보내기, 봇 정의 가져오기, 봇 삭제 등 봇 개발 및 배포 수명 주기의 다양한 단계를 자동화하는 AWS CodePipeline 인스턴스입니다.
+ **티켓 봇 및 기본 봇 **- Amazon Lex 봇 리소스로, 여기서 티켓 봇은 개별 팀 또는 개발자가 개발한 기능별 봇이고 기본 봇은 모든 기능을 통합하는 기본 봇입니다.

이 아키텍처 다이어그램은 다음 워크플로를 보여줍니다:

1. **기본 기본 봇 **- 워크플로의 시작점은 개발(Dev) 환경에서 기본 봇의 기준을 지정하는 것입니다. 기본 봇은 향후 개발 및 기능 추가를 위한 기반 역할을 합니다.

1. **티켓 봇 생성 **- 새 기능 또는 변경이 필요한 경우 티켓 봇이 생성됩니다. 티켓 봇은 기본적으로 개발자가 기본 버전에 영향을 주지 않고 작업할 수 있는 기본 봇의 사본 또는 브랜치입니다.

1. **티켓 봇 내보내기 **- 티켓 봇에 대한 작업이 완료되면 Amazon Lex 서비스에서 내보냅니다. 그런 다음 티켓 봇이 포함된 브랜치는 기본 브랜치에서 다시 시작됩니다. 이 단계를 통해 티켓 봇이 개발 중인 동안 기본 봇에 대한 모든 변경 사항을 통합하여 잠재적 충돌을 줄일 수 있습니다.

1. **재기반 티켓 봇 가져오기 및 검증 **- 재기반 티켓 봇을 개발 환경으로 다시 가져오고 기본 브랜치의 최신 변경 사항과 함께 올바르게 작동하는지 검증합니다. 검증에 성공하면 티켓 봇 변경 사항을 기본 브랜치에 병합하는 풀 요청(PR)이 생성됩니다.

1. **티켓 봇 삭제 **- 변경 사항이 기본 브랜치에 성공적으로 병합되면 티켓 봇이 더 이상 필요하지 않습니다. 티켓 봇을 삭제하여 환경을 정리하고 관리할 수 있습니다.

1. **개발 환경에 기본 봇 배포 및 테스트 **- 이제 새로운 기능 또는 변경 사항을 포함하여 업데이트된 기본 봇이 개발 환경에 배포됩니다. 여기서는 모든 기능이 예상대로 작동하는지 확인하기 위해 철저한 테스트를 거칩니다.

1. **프로덕션 환경에 기본 봇 배포 **- 개발 환경에서 테스트가 완료되고 성공하면 기본 봇이 프로덕션 환경에 배포됩니다. 이 단계는 최종 사용자가 새 기능을 사용할 수 있게 되는 워크플로의 마지막 단계입니다.

**자동화 및 규모 조정**

자동화된 워크플로를 통해 개발자는 각각 별도의 브랜치에 있는 다양한 기능을 병렬로 작업할 수 있습니다. 이를 통해 동시 개발을 촉진하여 팀이 효과적으로 협업하고 기능을 더 빠르게 제공할 수 있습니다. 브랜치를 서로 격리하면 진행 중인 다른 작업을 차단하거나 방해하지 않고 변경 사항을 병합하고 배포할 수 있습니다.

워크플로는 개발, 테스트 및 프로덕션과 같은 다양한 환경에서 봇 버전의 배포 및 승격을 자동화합니다.

Git과 같은 버전 관리 시스템에 봇 정의를 저장하면 포괄적인 감사 추적을 제공하고 효율적인 협업이 가능합니다. 개별 개발자에게 변경 사항을 추적하여 개발 수명 주기 전반에 걸쳐 투명성과 책임을 보장합니다. 또한이 접근 방식은 코드 검토를 용이하게 하여 팀이 프로덕션에 배포하기 전에 문제를 식별하고 해결할 수 있도록 합니다.

 AWS CodePipeline 및 기타를 사용하면 자동화된 워크플로 AWS 서비스를 확장하여 증가하는 워크로드와 팀 크기를 수용할 수 있습니다.

## 도구
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-tools"></a>

**AWS 서비스**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)는 친숙한 프로그래밍 언어를 사용하고 이를 통해 프로비저닝하여 코드로 AWS 클라우드 인프라를 정의하기 위한 오픈 소스 소프트웨어 개발 프레임워크입니다 CloudFormation. 이 패턴의 샘플 구현은 Python을 사용합니다.
+ [AWS CDK 명령줄 인터페이스(AWS CDK CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) - AWS CDK 도구 키트는 AWS CDK 앱과 상호 작용하기 위한 기본 도구입니다. 앱을 실행하고, 정의한 애플리케이션 모델을 조사하고, CDK에서 생성한 CloudFormation 템플릿을 생성 및 배포합니다.
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, AWS 계정 및의 수명 주기 동안 리소스를 관리할 수 있습니다 AWS 리전. 이 패턴은 CloudFormation을 사용하여 코드형 인프라를 사용하여 Amazon Lex 봇 구성 및 관련 리소스를 배포합니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다. 이 패턴은 CodeBuild를 사용하여 배포 아티팩트를 빌드하고 패키징합니다.
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다. 이 패턴은 CodePipeline을 사용하여 연속 전달 파이프라인을 오케스트레이션합니다.
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 셸의 명령을AWS 서비스 통해와 상호 작용하는 데 도움이 되는 오픈 소스 도구입니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [Amazon Lex V2](https://docs.aws.amazon.com/lexv2/latest/dg/what-is.html)는 음성 및 텍스트를 사용하는 애플리케이션을 AWS 서비스 위한 대화형 인터페이스(봇)를 구축하기 위한 입니다.
+ [AWS SDK for Python (Boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)는 Python 애플리케이션, 라이브러리 또는 스크립트를와 통합하는 데 도움이 되는 소프트웨어 개발 키트입니다 AWS 서비스.

**기타 도구**
+ [Git](https://git-scm.com/docs)은 오픈 소스 분산 버전 제어 시스템입니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [management-framework-sample-for-amazon-lex](https://github.com/aws-samples/management-framework-sample-for-amazon-lex) 리포지토리에서 사용할 수 있습니다. 코드 리포지토리에는 다음 폴더 및 파일이 포함되어 있습니다.
+ `prerequisite` 폴더 - 필요한 리소스 및 환경을 설정하기 위한 CloudFormation 스택 정의( 사용 AWS CDK)를 포함합니다.
+ `prerequisite/lexmgmtworkflow` 폴더 - 스택 정의 및 Python 코드를 포함한 Lex 관리 워크플로 프로젝트의 기본 디렉터리입니다.
+ `prerequisite/tests` - 단위 테스트를 포함합니다.
+ `src` 폴더 - Amazon Lex 봇 관리 래퍼 및 유틸리티를 포함한 소스 코드 디렉터리입니다.
+ `src/dialogue_lambda` - Amazon Lex 봇과의 대화 중에 사용자 입력을 가로채고 처리하는 대화 후크 Lambda 함수의 소스 코드 디렉터리입니다.

## 모범 사례
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-best-practices"></a>
+ **우려 사항 분리**
  + DevOps, 개발 및 프로덕션 환경 간에 책임을 명확하게 구분합니다.
  + 각 환경에 AWS 계정 대해 별도로 사용하여 적절한 격리 및 보안 경계를 적용합니다.
  + 교차 계정 역할 및 최소 권한 액세스 원칙을 사용하여 환경 간에 액세스를 제어합니다.
+ **코드형 인프라**
  + 모범 사례 및 진화하는 요구 사항에 맞게 인프라 코드를 정기적으로 검토하고 업데이트합니다.
  + 소스 코드 리포지토리에 대한 명확한 분기 및 병합 전략 설정
+ **테스트 및 검증**
  + 파이프라인의 다양한 단계에서 자동 테스트를 구현하여 개발 주기 초기에 문제를 파악합니다.
  + Amazon Lex 콘솔 또는 자동 테스트 프레임워크를 사용하여 상위 환경으로 승격하기 전에 봇 구성 및 기능을 검증합니다.
  + 프로덕션 또는 중요한 환경에 배포하기 위한 수동 승인 게이트를 구현하는 것이 좋습니다.
+ **모니터링 및 로깅 **
  + 파이프라인, 배포 및 봇 상호 작용에 대한 모니터링 및 로깅 메커니즘을 설정합니다.
  + 파이프라인 이벤트, 배포 상태 및 봇 성능 지표를 모니터링하여 문제를 즉시 식별하고 해결합니다.
  + 중앙 집중식 로깅 및 모니터링을 AWS X-Ray 위해 Amazon CloudWatch AWS CloudTrail및와 같은 AWS 서비스를 사용합니다.
  + 자동화된 워크플로의 성능, 효율성 및 효과를 정기적으로 검토하고 분석합니다.
+ **보안 및 규정 준수**
  + 보안 코딩 사례를 구현하고 Amazon Lex 봇 개발 및 배포에 대한 AWS 보안 모범 사례를 따릅니다.
  + 최소 권한 원칙에 따라 IAM 역할, 정책 및 권한을 정기적으로 검토하고 업데이트합니다.
  + 보안 스캔 및 규정 준수 검사를 파이프라인에 통합하는 것이 좋습니다.

## 에픽
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-epics"></a>

### Amazon Lex 봇 관리를 위한 IaC 설정
<a name="set-up-iac-for-lex2-bot-management"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 로컬 CDK 환경을 설정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.html) | DevOps | 
| `devops` 환경에서 교차 계정 역할을 생성합니다. | `devops` 계정은 CI/CD 파이프라인을 호스팅하고 관리할 책임이 있습니다. CI/CD 파이프라인이 `dev` 및 `prod` 환경과 상호 작용할 수 있도록 하려면 다음 명령을 실행하여 `devops` 계정에서 교차 계정 역할을 생성합니다.<pre>cdk bootstrap --profile=devops<br /><br />cdk deploy LexMgmtDevopsRoleStack -c dev-account-id=2222222222222 -c prod-account-id=333333333333 --profile=devops</pre> | DevOps | 
| `dev` 환경에서 교차 계정 역할을 생성합니다. | `dev` 계정이이 역할을 수임하도록 허용하는 데 필요한 권한이 있는 IAM 역할을 `devops` 계정에 생성합니다. CI/CD 파이프라인은이 역할을 사용하여 `dev` 계정에서 Amazon Lex 봇 리소스 배포 및 관리와 같은 작업을 수행합니다.IAM 역할을 생성하려면 다음 명령을 실행합니다.<pre>cdk bootstrap --profile=dev<br /><br />cdk deploy LexMgmtCrossaccountRoleStack -c devops-account-id=1111111111111 --profile=dev</pre> | DevOps | 
| `prod` 환경에서 교차 계정 역할을 생성합니다. | `prod` 계정이이 역할을 수임하도록 허용하는 데 필요한 권한이 있는 IAM 역할을 `devops` 계정에 생성합니다. CI/CD 파이프라인은이 역할을 사용하여 `prod` 계정에서 Amazon Lex 봇 리소스 배포 및 관리와 같은 작업을 수행합니다.<pre>cdk bootstrap --profile=prod<br /><br />cdk deploy LexMgmtCrossaccountRoleStack -c devops-account-id=1111111111111 --profile=prod</pre> | DevOps | 
| `devops` 환경에서 파이프라인을 생성합니다. | Amazon Lex 봇의 개발 워크플로를 관리하려면 다음 명령을 실행하여 `devops` 환경에서 파이프라인을 설정합니다.<pre>cdk deploy LexMgmtWorkflowStack -c devops-account-id=1111111111111 -c dev-account-id=2222222222222 -c prod-account-id=333333333333 --profile=devops</pre> | DevOps | 

### 기본 봇의 기준 설정
<a name="establish-the-baseline-for-the-main-bot"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 기본 봇의 초기 버전을 정의합니다. | 기본 봇의 초기 버전을 정의하려면 `BaselineBotPipeline` 파이프라인을 [트리거](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html#concepts-triggers)합니다.파이프라인은 CloudFormation 템플릿에 정의된 기본 봇 정의를 배포하고, 기본 봇 정의를 .json 파일로 내보내고, 버전 관리 시스템에 기본 봇 코드를 저장합니다. | DevOps | 

### 기능 개발 워크플로 구현
<a name="implement-the-feature-development-workflow"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 티켓 봇을 생성하여 기능을 개발하고 테스트합니다. | `TicketBot`는 기능 브랜치의 기존 기본 봇 정의에서 가져온 새 봇 인스턴스입니다. 이 접근 방식을 사용하면 새 봇이 기본 봇의 모든 현재 기능과 구성을 갖게 됩니다.티켓 봇의 초기 버전을 정의하려면 `CreateTicketBotPipeline` 파이프라인을 트리거합니다.파이프라인은 버전 관리 시스템에 새 기능 브랜치를 생성하고 기본 봇을 기반으로 새 티켓 봇 인스턴스를 생성합니다. | Lex 봇 개발자 | 
| 티켓 봇 기능을 개발하고 테스트합니다. | 기능을 개발하고 테스트하려면에 로그인 AWS Management Console 하고 [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/) Amazon Lex 콘솔을 엽니다. 자세한 내용은 Amazon Lex 설명서의 [콘솔을 사용하여 봇 테스트를](https://docs.aws.amazon.com/lexv2/latest/dg/test-bot.html) 참조하세요.이제 `TicketBot` 인스턴스를 사용하여 봇의 기능을 추가, 수정 또는 확장하여 새 기능을 구현할 수 있습니다. 예를 들어 의도, 발화, 슬롯 및 대화 흐름을 생성하거나 수정할 수 있습니다. 자세한 내용은 Amazon Lex 설명서의 [의도 추가](https://docs.aws.amazon.com/lexv2/latest/dg/add-intents.html)를 참조하십시오. | Lex 봇 개발자 | 
| 티켓 봇 정의를 내보냅니다. | 내보낸 봇 정의는 기본적으로 봇의 구성 및 기능을 JSON 형식으로 표현한 것입니다.티켓 봇 정의를 내보내려면 `ExportTicketBotPipeline` 파이프라인을 트리거합니다.파이프라인은 티켓 봇 정의를 .json 파일로 내보내고 티켓 봇 코드를 버전 관리 시스템의 기능 브랜치에 저장합니다. | Lex 봇 개발자 | 
| 최신 기본 브랜치에서 기능 브랜치를 리베이스합니다. | 새 기능을 개발하는 동안 기본 브랜치는 다른 개발자 또는 팀으로부터 다른 변경 사항을 수신했을 수 있습니다.이러한 변경 사항을 기능 브랜치에 통합하려면 Git `rebase` 작업을 수행합니다. 이 작업은 기본적으로 기본 브랜치의 최신 커밋 위에 특성 브랜치의 커밋을 재생하여 특성 브랜치에 모든 최신 변경 사항이 포함되도록 합니다. | Lex 봇 개발자 | 
| 기반 티켓 봇을 가져오고 검증합니다. | 특성 브랜치를 리베이스한 후 티켓 봇 인스턴스로 가져와야 합니다. 이 가져오기는 기존 티켓 봇을 기반 브랜치의 최신 변경 사항으로 업데이트합니다.기반 티켓 봇을 가져오려면 `ImportTicketBotPipeline` 파이프라인을 트리거합니다.파이프라인은 버전 관리 시스템의 기능 브랜치에 있는 티켓 봇 정의 .json 파일을 `TicketBot` 인스턴스로 가져옵니다. | Lex 봇 개발자 | 
| 기반 봇 정의를 검증합니다. | 기반 봇 정의를 가져온 후에는 기능을 검증하는 것이 중요합니다. 새 기능이 예상대로 작동하고 기존 기능과 충돌하지 않도록 하려고 합니다.이 검증에는 일반적으로 다양한 입력 시나리오로 봇을 테스트하고, 응답을 확인하고, 봇이 의도한 대로 작동하는지 확인하는 작업이 포함됩니다. 다음 방법 중 하나로 검증을 수행할 수 있습니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.html) | Lex 봇 개발자 | 
| 기능 브랜치를 기본 브랜치로 병합합니다. | 격리된 `TicketBot` 인스턴스에서 새 기능을 개발하고 테스트한 후 다음을 수행합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.html) | Lex Bot Developer, 리포지토리 관리자 | 
| 기능 브랜치와 티켓 봇을 삭제합니다. | 특성 브랜치가 기본 브랜치에 성공적으로 병합되면 소스 코드 리포지토리에서 특성 브랜치와 티켓 봇을 삭제합니다.기능 브랜치와 티켓 봇을 삭제하려면 `DeleteTicketBotPipeline` 파이프라인을 트리거합니다.파이프라인은 개발 프로세스 중에 생성된 임시 봇 리소스(예: 티켓 봇)를 제거합니다. 이 작업은 클린 리포지토리를 유지하고 향후 기능 브랜치와의 혼동 또는 충돌을 방지하는 데 도움이 됩니다. | Lex 봇 개발자 | 

### 기본 봇 유지 관리
<a name="maintain-the-main-bot"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 최신 기본 봇 정의를 `dev` 환경으로 가져옵니다. | 기본 브랜치의 최신 기본 봇 정의를 `dev` 환경으로 가져오려면 `DeployBotDevPipeline` 파이프라인을 트리거합니다.파이프라인은 승인 시 git 태그도 생성합니다. | DevOps | 
| 최신 기본 봇 정의를 `prod` 환경으로 가져옵니다. | 기본 브랜치의 최신 봇 정의를 `prod` 환경으로 가져오려면 이전 작업의 태그 참조를 파라미터로 제공하고 `DeployBotProdPipeline` 파이프라인을 트리거합니다.파이프라인은 특정 태그에서 `prod` 환경으로 최신 봇 정의를 가져옵니다. | DevOps | 

## 문제 해결
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| Amazon Lex 봇을 다른에 배포하는 경우 도구 서비스에는 해당 계정 AWS 계정의 리소스에 액세스하는 데 필요한 권한이 있어야 합니다. | 교차 계정 액세스 권한을 부여하려면 IAM 역할 및 정책을 사용합니다. 대상 계정에서 IAM 역할을 생성하고 필요한 권한을 부여하는 역할에 정책을 연결합니다. 그런 다음 Amazon Lex 봇이 배포된 계정에서 이러한 역할을 수임합니다.자세한 내용은 Amazon Lex 설명서의 Lex V2에서 봇을 내보내는 데 [필요한 IAM 권한 및 가져오기](https://docs.aws.amazon.com/lexv2/latest/dg/import.html#import-permissions)에 필요한 IAM 권한을 참조하세요. [ V2](https://docs.aws.amazon.com/lexv2/latest/dg/export.html#export-permissions)  | 

## 관련 리소스
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-resources"></a>
+ [Amazon Lex V2에서 봇 가져오기](https://docs.aws.amazon.com/lexv2/latest/dg/import.html)
+ [CodePipeline에서 파이프라인 시작](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-about-starting.html)
+ [Amazon Lex V2 봇 작업](https://docs.aws.amazon.com/lexv2/latest/dg/building-bots.html)

# AWS Fargate WaitCondition 후크 구성을 사용하여 리소스 종속성과 작업 실행을 조정합니다.
<a name="use-the-aws-fargate-waitcondition-hook-construct"></a>

*Stan Fan, Amazon Web Services*

## 요약
<a name="use-the-aws-fargate-waitcondition-hook-construct-summary"></a>

이 패턴은 Amazon Elastic Container Service(Amazon ECS`waitcondition-hook-for-aws-fargate-task`) 클러스터에서 [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html) 작업을 오케스트레이션하기 위해 설계된 클라우드 네이티브 솔루션인 WaitCondition 후크() npm 패키지를 설명합니다.

WaitCondition 후크는 통합에 맞게 특별히 조정된 AWS Cloud Development Kit (AWS CDK) 구문입니다 AWS CloudFormation. WaitCondition 후크는 다음과 같은 주요 기능을 제공합니다.
+ 대기 조건 메커니즘으로 작동하여 지정된 Fargate 작업이 완료될 때까지 CloudFormation 스택 실행을 일시 중지하므로 정렬된 배포 및 리소스 프로비저닝에 도움이 됩니다.
+ TypeScript 및 Python을 지원하므로 AWS CDK 프로젝트에 적합합니다.
+ 개발자와 아키텍트가에서 컨테이너화된 애플리케이션의 작업 완료 및 리소스 관리를 조정하여 배포를 오케스트레이션할 수 있습니다 AWS.
+ CloudFormation 수명 주기에 포함된 하나 이상의 컨테이너를 사용하여 Fargate 작업을 실행할 수 있습니다. 및는 작업 실패를 처리하고 작업 실패 후 CloudFormation 스택을 롤백할 수 있습니다.
+ 리소스와 Fargate 작업 실행 결과 간에 종속성을 추가할 수 있는 유연성을 제공하여 사용자 지정 작업을 활성화하거나 다른 엔드포인트를 간접적으로 호출할 수 있습니다. 예를 들어 CloudFormation 스택을 일시 중지하고 데이터베이스 마이그레이션(Fargate 작업으로 완료)을 기다리고 데이터베이스 마이그레이션의 성공에 의존할 수 있는 다른 리소스를 프로비저닝할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="use-the-aws-fargate-waitcondition-hook-construct-prereqs"></a>

**사전 조건 **
+ 활성. AWS 계정
+ AWS Cloud Development Kit (AWS CDK) 로컬 워크스테이션에 설치된 명령줄 인터페이스(CLI)입니다. 자세한 내용은 AWS CDK 설명서의 [AWS CDK CLI 참조](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)를 참조하세요.
+ 로컬 워크스테이션에 설치되고 [TypeScript에서AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-typescript.html)에 대해 구성된 노드 패키지 관리자(npm). 자세한 내용은 npm 설명서의 [Node.js 및 npm 다운로드 및 설치](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)를 참조합니다.
+ 로컬 워크스테이션에 설치된 Yarn입니다. 자세한 내용은 설명서에서 Installation을 참조하세요.

**제한 사항 **
+ 이 솔루션은 단일에 배포됩니다 AWS 계정.
+ 컨테이너의 예상 반환 코드는 성공을 `0` 위한 것입니다. 다른 모든 반환 코드는 실패를 나타내며 CloudFormation 스택이 롤백됩니다.
+ 일부 AWS 서비스 는 전혀 사용할 수 없습니다 AWS 리전. 리전 가용성은 [리전별AWS 서비스](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) 섹션을 참조하세요. 구체적인 엔드포인트는 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하고 서비스 링크를 선택합니다.

## 아키텍처
<a name="use-the-aws-fargate-waitcondition-hook-construct-architecture"></a>

다음 다이어그램은 아키텍처입니다.

![\[waitcondition-hook-for-aws-fargate-task 구문의 AWS Step Functions 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/e58680e3-f89f-422f-b0e1-e85605ae8bf9/images/598020df-908c-4486-9844-c05af759c18a.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. `WaitCondition` 및 `WaitConditionHandler`는 AWS Lambda 함수의 응답을 수신하도록 프로비저닝됩니다.

1. 작업 결과에 따라 `CallbackFunction` 또는 `ErrorHandlerFunction`가 Fargate 작업 완료에 의해 트리거됩니다.

1. Lambda 함수는 SUCCEED 또는 FAILURE 신호를에 전송합니다`WaitConditionHandler`.

1. `WaitConditionHandler` Fargate 작업의 실행 결과가 성공하면는 리소스를 계속 프로비저닝하고, 작업이 실패하면 스택을 롤백합니다.

다음 다이어그램은 데이터베이스 마이그레이션을 수행하는 워크플로의 예를 보여줍니다.

![\[WaitCondition 후크 구성을 사용한 Amazon RDS 데이터베이스 마이그레이션 워크플로입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/e58680e3-f89f-422f-b0e1-e85605ae8bf9/images/3b83fc2a-80bb-4ba9-9637-782060493cf0.png)


예시 워크플로는 다음과 같이 `waitcondition-hook-for-aws-fargate-task` 구문을 사용하여 데이터베이스 마이그레이션을 수행합니다.

1. Amazon Relational Database Service(RDS) 인스턴스

1. `waitcondition-hook-for-aws-fargate-task` 구문은 데이터베이스 마이그레이션 작업을 실행하고 스택을 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스로 일시 중지합니다.

1. 마이그레이션 작업이 성공적으로 완료되면 CloudFormation에 성공 신호를 보냅니다. 그렇지 않으면 CloudFormation에 실패 신호를 보내고 스택을 롤백합니다.

## 도구
<a name="use-the-aws-fargate-waitcondition-hook-construct-tools"></a>

**서비스**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)는 코드에서 클라우드 인프라를 정의하고 프로비저닝하는 데 도움이 되는 소프트웨어 개발 프레임워크입니다 CloudFormation.
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)를 사용하면 AWS 리소스를 설정하고, 빠르고 일관되게 프로비저닝하고, AWS 계정 및의 수명 주기 동안 리소스를 관리할 수 있습니다 AWS 리전.
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)를 사용하면 AWS 리소스 및에서 실행되는 애플리케이션의 지표를 실시간으로 모니터링할 AWS 수 있습니다.
+ [Amazon Elastic Container Service(Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)는 클러스터에서 컨테이너를 실행, 중지 및 관리하는 데 도움이 되는 빠르고 확장 가능한 컨테이너 관리 서비스입니다.
+ [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html)를 사용하면 서버 또는 Amazon EC2 인스턴스를 관리할 필요 없이 컨테이너를 실행할 수 있습니다. Amazon ECS와 함께 사용됩니다.
+ [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)는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행하는 데 도움이 되는 컴퓨팅 서비스입니다. 필요할 때만 코드를 실행하며 자동으로 확장이 가능하므로 사용한 컴퓨팅 시간만큼만 비용을 지불합니다.
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)는 AWS Lambda 함수 및 기타를 결합하여 비즈니스 크리티컬 애플리케이션을 구축하는 AWS 서비스 데 도움이 되는 서버리스 오케스트레이션 서비스입니다.
+ [Amazon Virtual Private Cloud(Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)를 사용하면 정의한 가상 네트워크에서 AWS 리소스를 시작할 수 있습니다. 이 가상 네트워크는 AWS의 확장 가능한 인프라를 사용한다는 이점과 함께 고객의 자체 데이터 센터에서 운영하는 기존 네트워크와 유사합니다.

**기타 도구**
+ [npm](https://docs.npmjs.com/about-npm)은 Node.js 환경에서 실행되는 소프트웨어 레지스트리로, 패키지를 공유 또는 대여하고 개인 패키지의 배포를 관리하는 데 사용됩니다.
+ [Yarn](https://yarnpkg.com/)은 JavaScript 프로젝트의 종속성을 관리하는 데 사용할 수 있는 오픈 소스 패키지 관리자입니다. Yarn은 패키지 종속성을 설치, 업데이트, 구성 및 제거하는 데 도움이 될 수 있습니다.

**코드 리포지토리**

이 패턴의 코드는 GitHub [waitcondition-hook-for-aws-fargate-task](https://github.com/aws-samples/waitcondition-hook-for-aws-fargate-task) 리포지토리에서 사용할 수 있습니다.

## 모범 사례
<a name="use-the-aws-fargate-waitcondition-hook-construct-best-practices"></a>
+  AWS CDK 앱을 빌드할 때는 AWS CDK v2 설명서의 [를 사용하여 클라우드 인프라를 개발하고 배포하는 모범 사례를 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html) 따르세요.
+  AWS Fargate 태스크의 경우 [Amazon ECS 설명서의 Amazon ECS 컨테이너 이미지 모범 사례를](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/application.html) 따릅니다.

## 에픽
<a name="use-the-aws-fargate-waitcondition-hook-construct-epics"></a>

### 설정 AWS CDK
<a name="set-up-the-cdk"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 를 설치합니다 AWS CDK. | 로컬 시스템 또는 기타 환경에 AWS CDK 를 설치하려면 다음 명령을 실행합니다.<pre>npm install -g aws-cdk@latest</pre> | 클라우드 아키텍트, 앱 개발자 | 
| 를 부트스트랩합니다 AWS CDK. | [부트스트래핑](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)은 배포를 위한 [환경을](https://docs.aws.amazon.com/cdk/v2/guide/environments.html) 준비하는 프로세스입니다. 대상 AWS 계정 및에 대한 AWS CDK 도구 키트를 부트스트랩하려면 다음 명령을 AWS 리전실행합니다.<pre>cdk bootstrap aws://ACCOUNT-NUMBER-1/REGION-1 </pre>이 명령은 라는 CloudFormation 스택을 생성합니다`CDKToolkit`. | 클라우드 아키텍트 | 

### AWS Fargate 작업 구성에 대한 WaitCondition 후크 실행
<a name="run-the-waitcondition-hook-for-fargatelong-tasks-construct"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CDK 프로젝트 만들기 | 원하는 언어를 사용하여 CDK 프로젝트를 생성합니다. 이 패턴은 TypeScript를 사용합니다. TypeScript를 사용하여 CDK 프로젝트를 생성하려면 다음 명령을 실행합니다.`cdk init app —language typescript` | 클라우드 아키텍트 | 
|  패키지를 설치합니다. | CDK 프로젝트의 루트 경로`npm install`에서를 실행합니다. CDK 라이브러리를 설치한 후 다음 명령을 실행하여를 설치합니다. `waitcondition-hook-for-aws-fargate-task` `yarn add waitcondition-hook-for-aws-fargate-task` | 클라우드 아키텍트 | 
| CDK 애플리케이션 및 Amazon ECS 구성 요소를 빌드합니다. | 프로젝트를 빌드합니다. Amazon ECS 작업 정의 리소스가 필요합니다. 이에 대한 자세한 내용은 Amazon ECS 설명서의 [작업 정의 생성](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)을 참조하십시오.이 예제에서는 다음 구성 파일을 사용합니다.<pre>import * as cdk from 'aws-cdk-lib';<br />import { Vpc } from 'aws-cdk-lib/aws-ec2';<br />import * as ecr from 'aws-cdk-lib/aws-ecr';<br />import * as ecs from 'aws-cdk-lib/aws-ecs';<br />import { Construct } from 'constructs';<br />import { FargateRunner } from 'waitcondition-hook-for-aws-fargate-task';<br />import { Queue } from 'aws-cdk-lib/aws-sqs';<br /><br />export class FargateRunnerStack extends cdk.Stack {<br />    constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br />        super(scope, id, props);<br />        // Define the VPC<br />        const vpc = new Vpc(this, 'MyVpc')<br />        // Define the Fargate Task<br />        const taskDefinition = new ecs.FargateTaskDefinition(this, 'MyTask', {});<br />        // Import exiting ecr repo<br />        const repo = ecr.Repository.fromRepositoryName(this, 'MyRepo', 'RepoName');<br />        // Add a container to the task<br />        taskDefinition.addContainer('MyContainer', {<br />            image: ecs.ContainerImage.fromEcrRepository(repo),<br />        });<br />        // Create the Fargate runner<br />        const myFargateRunner = new FargateRunner(this, 'MyRunner', {<br />            fargateTaskDef: taskDefinition,<br />            timeout: `${60 * 5}`,<br />            vpc: vpc,<br />        });<br />        // Create the SQS queue<br />        const myQueue = new Queue(this, 'MyQueue', {});<br />        // Add dependency<br />        myQueue.node.addDependency(myFargateRunner);<br />    }<br />}</pre> | 클라우드 아키텍트 | 
| CDK 애플리케이션을 동기화하고 시작합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)`waitcondition-hook-for-aws-fargate-task` 구문은 Fargate 작업을 실행합니다. | 클라우드 아키텍트 | 

### 정리
<a name="clean-up"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 리소스를 정리하십시오. | 이전 단계에서 프로비저닝된 리소스를 정리하려면 다음 명령을 실행합니다.<pre>cdk destroy </pre> | 클라우드 아키텍트 | 

## 문제 해결
<a name="use-the-aws-fargate-waitcondition-hook-construct-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 일반 CloudFormation 스택 실패 | 일반적인 CloudFormation 스택 실패 문제를 해결하려면 다음 예시와 같이 `--no-rollback` 플래그를 추가합니다.<pre>cdk deploy --no-rollback</pre>이 명령은 CloudFormation 스택이 롤백되지 않도록 일시 중지하여 문제를 해결할 리소스를 제공합니다. 자세한 내용은 CloudFormation 설명서의 [리소스 프로비저닝 시 실패를 처리하는 방법 선택을](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-failure-options.html) 참조하세요. | 
| AWS Step Functions 실패 |  AWS Step Functions 상태 머신은 여러 가지 이유로 실행되지 않을 수 있습니다. 가 `—disable-rollback` 구성된 경우 다음 단계를 사용하여 문제를 해결합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)자세한 내용은 AWS Step Functions 설명서[의 Step Functions에서 문제 해결](https://docs.aws.amazon.com/step-functions/latest/dg/troubleshooting.html) 및 [Step Functions 콘솔에서 실행 세부 정보 보기를](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-view-execution-details.html#exec-details-intf-step-details) 참조하세요. | 
| AWS Lambda 함수 실패 | 이 구문은 `CallbackFunction` 및 라는 두 가지 Lambda 함수를 프로비저닝합니다`ErrorhandlerFunction`. 처리되지 않은 예외와 같은 다양한 이유로 실패할 수 있습니다. 문제 해결을 위해 다음 단계를 시도하세요: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)자세한 내용은 AWS Lambda 설명서[의 Lambda 문제 해결을](https://docs.aws.amazon.com/lambda/latest/dg/lambda-troubleshooting.html) 참조하세요. | 

## 관련 리소스
<a name="use-the-aws-fargate-waitcondition-hook-construct-resources"></a>

**AWS 설명서**
+ [AWS CDK 구문 API 참조](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)
+ [시작하기 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
+ [Amazon ECS 리소스를 생성하고 사용하는 방법을 알아봅니다.](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/getting-started.html)
+ [Step Functions를 시작하는 방법 알아보기](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)
+ [란 무엇입니까 AWS CDK?](https://docs.aws.amazon.com/cdk/v2/guide/home.html)

**기타 리소스**
+ [AWS Fargate 작업에 대한 Waitcondition 후크](https://pypi.org/project/waitcondition-hook-for-aws-fargate-task/)(npm)
+ [waitcondition-hook-for-aws-fargate-task 1.0.6](https://pypi.org/project/waitcondition-hook-for-aws-fargate-task/)(pypi.org)

# AWS CodePipeline의 타사 Git 소스 리포지토리 사용
<a name="use-third-party-git-source-repositories-in-aws-codepipeline"></a>

*Kirankumar Chandrashekar, Amazon Web Services*

## 요약
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-summary"></a>

이 패턴은 서드파티 Git 소스 리포지토리와 함께 AWS CodePipeline을 사용하는 방법을 설명합니다.

[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts-continuous-delivery-integration.html)은 소프트웨어 구축, 테스트 및 배포 작업을 자동화하는 지속적 전달 서비스입니다. 서비스는 현재 GitHub, [AWS CodeCommit](https://aws.amazon.com/codecommit) 및 Atlassian Bitbucket에서 관리하는 Git 리포지토리를 지원합니다. 그러나 일부 기업은 AWS Single Sign-On(SSO) 서비스 및 Microsoft Active Directory와 통합된 타사 Git 리포지토리를 인증에 사용합니다. 사용자 지정 작업 및 웹후크를 생성하여 이러한 타사 Git 리포지토리를 CodePipeline의 소스로 사용할 수 있습니다.

Webhook는 GitHub 리포지토리 등의 다른 도구에서 이벤트를 감지하고 해당 외부 이벤트를 파이프라인에 연결하는 HTTP 알림입니다. CodePipeline에서 웹후크를 만들면 서비스가 Git 리포지토리 웹후크에서 사용할 수 있는 URL을 반환합니다. Git 리포지토리의 특정 브랜치로 코드를 푸시하면 Git 웹후크가 이 URL을 통해 CodePipeline 웹후크를 시작하고 파이프라인의 소스 단계를 **진행 중**으로 설정합니다. 파이프라인이 이 상태이면 작업 워커는 CodePipeline에서 사용자 지정 작업을 폴링하고, 작업을 실행하고, 성공 또는 실패 상태를 CodePipeline에 보냅니다. 이 경우 파이프라인이 소스 단계에 있으므로 작업 워커는 Git 리포지토리의 콘텐츠를 가져와 콘텐츠를 압축한 다음 폴링된 작업에서 제공한 객체 키를 사용하여 파이프라인의 아티팩트가 저장되는 Amazon Simple Storage Service(S3) 버킷에 업로드합니다. 또한 사용자 지정 작업에 대한 전환을 Amazon CloudWatch의 이벤트와 연결하고 이벤트를 기반으로 작업 작업자를 시작할 수 있습니다. 이 설정을 사용하면 서비스에서 기본적으로 지원하지 않는 서드파티 Git 리포지토리를 CodePipeline의 소스로 사용할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정
+ 웹후크를 지원하고 인터넷을 통해 코드파이프라인 웹후크 URL에 연결할 수 있는 Git 리포지토리 
+ AWS Command Line Interface (AWS CLI)가 AWS 계정과 함께 작동하도록 [설치](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) 및 [구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)

## 아키텍처
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-architecture"></a>

패턴에는 다음 단계가 포함됩니다.

1. 사용자가 Git 리포지토리에 코드를 커밋합니다.

1. Git 웹후크를 호출합니다.

1. CodePipeline 웹후크가 호출됩니다.

1. 파이프라인은 **진행 중**으로 설정되고 소스 단계는 **진행 중** 상태로 설정됩니다.

1. 소스 스테이지 작업은 시작되었음을 나타내는 CloudWatch Events 규칙을 시작합니다.

1. CloudWatch 이벤트는 Lambda 함수를 시작합니다.

1. Lambda 함수는 사용자 지정 실행 작업의 세부 정보를 가져옵니다.

1. Lambda 함수는 AWS CodeBuild를 시작하고 모든 작업 관련 정보를 전달합니다.

1. CodeBuild는 Secrets Manager로부터 HTTPS Git 액세스를 위한 공개 SSH 키 또는 사용자 보안 인증 정보를 가져옵니다.

1. CodeBuild는 특정 브랜치의 Git 리포지토리를 복제합니다.

1. CodeBuild는 아카이브를 압축하여 CodePipeline 아티팩트 스토어 역할을 하는 S3 버킷에 업로드합니다.

![\[서드 파티 Git 소스 리포지토리를 AWS CodePipeline의 소스로 사용하는 워크플로.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/84284bec-b39d-466a-9fd9-994be2c953df/images/85555dab-7317-40f5-86a7-ccb8987c5bf3.png)


 

## 도구
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-tools"></a>
+ [AWS CodePipeline](https://aws.amazon.com/codepipeline/) – AWS CodePipeline은 빠르고 안정적인 애플리케이션 및 인프라 업데이트를 위해 릴리스 파이프라인을 자동화하는 데 사용할 수 있는 완전관리형 [지속적 제공](https://aws.amazon.com/devops/continuous-delivery/) 서비스입니다. CodePipeline은 정의한 릴리스 모델을 기반으로 각 코드 변경에 대한 릴리스 프로세스의 빌드, 테스트 및 배포 단계를 자동화합니다. 이를 통해 기능과 업데이트를 신속하고 안정적으로 제공할 수 있습니다. AWS CodePipeline을 GitHub 같은 타사 서비스 또는 자체 사용자 지정 플러그인과 통합할 수 있습니다.
+ [AWS Lambda](https://aws.amazon.com/lambda/) – AWS Lambda는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행할 수 있습니다. Lambda를 사용하면 관리할 필요 없이 거의 모든 유형의 애플리케이션 또는 백엔드 서비스에 대한 코드를 실행할 수 있습니다. 코드를 업로드하면 고가용성을 유지한 채로 코드를 실행하고 확장하는 데 필요한 모든 것을 Lambda가 알아서 처리해 줍니다. 코드가 다른 AWS 서비스에서 자동으로 시작되도록 설정하거나 어떤 웹 또는 모바일 앱에서도 코드를 직접 호출할 수 있습니다.
+ [AWS CodeBuild](https://aws.amazon.com/codebuild/) – AWS CodeBuild는 소스 코드를 컴파일하고 테스트를 실행하며 배포 준비가 완료된 소프트웨어 패키지를 생성하는 종합 관리형 [지속 통합](https://aws.amazon.com/devops/continuous-integration/) 서비스입니다. CodeBuild를 사용하면 자체 빌드 서버를 프로비저닝, 관리 및 조정할 필요가 없습니다. CodeBuild는 지속적으로 규모가 조정되며 여러 빌드를 동시에 처리하기 때문에 빌드가 대기열에서 대기하지 않고 바로 처리됩니다. 사전 패키징된 빌드 환경을 사용하면 신속하게 시작할 수 있으며 혹은 자체 빌드 도구를 사용하는 사용자 지정 빌드 환경을 만들 수 있습니다.
+ [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) – Secrets Manager는 애플리케이션, 서비스, IT 리소스에 액세스하는 데 필요한 보안 암호를 지키도록 도와줍니다. 서비스를 사용하면 수명 주기 동안 데이터베이스 보안 인증 정보, API 키 및 기타 보안 암호를 교체, 관리 및 검색할 수 있습니다. 사용자와 애플리케이션은 민감한 정보를 일반 텍스트로 하드코딩할 필요 없이 Secrets Manager API를 호출하여 보안 정보를 검색합니다. Secrets Manager는 Amazon Relational Database Service(RDS), Amazon Redshift 및 Amazon DocumentDB에 대한 통합 기능이 내장되어 있는 암호 로테이션을 제공합니다. API 키 및 OAuth 토큰을 비롯한 다른 유형의 암호를 지원하도록 서비스를 확장할 수 있습니다. 또한 Secrets Manager를 사용하면 세분화된 권한을 사용하여 비밀에 대한 액세스를 제어하고, AWS 클라우드, 타사 서비스 및 온프레미스 환경의 리소스에 대한 비밀 로테이션을 중앙에서 감사할 수 있습니다.
+ [Amazon CloudWatch](https://aws.amazon.com/cloudwatch/) – Amazon CloudWatch는 DevOps 엔지니어, 개발자, 사이트 신뢰성 엔지니어(SRE) 및 IT 관리자를 위해 구축된 모니터링 및 관찰 서비스입니다. CloudWatch는 애플리케이션을 모니터링하고, 시스템 전반의 성능 변화에 대응하고, 리소스 활용도를 최적화하고, 운영 상태에 대한 통합 보기를 얻을 수 있는 데이터와 실행 가능한 인사이트를 제공합니다. CloudWatch는 로그, 지표 및 이벤트의 형태로 모니터링 및 운영 데이터를 수집하여 AWS 및 온프레미스 서버에서 실행되는 AWS 리소스, 애플리케이션 및 서비스를 통합적으로 볼 수 있게 합니다. CloudWatch를 사용하면 환경에서 비정상적인 동작을 감지하고, 경보를 설정하고, 로그와 지표를 나란히 시각화하고, 자동화된 조치를 취하고, 문제를 해결하고, 애플리케이션을 원활하게 실행하기 위한 인사이트를 발견할 수 있습니다.
+ [Amazon S3](https://aws.amazon.com/s3/) - Amazon Simple Storage Service(S3)는 웹사이트, 모바일 애플리케이션, 백업 및 복원, 아카이브, 엔터프라이즈 애플리케이션, IoT 디바이스, 빅 데이터 분석 등 다양한 사용 사례에서 원하는 양의 데이터를 저장하고 보호할 수 있는 객체 스토리지 서비스입니다. Amazon S3는 특정 비즈니스, 조직 및 규정 준수 요구 사항을 충족하도록 데이터를 구성하고 세부적으로 조정된 액세스 제어를 구성하는 데 도움이 되는 사용하기 쉬운 관리 기능을 제공합니다.

## 에픽
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-epics"></a>

### CodePipeline에서 사용자 지정 작업 생성
<a name="create-a-custom-action-in-codepipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| AWS CLI 또는 AWS CloudFormation을 사용하여 사용자 지정 작업을 생성합니다. | 이 단계에는 특정 지역의 AWS 계정에 있는 파이프라인의 소스 단계에서 사용할 수 있는 사용자 지정 소스 작업을 생성하는 작업이 포함됩니다. 사용자 지정 소스 작업을 생성하려면 AWS CLI 또는 AWS CloudFormation(콘솔 아님)을 사용해야 합니다. 이 에픽과 다른 에픽에 설명된 명령 및 단계에 대한 자세한 내용은 이 패턴 끝에 있는 ‘관련 리소스’ 섹션을 참조하세요. AWS CLI에서는 사용자 지정 작업 유형 생성 명령을 사용합니다. --configuration-properties를 사용하면 CodePipeline을 사용하여 작업에 대한 CodePipeline을 폴링할 때 작업 워커가 처리하는 데 필요한 모든 파라미터를 제공합니다. 이 사용자 지정 소스 스테이지로 파이프라인을 생성할 때 동일한 값을 사용할 수 있도록 --provider 및 --action-version 옵션에 제공된 값을 기록합니다. AWS::CodePipeline::CustomActionType 리소스 유형을 사용하여 AWS CloudFormation에서 사용자 지정 소스 작업을 생성할 수도 있습니다. | 일반 AWS | 

### 인증 설정
<a name="set-up-authentication"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| SSH 키 페어를 생성합니다. | Secure Shell(SSH) 키 페어를 생성합니다. 지침은 GitHub 설명서를 참조하세요. | 시스템/DevOps 엔지니어 | 
| AWS Secrets Manager에서 보안 암호를 생성합니다. | SSH 키 페어에서 프라이빗 키의 콘텐츠를 복사하고 AWS Secrets Manager에서 암호를 생성합니다. 이 비밀번호는 Git 리포지토리에 액세스할 때 인증하는 데 사용됩니다. | 일반 AWS | 
| Git 리포지토리에 퍼블릭 키를 추가합니다. | 개인 키에 대한 인증을 위해 SSH 키 쌍의 공개 키를 Git 저장소 계정 설정에 추가합니다. | 시스템/DevOps 엔지니어 | 

### 파이프라인 및 웹후크 생성
<a name="create-a-pipeline-and-webhook"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 사용자 지정 소스 작업이 포함된 파이프라인을 생성합니다. | CodePipeline에서 파이프라인을 생성합니다. 소스 단계를 구성할 때 이전에 만든 사용자 지정 소스 작업을 선택합니다. AWS CodePipeline 콘솔 또는 AWS CLI에서 이 작업을 수행할 수 있습니다. CodePipeline은 사용자 지정 작업에 설정한 구성 속성을 입력하라는 메시지를 표시합니다. 이 정보는 작업 워커가 사용자 지정 작업에 대한 작업을 처리하는 데 필요합니다. 마법사의 지시에 따라 파이프라인의 다음 단계를 생성하세요. | 일반 AWS | 
| CodePipeline 웹후크를 생성합니다. | 사용자 지정 소스 작업으로 생성한 파이프라인에 대한 웹후크를 생성합니다. 웹후크를 생성하려면 AWS CLI 또는 AWS CloudFormation(콘솔 아님)을 사용해야 합니다. AWS CLI에서 put-webhook 명령을 실행하고 웹후크 옵션에 적절한 값을 제공합니다. 명령이 반환하는 웹후크 URL을 기록합니다. AWS CloudFormation을 사용하여 웹후크를 생성하는 경우 AWS::CodePipeline: :웹후크 리소스 유형을 사용하세요. 생성된 리소스에서 웹후크 URL을 출력하고 기록합니다. | 일반 AWS | 
| Lambda 함수 및 CodeBuild 프로젝트 생성 | 이 단계에서는 Lambda와 CodeBuild를 사용하여 사용자 지정 작업의 작업 요청에 대해 CodePipeline을 폴링하고, 작업을 실행하고, 상태 결과를 CodePipeline에 반환하는 작업 워커를 생성합니다. 파이프라인의 사용자 지정 소스 작업 단계가 ‘진행 중’으로 전환될 때 Amazon CloudWatch Events 규칙에 의해 시작되는 Lambda 함수를 생성합니다. Lambda 함수가 시작되면 작업 폴링을 통해 사용자 지정 작업 세부 정보를 가져와야 합니다. PollForJobs API를 사용하여 이 정보를 반환할 수 있습니다. 폴링된 작업 정보를 획득한 후 Lambda 함수는 승인을 반환한 다음 사용자 지정 작업에 대한 구성 속성에서 획득한 데이터로 정보를 처리해야 합니다. 작업자가 Git 리포지토리와 통신할 준비가 되면 CodeBuild 프로젝트를 시작할 수 있습니다. SSH 클라이언트를 사용하여 Git 작업을 처리하는 것이 편리하기 때문입니다. | 일반 AWS, 코드 개발자 | 

### CloudWatch에서 이벤트 생성
<a name="create-an-event-in-cloudwatch"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| CloudWatch Events 규칙을 생성합니다. | 파이프라인의 사용자 지정 작업 단계가 ‘진행 중’으로 전환될 때마다 Lambda 함수를 대상으로 시작하는 CloudWatch Events 규칙을 생성합니다. | 일반 AWS | 

## 관련 리소스
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-resources"></a>

**CodePipeline에서 사용자 지정 작업 생성**
+ [CodePipeline에서 사용자 지정 작업 생성 및 추가](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-create-custom-action.html)
+ [AWS::CodePipeline::CustomActionType 리소스](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html)

**인증 설정**
+ [AWS Secrets Manager를 사용한 암호 생성 및 관리](https://docs.aws.amazon.com/secretsmanager/latest/userguide/managing-secrets.html)

**파이프라인 및 웹후크 생성**
+ [CodePipeline에서 파이프라인 생성](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-create.html)
+ [put-webhook 명령 레퍼런스](https://docs.aws.amazon.com/cli/latest/reference/codepipeline/put-webhook.html)
+ [AWS::CodePipeline::Webhook 리소스](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html)
+ [PollforJobs API 참조](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html)
+ [CodePipeline에서 사용자 지정 작업 생성 및 추가](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-create-custom-action.html)
+ [AWS CodeBuild에서 빌드 프로젝트 생성](https://docs.aws.amazon.com/codebuild/latest/userguide/create-project.html)

**이벤트 생성**
+ [Amazon CloudWatch Events를 통해 파이프라인 상태의 변경 감지 및 대응](https://docs.aws.amazon.com/codepipeline/latest/userguide/detect-state-changes-cloudwatch-events.html)

**추가 참조**
+ [CodePipeline에서 파이프라인을 사용한 작업](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines.html)
+ [AWS Lambda 개발자 안내서](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)

# AWS CodePipeline을 사용하여 Terraform 구성을 검증하는 CI/CD 파이프라인 생성
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline"></a>

*Aromal Raj Jayarajan, Vijesh Vijayakumaran Nair, Amazon Web Services*

## 요약
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-summary"></a>

이 패턴은 AWS CodePipeline에서 배포한 지속적 통합 및 지속적 전달(CI/CD) 파이프라인을 사용하여 HashiCorp Terraform 구성을 테스트하는 방법을 보여줍니다.

Terraform은 코드를 사용하여 클라우드 인프라 및 리소스를 프로비저닝하고 관리하는 데 도움이 되는 명령줄 인터페이스 애플리케이션입니다. 이 패턴에서 제공하는 솔루션은 5가지 [CodePipeline 단계](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html#concepts-stages)를 실행하여 Terraform 구성의 무결성을 검증하는 데 도움이 되는 CI/CD 파이프라인을 생성합니다.

1. `"checkout"`은 테스트 중인 Terraform 구성을 AWS CodeCommit 리포지토리에서 가져옵니다.

1. `"validate"`는 [tfsec](https://github.com/aquasecurity/tfsec), [TFLint](https://github.com/terraform-linters/tflint), [checkov](https://www.checkov.io/)를 비롯한 코드형 인프라(IaC) 검증 도구를 실행합니다. 또한 스테이지는 `terraform validate` 및 `terraform fmt`와 같은 Terraform IAc 유효성 검사 명령어를 실행합니다.

1. `"plan"`은 Terraform 구성이 적용된 경우 인프라에 어떤 변경 사항이 적용되는지를 보여 줍니다.

1. `"apply"`는 생성된 계획을 사용하여 테스트 환경에 필요한 인프라를 프로비저닝합니다.

1. `"destroy"`는 `"apply"`단계에서 생성된 테스트 인프라를 제거합니다.

## 사전 조건 및 제한 사항
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-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)
+ 로컬 머신에 설치 및 구성된 [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
+ 로컬 머신에 설치 및 구성된 [Terraform](https://learn.hashicorp.com/collections/terraform/aws-get-started?utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS)

**제한 사항 **
+ 이 패턴의 접근 방식은 AWS CodePipeline을 하나의 AWS 계정과 AWS 리전에만 배포합니다. 다중 계정 및 다중 리전 배포에는 구성을 변경해야 합니다.
+ 이 패턴이 제공하는 AWS Identity 및 Access Management(IAM) 역할(**codePipeline\$1iam\$1role**)은 최소 권한 원칙을 따릅니다. 파이프라인이 생성해야 하는 특정 리소스를 기반으로 이 IAM 역할의 권한을 업데이트해야 합니다.** **

**제품 버전**
+ AWS CLI버전 2.9.15 이상
+ Terraform 버전 1.3.7 이상

## 아키텍처
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-architecture"></a>

**대상 기술 스택**
+ AWS CodePipeline
+ AWS CodeBuild
+ AWS CodeCommit
+ AWS IAM
+ Amazon Simple Storage Service(Amazon S3)
+ AWS Key Management Service (AWS KMS)
+ Terraform

**대상 아키텍처**

다음 다이어그램은 CodePipeline에서 Terraform 구성을 테스트하기 위한 예제 CI/CD 파이프라인 워크플로를 보여줍니다.

![\[AWS CI/CD 파이프라인을 사용하여 Terraform 구성을 테스트하는 아키텍처입니다.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/4df7b1f8-8eef-4d85-a971-a7f158be9691/images/90b931c8-e745-4b52-92de-a367fb0f1f51.png)


이 다이어그램은 다음 워크플로를 보여줍니다.

1. CodePipeline에서 AWS 사용자는 AWS CLI에서 `terraform apply` 명령을 실행하여 Terraform 계획에 제안된 작업을 시작합니다.

1. AWS CodePipeline은 CodeCommit, CodeBuild, AWS KMS 및 Amazon S3에 액세스하는 데 필요한 정책을 포함하는 IAM 서비스 역할을 맡습니다.

1. CodePipeline은 `"checkout"` 파이프라인 단계를 실행하여 테스트를 위해 AWS CodeCommit 리포지토리에서 Terraform 구성을 가져옵니다.

1. CodePipeline은 CodeBuild 프로젝트에서 IAC 유효성 검사 도구를 실행하고 Terraform IAC 유효성 검사 명령을 실행하여 Terraform 구성을 테스트하는 `"validate"` 단계를 실행합니다.

1. CodePipeline은 Terraform 구성을 기반으로 CodeBuild 프로젝트에서 계획을 생성하는 `"plan"` 단계를 실행합니다. AWS 사용자는 변경 사항을 테스트 환경에 적용하기 전에 이 계획을 검토할 수 있습니다.

1. Code Pipeline은 CodeBuild 프로젝트를 사용하여 테스트 환경에 필요한 인프라를 프로비저닝함으로써 계획을 구현하는 `"apply"` 단계를 실행합니다.

1. CodePipeline은 CodeBuild를 사용하여 `"apply"` 단계 중에 생성된 테스트 인프라를 제거하는 `"destroy"` 단계를 실행합니다.

1. Amazon S3 버킷은 파이프라인 아티팩트를 저장하며, 이 아티팩트는 AWS KMS [고객 관리형 키](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#customer-cmk)를 사용하여 암호화되고 복호화됩니다.

## 도구
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-tools"></a>

**도구**

*서비스*
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)은 소프트웨어 릴리스의 여러 단계를 신속하게 모델링하고 구성하고 소프트웨어 변경 내용을 지속적으로 릴리스하는 데 필요한 단계를 자동화합니다.
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)는 소스 코드를 컴파일하고 유닛 테스트를 실행하며 배포할 준비가 완료된 아티팩트를 생성하는 완전 관리형 빌드 서비스입니다.
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)은 나만의 소스 제어 시스템을 관리할 필요 없이 Git 리포지토리를 비공개로 저장하고 관리할 수 있는 버전 제어 서비스입니다.
+ [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)를 사용하면 암호화 키를 생성하고 제어하여 데이터를 보호할 수 있습니다.
+ [Amazon Simple Storage Service(S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)는 원하는 양의 데이터를 저장, 보호 및 검색하는 데 도움이 되는 클라우드 기반 객체 스토리지 서비스입니다.

*기타 서비스*
+ [HashiCorp Terraform](https://www.terraform.io/docs)은 코드를 사용하여 클라우드 인프라 및 리소스를 프로비저닝하고 관리하는 데 도움이 되는 명령줄 인터페이스 애플리케이션입니다.

**코드**

이 패턴의 코드는 [aws-codepipeline-terraform-cicdsamples](https://github.com/aws-samples/aws-codepipeline-terraform-cicd-samples) 리포지토리에서 사용할 수 있습니다. 리포지토리에는 이 패턴에 설명된 대상 아키텍처를 생성하는 데 필요한 Terraform 구성이 포함되어 있습니다.

## 에픽
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-epics"></a>

### 솔루션 구성 요소 제공
<a name="provision-the-solution-components"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| GitHub 리포지토리를 복제합니다. | 터미널 창에 다음 명령을 실행하여 GitHub [aws-codepipeline-terraform-cicdsamples](https://github.com/aws-samples/aws-codepipeline-terraform-cicd-samples) 리포지토리를 복제합니다.<pre>git clone https://github.com/aws-samples/aws-codepipeline-terraform-cicd-samples.git</pre>자세한 내용은 GitHub 설명서의 [리포지토리 복제](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)를 참조하세요. | DevOps 엔지니어 | 
| Terraform 변수 정의 파일을 생성합니다. | 사용 사례 요구 사항에 따라 `terraform.tfvars` 파일을 생성합니다. 복제된 리포지토리에 있는 `examples/terraform.tfvars` 파일의 변수를 업데이트할 수 있습니다.자세한 내용은 Terraform 설명서의 [루트 모듈 변수에 값 할당](https://developer.hashicorp.com/terraform/language/values/variables#assigning-values-to-root-module-variables)을 참조하세요.리포지토리의 파일에는 필수 변수에 대한 자세한 정보가 포함되어 있습니다. | DevOps 엔지니어 | 
| AWS를 Terraform 공급자로 구성합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)자세한 내용은 Terraform 설명서의 [AWS 공급자](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)를 참조하세요. | DevOps 엔지니어 | 
| Amazon S3 복제 버킷을 생성하기 위한 Terraform 공급자 구성을 업데이트합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)S3 복제를 활성화하면 Amazon S3 버킷 전체에 걸쳐 객체를 비동기식으로 자동 복사할 수 있습니다. | DevOps 엔지니어 | 
| Terraform 구성을 초기화합니다. | Terraform 구성 파일이 포함된 작업 디렉토리를 초기화하려면 복제된 리포지토리의 루트 폴더에서 다음 명령을 실행하세요.<pre>terraform init</pre> | DevOps 엔지니어 | 
| Terraform 플랜을 생성합니다. | Terraform 계획을 생성하려면 복제된 리포지토리의 루트 폴더에서 다음 명령을 실행하세요.<pre>terraform plan --var-file=terraform.tfvars -out=tfplan</pre>Terraform은 구성 파일을 평가하여 선언된 리소스의 목표 상태를 결정합니다. 그런 다음 목표 상태를 현재 상태와 비교하고 계획을 구성합니다. | DevOps 엔지니어 | 
| Terraform 계획을 검증합니다. | Terraform 계획을 검토하고 대상 AWS 계정에 필요한 아키텍처가 구성되어 있는지 확인합니다. | DevOps 엔지니어 | 
| 솔루션을 배포합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)Terraform은 구성 파일에 선언된 목표 상태를 달성하기 위해 인프라를 생성, 업데이트 또는 파괴합니다. | DevOps 엔지니어 | 

### 파이프라인을 실행하여 Terraform 구성 검증
<a name="validate-terraform-configurations-by-running-the-pipeline"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 소스 코드 리포지토리를 설정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html) | DevOps 엔지니어 | 
| 파이프라인 단계를 검증합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)자세한 내용은 *AWS CodePipeline 사용 설명서*의 [파이프라인 세부 정보 및 기록 보기(콘솔)](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-view-console.html)를 참조하세요.소스 리포지토리의 메인 브랜치에 변경 사항이 커밋되면 테스트 파이프라인이 자동으로 활성화됩니다. | DevOps 엔지니어 | 
| 보고서 출력을 검증합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)`<project_name>-validate` CodeBuild 프로젝트는 `"validate"` 단계 중에 코드에 대한 취약성 보고서를 생성합니다. | DevOps 엔지니어 | 

### 리소스 정리
<a name="clean-up-your-resources"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 파이프라인 및 관련 리소스를 정리합니다. | AWS 계정에서 테스트 리소스를 삭제하려면 복제된 리포지토리의 루트 폴더에서 다음 명령을 실행하세요.<pre>terraform destroy --var-file=terraform.tfvars</pre> | DevOps 엔지니어 | 

## 문제 해결
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| `"apply"` 단계 중에 **액세스 거부** 오류가 발생합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html) | 

## 관련 리소스
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-resources"></a>
+ [모듈 블록](https://developer.hashicorp.com/terraform/language/modules/syntax)(Terraform 설명서)
+ [CI/CD를 사용하여 Terraform으로 AWS 보안 서비스를 배포하고 구성하는 방법](https://aws.amazon.com/blogs/security/how-use-ci-cd-deploy-configure-aws-security-services-terraform/)(AWS Blog 게시물)
+ [서비스 연결 역할 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)(IAM 설명서)
+ [create-pipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/create-pipeline.html)(AWS CLI 설명서)
+ [Amazon S3 for CodePipeline에 저장된 아티팩트에 대한 서버 측 암호화 구성](https://docs.aws.amazon.com/codepipeline/latest/userguide/S3-artifact-encryption.html)(AWS CodePipeline 설명서)
+ [AWS CodeBuild 할당량](https://docs.aws.amazon.com/codebuild/latest/userguide/limits.html)(AWS CodeBuild 설명서)
+ [AWS CodePipeline의 데이터 보호](https://docs.aws.amazon.com/codepipeline/latest/userguide/data-protection.html)(AWS CodePipeline 설명서)

## 추가 정보
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-additional"></a>

**Terraform 모듈 사용자 지정**

다음 사항은 이 패턴에 사용되는 사용자 지정 Terraform 모듈 목록입니다.
+ `codebuild_terraform`은 파이프라인의 각 단계를 구성하는 CodeBuild 프로젝트를 만듭니다.
+ `codecommit_infrastructure_source_repo`는 소스 CodeCommit 리포지토리를 캡처하고 만듭니다.
+ `codepipeline_iam_role`은 파이프라인에 필요한 IAM 역할을 생성합니다.
+ `codepipeline_kms`는 Amazon S3 객체 암호화 및 복호화에 필요한 AWS KMS 키를 생성합니다.
+ `codepipeline_terraform`은 소스 CodeCommit 리포지토리에 대한 테스트 파이프라인을 생성합다.
+ `s3_artifacts_bucket`은 Amazon S3 버킷을 생성하여 파이프라인 아티팩트를 관리합니다.

**빌드 사양 파일**

다음 사항은 이 패턴이 각 파이프라인 단계를 실행하는 데 사용하는 빌드 사양(buildspec) 파일 목록입니다.
+ `buildspec_validate.yml`은 `"validate"` 단계를 실행합니다.
+ `buildspec_plan.yml`은 `"plan"` 단계를 실행합니다.
+ `buildspec_apply.yml`은 `"apply"` 단계를 실행합니다.
+ `buildspec_destroy.yml`은 `"destroy"` 단계를 실행합니다.

*빌드 사양 파일 변수*

각 buildspec 파일은 다음 변수를 사용하여 다양한 빌드별 설정을 활성화합니다.


| 
| 
| 변수 | 기본값  | 설명 | 
| --- |--- |--- |
| `CODE_SRC_DIR` | "." | 소스 CodeCommit 디렉터리 정의 | 
| `TF_VERSION` | "1.3.7" | 빌드 환경을 위한 Terraform 버전 정의 | 

`buildspec_validate.yml` 파일은 또한 다음과 같은 변수를 지원하여 다양한 빌드별 설정을 활성화합니다.


| 
| 
| 변수 | 기본값  | 설명 | 
| --- |--- |--- |
| `SCRIPT_DIR` | "./templates/scripts" | 스크립트 디렉터리 정의 | 
| `ENVIRONMENT` | "dev" | 환경 이름 정의 | 
| `SKIPVALIDATIONFAILURE` | "Y" | 실패 시 검증 생략 | 
| `ENABLE_TFVALIDATE` | "Y" | Terraform 검증 활성화  | 
| `ENABLE_TFFORMAT` | "Y" | Terraform 형식 활성화 | 
| `ENABLE_TFCHECKOV` | "Y" | checkov 스캔 활성화 | 
| `ENABLE_TFSEC` | "Y" | tfsec 스캔 활성화 | 
| `TFSEC_VERSION` | “v1.28.1" | tfsec 버전 정의 | 

# 패턴 더 보기
<a name="devops-more-patterns-pattern-list"></a>

**Topics**
+ [AWS PrivateLink 및 Network Load Balancer를 사용하여 Amazon EKS에서 컨테이너 애플리케이션에 비공개로 액세스](access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer.md)
+ [한의 AWS CodeCommit 리포지토리를 다른 계정의 AWS 계정 Amazon SageMaker AI Studio Classic과 연결](associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.md)
+ [의 Landing Zone Accelerator를 사용하여 계정 생성 자동화 AWS](automate-account-creation-lza.md)
+ [AWS Systems Manager를 사용하여 Windows 레지스트리 항목의 추가 또는 업데이트 자동화](automate-adding-or-updating-windows-registry-entries-using-aws-systems-manager.md)
+ [AWS Batch를 사용하여 Amazon RDS for PostgreSQL DB 인스턴스 백업 자동화](automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch.md)
+ [AWS SAM을 사용하여 중첩된 애플리케이션 자동 배포](automate-deployment-of-nested-applications-using-aws-sam.md)
+ [CI/CD 파이프라인을 사용하여 Amazon EKS에서 노드 종료 핸들러 배포 자동화](automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline.md)
+ [Amazon MQ에서 RabbitMQ 구성의 자동화](automate-rabbitmq-configuration-in-amazon-mq.md)
+ [에서 Amazon RDS 인스턴스 복제 자동화 AWS 계정](automate-the-replication-of-amazon-rds-instances-across-aws-accounts.md)
+ [CI/CD 파이프라인을 사용하여 Amazon EKS에 Java 애플리케이션 자동 구축 및 배포](automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.md)
+ [Python 애플리케이션을 사용하여 Amazon DynamoDB용 PynamoDB DynamoDB 모델 및 CRUD 함수 자동 생성](automatically-generate-a-pynamodb-model-and-crud-functions-for-amazon-dynamodb-by-using-a-python-application.md)
+ [CodePipeline, IAM Access Analyzer 및 AWS CloudFormation 매크로를 사용하여 IAM 정책 및 역할을 자동으로 검증하고 배포](automatically-validate-and-deploy-iam-policies-and-roles-in-an-aws-account-by-using-codepipeline-iam-access-analyzer-and-aws-cloudformation-macros.md)
+ [의 Stromasys Charon-SSP 에뮬레이터에서 Sun SPARC 서버 백업 AWS 클라우드](back-up-sun-sparc-servers-in-the-stromasys-charon-ssp-emulator-on-the-aws-cloud.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 EC2 Auto Scaling 및 Systems Manager를 사용하여 Micro Focus Enterprise Server PAC 구축하기](build-a-micro-focus-enterprise-server-pac-with-amazon-ec2-auto-scaling-and-systems-manager.md)
+ [EC2 Image Builder와 Terraform을 사용하여 강화된 컨테이너 이미지용 파이프라인 구축](build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform.md)
+ [Amazon SageMaker AI 및 Azure DevOps를 사용하여 MLOps 워크플로 구축](build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops.md)
+ [AWS Managed Microsoft AD 및 온프레미스 Microsoft Active Directory를 사용하여 DNS 확인 중앙 집중화](centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.md)
+ [상태 파일 손실 후 AWS Account Factory for Terraform(AFT) 리소스를 안전하게 정리](clean-up-aft-resources-safely-after-state-file-loss.md)
+ [NLog를 사용하여 Amazon CloudWatch Logs에서.NET 애플리케이션에 대한 로깅 구성](configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog.md)
+ [AWS 계정 및 간에 Amazon ECR 컨테이너 이미지 복사 AWS 리전](copy-ecr-container-images-across-accounts-regions.md)
+ [SageMaker용 사용자 지정 Docker 컨테이너 이미지를 생성하고 이를 AWS Step Functions의 모델 교육에 사용합니다.](create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions.md)
+ [AWS CodePipeline을 지원하지 않는 AWS 리전에 파이프라인 생성](create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline.md)
+ [Amazon CloudWatch 이상 탐지를 사용하여 사용자 지정 지표에 대한 경보를 생성](create-alarms-for-custom-metrics-using-amazon-cloudwatch-anomaly-detection.md)
+ [AWS CDK 측면 및 이스케이프 해치를 사용하여 기본 역할 이름 사용자 지정](customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches.md)
+ [여러 코드 결과물에서 보안 문제를 동시에 감지하는 파이프라인 배포](deploy-a-pipeline-that-simultaneously-detects-security-issues-in-multiple-code-deliverables.md)
+ [AWS 클라우드에서 인프라를 코드로 사용하여 서버리스 데이터 레이크 배포와 관리](deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code.md)
+ [Docker 컨테이너로 AWS IoT Greengrass V2 실행 중인에 컨테이너화된 애플리케이션 배포](deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.md)
+ [Amazon EKS와 Amazon S3의 차트 Helm 리포지토리를 사용하여 Kubernetes 리소스 및 패키지 배포](deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3.md)
+ [TypeScript와 함께 AWS CDK를 사용하여 다중 스택 애플리케이션 배포하기](deploy-multiple-stack-applications-using-aws-cdk-with-typescript.md)
+ [Kiro 및 기타 코딩 어시스턴트와 함께 MCP 서버를 사용하여 실시간 코딩 보안 검증 배포](deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.md)
+ [Terraform을 사용하여 Amazon EC2 및 Amazon FSx에 SQL Server 장애 조치 클러스터 인스턴스 배포](deploy-sql-server-failover-cluster-instances-on-amazon-ec2-and-amazon-fsx.md)
+ [Terraform을 사용하여 AWS WAF 솔루션에 대한 보안 자동화 배포](deploy-the-security-automations-for-aws-waf-solution-by-using-terraform.md)
+ [RAG 및 ReAct 프롬프트를 사용하여 고급 생성형 AI 채팅 기반 어시스턴트 개발](develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.md)
+ [AWS CloudFormation 템플릿을 사용하여 조건부로 Amazon GuardDuty 활성화](enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates.md)
+ [Amazon EKS Pod Identity 및 KEDA를 사용하여 Amazon EKS에서 이벤트 기반 Auto Scaling 설정](event-driven-auto-scaling-with-eks-pod-identity-and-keda.md)
+ [Amazon Personalize를 사용하여 개인화되고 순위가 다시 매겨진 추천 생성](generate-personalized-and-re-ranked-recommendations-using-amazon-personalize.md)
+ [AWS KMS 키의 키 상태가 변경될 때 Amazon SNS 알림 받기](get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes.md)
+ [Account Factory for Terraform을 사용하여 여러 계정에 대한 권한 세트 관리](govern-permission-sets-aft.md)
+ [Amazon ECR 리포지토리로 마이그레이션할 때 중복 컨테이너 이미지 자동 식별](identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.md)
+ [Amazon API Gateway 버전 관리 구현](implement-path-based-api-versioning-by-using-custom-domains.md)
+ [AWS CDK를 통해 여러 AWS 리전, 계정, OU에서 Amazon DevOps Guru를 활성화하여 운영 성능을 개선하세요.](improve-operational-performance-by-enabling-amazon-devops-guru-across-multiple-aws-regions-accounts-and-ous-with-the-aws-cdk.md)
+ [Kubernetes DaemonSet을 사용하여 Amazon EKS 워커 노드에 SSM 에이전트 설치](install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset.md)
+ [Stonebranch 유니버설 컨트롤러를 AWS Mainframe Modernization과 통합](integrate-stonebranch-universal-controller-with-aws-mainframe-modernization.md)
+ [메인프레임 현대화: Rocket Software Enterprise Suite를 AWS 사용한의 DevOps](mainframe-modernization-devops-on-aws-with-micro-focus.md)
+ [를 사용하여 AWS IAM Identity Center 권한 세트를 코드로 관리 AWS CodePipeline](manage-aws-iam-identity-center-permission-sets-as-code-by-using-aws-codepipeline.md)
+ [Terraform을 사용하여 AWS 권한 세트 동적 관리](manage-aws-permission-sets-dynamically-by-using-terraform.md)
+ [AWS CDK로 Amazon ECS Anywhere를 설정하여 온프레미스 컨테이너 애플리케이션을 관리](manage-on-premises-container-applications-by-setting-up-amazon-ecs-anywhere-with-the-aws-cdk.md)
+ [AWS CodePipeline 및 Amazon Bedrock을 사용하여 AWS Organizations 정책을 코드로 관리](manage-organizations-policies-as-code.md)
+ [DNS 레코드를 Amazon Route 53 프라이빗 호스팅 영역으로 대량 마이그레이션합니다.](migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone.md)
+ [appcmd.exe를 사용하여 IIS 호스팅 애플리케이션을 Amazon EC2로 마이그레이션](migrate-iis-hosted-applications-to-amazon-ec2-by-using-appcmd.md)
+ [여러에서 공유 Amazon Machine Image 사용 모니터링 AWS 계정](monitor-use-of-a-shared-amazon-machine-image-across-multiple-aws-accounts.md)
+ [를 사용하여 검증, 변환 및 파티셔닝으로 ETL 파이프라인 오케스트레이션 AWS Step Functions](orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.md)
+ [IaC 원칙을 사용하여 Amazon Aurora 글로벌 데이터베이스의 블루/그린 배포 자동화](p-automate-blue-green-deployments-aurora-global-databases-iac.md)
+ [비 워크로드 서브넷을 위한 다중 계정 VPC 설계에서 라우팅 가능한 IP 공간 보존](preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets.md)
+ [코드 리포지토리를 AWS Service Catalog 사용하여에서 Terraform 제품 프로비저닝](provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.md)
+ [AWS Step Functions에서 AWS Systems Manager Automation 작업을 동기적으로 실행](run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions.md)
+ [AWS CDK 및 GitLab을 사용하여 Amazon ECS Anywhere에서 하이브리드 워크로드를 위한 CI/CD 파이프라인 설정하기](set-up-a-ci-cd-pipeline-for-hybrid-workloads-on-amazon-ecs-anywhere-by-using-aws-cdk-and-gitlab.md)
+ [Terraform을 사용하여 데이터베이스 마이그레이션을 위한 CI/CD 파이프라인 설정](set-up-ci-cd-pipeline-for-db-migration-with-terraform.md)
+ [Amazon FSx를 사용하여 SQL Server Always On FCI용 다중 AZ 인프라 설정](set-up-multi-az-infrastructure-for-a-sql-server-always-on-fci-by-using-amazon-fsx.md)
+ [AWS CloudFormation을 사용하여 Amazon EC2에 UiPath RPA 봇을 자동으로 설정](set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.md)
+ [Application Load Balancer를 사용하여 Amazon ECS에서 상호 TLS로 애플리케이션 인증 간소화](simplify-application-authentication-with-mutual-tls-in-amazon-ecs.md)
+ [C\$1 및 AWS CDK를 사용한 사일로 모델을 위한 SaaS 아키텍처의 테넌트 온보딩](tenant-onboarding-in-saas-architecture-for-the-silo-model-using-c-and-aws-cdk.md)
+ [Terraform을 사용하여 조직의 Amazon GuardDuty를 자동으로 활성화합니다](use-terraform-to-automatically-enable-amazon-guardduty-for-an-organization.md)
+ [Amazon Bedrock 에이전트를 사용하여 텍스트 기반 프롬프트를 통해 Amazon EKS에서 액세스 항목 제어 생성 자동화](using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.md)
+ [Account Factory에 대한 테라폼(AFT) 코드를 로컬에서 검증](validate-account-factory-for-terraform-aft-code-locally.md)
+ [Flask와 AWS Elastic Beanstalk를 사용하여 AI/ML 모델 결과 시각화](visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.md)