

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

# CodePipeline을 사용하여 Terraform 및 CloudFormation 템플릿 배포
<a name="using-codepipeline"></a>

DPA에서는 용 빌딩 블록 AWS CodePipeline 을 사용하여 Terraform 및 CloudFormation IaC용 액셀러레이터를 생성합니다. 이 섹션에서는이 사용 사례에 대해 다음을 설명합니다.
+ 표준화된 파이프라인 구조
+ 재사용 가능한 단계 및 작업
+ 보안 스캔을 위한 통합 도구

DPA 리포지토리에는 [Terraform](https://github.com/aws-samples/aws-devops-pipeline-accelerator/tree/main/aws-codepipeline/terraform) 및 [CloudFormation](https://github.com/aws-samples/aws-devops-pipeline-accelerator/tree/main/aws-codepipeline/cloudformation)용 폴더가 포함되어 있습니다. 이러한 각 폴더에는 다음 두 개의 하위 폴더가 포함되어 있습니다.
+ **pipeline-modules** -이 폴더에는 표준화된 파이프라인 구조를 배포하기 위한 코드가 포함되어 있습니다.
+ **공유**됨 -이 폴더에는 DPA 단계 및 작업에 바로 ready-to-use 수 있는 buildspec 파일이 포함되어 있습니다.

## 사전 조건
<a name="prerequisites-codepipeline"></a>
+ 활성 AWS 계정
+ IaC 템플릿을 사용하여 리소스를 프로비저닝할 수 있는 권한
+  AWS CodeCommit 리포지토리 및 CodePipeline 구성 요소를 생성할 수 있는 권한

## 도구
<a name="tools-codepipeline"></a>
+ [cfn-lint](https://github.com/aws-cloudformation/cfn-lint)는 CloudFormation YAML 또는 JSON 템플릿을 [AWS CloudFormation 리소스 사양](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)과 비교하여 확인하는 린터입니다. 또한 리소스 속성의 유효한 값 확인 및 모범 사례 준수와 같은 다른 검사를 수행합니다.
+ [cfn\$1nag](https://github.com/stelligent/cfn_nag)는 패턴을 검색하여 CloudFormation 템플릿의 잠재적 보안 문제를 식별하는 오픈 소스 도구입니다.
+ [Checkov](https://www.checkov.io/1.Welcome/What%20is%20Checkov.html)는 IaC의 보안 및 규정 준수 구성 오류를 확인하는 정적 코드 분석 도구입니다.
+ [TFLint](https://github.com/terraform-linters/tflint)는 Terraform 코드에서 잠재적 오류와 모범 사례 준수를 확인하는 린터입니다.
+ [tfsec](https://github.com/aquasecurity/tfsec)은 Terraform 코드에 잠재적인 잘못된 구성이 있는지 확인하는 정적 코드 분석 도구입니다.

## 지침
<a name="instructions-codepipeline"></a>

### CodeCommit 리포지토리 생성
<a name="instructions-repo"></a>

1. 다음과 같이 두 개의 개별 CodeCommit 리포지토리를 생성합니다.
   + `common-repo` -이 리포지토리에는 공유 라이브러리, buildspec 파일 및 종속성이 포함되어 있습니다.
   + `app-repo` -이 리포지토리에는 인프라를 배포하기 위한 Terraform 또는 CloudFormation 템플릿이 포함되어 있습니다.

   지침은 [AWS CodeCommit 리포지토리 생성을 참조하세요](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html).

1. `common-repo` 리포지토리에서 라는 폴더를 생성합니다`shared`. GitHub DPA 리포지토리의 [Terraform](https://github.com/aws-samples/aws-devops-pipeline-accelerator/tree/main/aws-codepipeline/terraform/shared) 또는 [CloudFormation](https://github.com/aws-samples/aws-devops-pipeline-accelerator/tree/main/aws-codepipeline/cloudformation/shared) **공유 **폴더에서 새 폴더로 buildspec 파일을 복사합니다. 지침은 [AWS CodeCommit 리포지토리에 파일 생성 또는 추가를 참조하세요](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-file.html).

1. `app-repo` 리포지토리에서 라는 폴더를 생성합니다`entrypoint`. GitHub DPA 리포지토리의 [Terraform](https://github.com/aws-samples/aws-devops-pipeline-accelerator/blob/main/examples/aws_codepipeline/terraform/entrypoint/terraform-infrastructure.json) 또는 [CloudFormation](https://github.com/aws-samples/aws-devops-pipeline-accelerator/blob/main/examples/aws_codepipeline/cloudformation/entrypoint/config.json) **진입점** 폴더에서 새 폴더로 파일을 복사합니다. 이러한 파일에 대한 자세한 내용은 섹션을 참조하세요[진입점 JSON 파일 이해](#understanding-json-file).

1. [Terraform](https://github.com/aws-samples/aws-devops-pipeline-accelerator/tree/main/examples/aws_codepipeline/terraform) 또는 [CloudFormation](https://github.com/aws-samples/aws-devops-pipeline-accelerator/tree/main/examples/aws_codepipeline/cloudformation) **예제** 디렉터리를 검토한 다음 다음 예제에 따라 `app-repo` 폴더를 구성합니다. 이러한 디렉터리에는 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스 또는 Amazon Simple Storage Service(Amazon S3) 버킷을 배포하는 예제가 포함되어 있습니다.

1. 다음 두 섹션 중 하나를 계속 진행합니다.
   + [파이프라인 생성 및 단계 정의(Terraform)](#instructions-terraform-pipeline)
   + [파이프라인 생성 및 단계 정의(CloudFormation)](#instructions-cfn-pipeline)

### 파이프라인 생성 및 단계 정의(Terraform)
<a name="instructions-terraform-pipeline"></a>

1. GitHub에서 로컬 워크스테이션으로[ DevOps Pipeline Accelerator(DPA) 리포지토리](https://github.com/aws-samples/aws-devops-pipeline-accelerator)를 복제합니다.

1. 복제된 리포지토리에서 `aws-codepipeline/terraform/pipeline-modules` 폴더로 이동합니다.

1. **terraform.tfvars** 파일에서 Terraform 상태 및 AWS Identity and Access Management (IAM) 역할별 변수를 업데이트하고 검증합니다.

1. Docker 이미지를 생성합니다. 지침은 [ CodeBuild(GitHub)에서를 사용하기 위한 도커 이미지 생성을](https://github.com/aws-samples/aws-devops-pipeline-accelerator/blob/main/shared-docker/docker-images/README.md) 참조하세요.GitHub

1. **terraform.tfvars** 파일에 정의된 `builder_image` 변수를 업데이트합니다.

1. 다음 명령을 입력합니다. 이렇게 하면 Terraform을 통해 인프라가 초기화, 미리 보기 및 배포됩니다.

   ```
   terraform init
   terraform plan
   terraform apply
   ```

1.  AWS 계정에 로그인합니다. [CodePipeline 콘솔](https://console.aws.amazon.com/codesuite/codepipeline/home)에서 새 파이프라인이 생성되었는지 확인합니다.

   **참고**: 첫 번째 실행이 `failed` 상태인 경우 이전 단계를 반복합니다.

1. 새 CodePipeline 파이프라인이 생성되면에 대한 AWS CodeBuild 새 IAM 역할이 자동으로 생성됩니다. 자동으로 생성된이 역할의 이름은 로 끝납니다`-codebuild-role`. 인프라를 배포하는 데 필요한 권한으로이 역할을 업데이트합니다.

### 파이프라인 생성 및 단계 정의(CloudFormation)
<a name="instructions-cfn-pipeline"></a>

1. GitHub에서 로컬 워크스테이션으로[ DevOps Pipeline Accelerator(DPA) 리포지토리](https://github.com/aws-samples/aws-devops-pipeline-accelerator)를 복제합니다.

1. 복제된 리포지토리에서 `aws-codepipeline/cloudformation/pipeline-modules` 폴더로 이동합니다.

1. **pipeline-cft.yaml** CloudFormation 템플릿을 배포합니다. 다음은 스택에 전달해야 하는 필수 파라미터입니다.
   + `ArtifactsBucket` - 업데이트할 파이프라인 아티팩트가 포함된 리포지토리의 이름
   + `EcrDockerRepository` - `image` 태그가 있는 Amazon ECR 리포지토리의 URI(Uniform Resource Identifier)
   + `CodeCommitAppRepo` - 템플릿이 포함된 CodeCommit 리포지토리의 이름
   + `CodeCommitBaseRepo` - 공유 파일이 포함된 CodeCommit 리포지토리의 이름
   + `CodeCommitRepoBranch` - CodeCommit 리포지토리 브랜치의 이름
   + `SNSMailAddress` - 파이프라인 상태에 대한 Amazon Simple Notification Service(Amazon SNS) 알림을 받을 이메일 주소

   지침은 CloudFormation 설명서의 [스택 작업을 참조하세요](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html).

1. AWS 계정에 로그인합니다. [CodePipeline 콘솔](https://console.aws.amazon.com/codesuite/codepipeline/home)에서 새 파이프라인이 생성되었는지 확인합니다. 

1. 새 CodePipeline 파이프라인이 생성되면에 대한 AWS CodeBuild 새 IAM 역할이 자동으로 생성됩니다. 자동으로 생성된이 역할의 이름은 로 끝납니다`-codebuild-role`. 인프라를 배포하는 데 필요한 권한으로이 역할을 업데이트합니다.

## 진입점 JSON 파일 이해
<a name="understanding-json-file"></a>

### Terraform 진입점 파일
<a name="entry-point-terraform"></a>

기본 구성 파일입니다. 이 파일에서 스테이지를 사용자 지정하고 활성화 또는 비활성화할 수 있습니다. 스테이지를 비활성화해도 파이프라인에서 스테이지가 삭제되거나 제거되지 않습니다. 대신 런타임 중에 단계를 건너뜁니다.

```
{
    "build_stage_required" : "true",
    "test_stage_required" : "true",
    "predeploy_stage_required": "true",
    "deploy_stage_required": "true",
    "postdeploy_stage_required": "true",
    "destroy_stage_required": "true",
    "bucket":"tf-state-dpa",                # S3 bucket used for Terraform backend
    "key":"terraform_test.tfstate",         # S3 key to be used
    "region":"us-east-1",       
    "dynamodb_table":"tf-state-dpa"         # DynamoDB Table for Terraform backend
}
```

### CloudFormation 진입점 파일
<a name="entry-point-cfn"></a>

기본 구성 파일입니다. 이 파일에서는 스테이지를 사용자 지정하고 활성화 또는 비활성화합니다. 스테이지를 비활성화해도 파이프라인에서 스테이지가 삭제되거나 제거되지 않습니다. 대신 파이프라인은 런타임 중에 단계를 건너뜁니다.

```
{
    "init_stage_required" : "true",
    "test_stage_required" : "true",
    "createinfra_stage_required": "true",
    "envType" : "cloudformation",
    "stage_required" : "true",
    "cft_s3_bucket" : "pipeline-bucket",               #S3 bucket from the destination account to keep CFT templates
    "stack_name" : "aws-cft-poc",                      #CloudFormation stack name
    "account" : "************",                        #Destination AWS account to deploy stack
    "roleName" : "codestack-poc-cross-account-role",   #Cross-account IAM role name
    "region" : "us-east-1",
    "destroy_stack" : "false"                          #To destroy the provisioned stack, set this value to "true"
}
```