1. 개요

CdeDeploy를 사용해본다.


2. 참고문서


3. 역할 (Role) 생성

  • CodeDeploy 생성 시 관련 role이 필요하므로 미리 만들어 놓는 것이다.
  • IAM
  • [AWS 서비스/EC2, Lambda and others]
  • AWSCodeDeployRole 정책 연결
  • 신뢰관계 탭에 다음 내용 입력
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "codedeploy.amazonaws.com"
                ]
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

4. 애플리케이션

4.1. 애플리케이션 생성

  • 애플리케이션 이름 : myApp
  • 컴퓨팅 플랫폼 : EC2
  • 배포 그룹 이름 : myAppDeploymentGroup

4.2. 배포 유형

  • 현재 위치 배포

4.3. 환경 구성

  • EC2 중 태그 기반으로 대상을 정한다.
  • 설치하는 인스턴스가 보인다.

4.4. 배포 구성

4.4.1. EC2

  • CodeDeployDefault.AllAtOnce : 한 번에 가급적 많은 수의 인스턴스에 애플리케이션 개정을 배포하기 위한 시도
  • CodeDeployDefault.HalfAtATime : 최대 절반의 인스턴스(분수는 반내림함)에 한번에 배포
  • CodeDeployDefault.OneAtATime : 한 번에 한 인스턴스에만 애플리케이션 개정을 배포

위 선택지 중 하나 선택한다.

4.4.2. Lambda

  • CodeDeployDefault.LambdaCanary10Percent5Minutes : 첫 번째 증분에 트래픽의 10%가 전환. 나머지 90%는 5분 이후 배포.
  • CodeDeployDefault.LambdaCanary10Percent10Minutes : 첫 번째 증분에 트래픽의 10%가 전환. 나머지 90%는 10분 이후 배포.
  • CodeDeployDefault.LambdaCanary10Percent15Minutes : 첫 번째 증분에 트래픽의 10%가 전환. 나머지 90%는 15분 이후 배포.
  • CodeDeployDefault.LambdaCanary10Percent30Minutes : 첫 번째 증분에 트래픽의 10%가 전환. 나머지 90%는 30분 이후 배포.
  • CodeDeployDefault.LambdaLinear10PercentEvery1Minute : 모든 트래픽이 전환될 때까지 트래픽의 10%가 매분마다 전환.
  • CodeDeployDefault.LambdaLinear10PercentEvery2Minutes : 모든 트래픽이 이동될 때까지 트래픽의 10%가 2분마다 이동.
  • CodeDeployDefault.LambdaLinear10PercentEvery3Minutes : 모든 트래픽이 이동될 때까지 트래픽의 10%가 3분마다 이동.
  • CodeDeployDefault.LambdaLinear10PercentEvery10Minutes : 모든 트래픽이 전환될 때까지 트래픽의 10%가 10분마다 전환.
  • CodeDeployDefault.LambdaAllAtOnce : 업데이트된 Lambda 함수로 모든 트래픽을 한번에 전환.

5. 배포

5.1. 배포 생성


6. EC2 인스턴스 프로파일

6.1. 정책 생성

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::(버킷이름)/*"
            ]
        }
    ]
}

6.2. EC2 인스턴스 프로파일에 위에서 만든 정책 연결

The overall deployment failed because too many individual instances failed deployment, too few healthy instances are available for deployment, or some instances in your deployment group are experiencing problems. (Error code: HEALTH_CONSTRAINTS)

7. AppSpec

  • appspec.yml 파일이 필요하다. (검색해볼 것)
  • 만약 CodeBuild를 타고 넘어온 것이라면, buildspec.yml에 appspec.yml에 대한 언급이 필요하다.
  • 주의사항 : zip 파일을 풀었을 때 appspec.yml 파일이 나와야 한다. appspec.yml 파일이 jar나 war 안에 있어서는 안된다는 말이다. 따라서 buildspec.yml 파일이 다음과 같이 되어 있는지 확인해보자. 만약 appspec.yml 파일 위치가 맞지 않으면 계속 HEALTH_CONSTRAINTS 오류가 난다.
artifacts:
  files:
    - target/testApp-0.0.1-SNAPSHOT.jar
    - appspec.yml

8. EC2에 CodeDeploy용 에이전트 설치

참고링크: https://docs.aws.amazon.com/ko_kr/codedeploy/latest/userguide/codedeploy-agent-operations-install-linux.html

[ec2-user@ip-10-0-0-129 ~]$ sudo yum update
Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main                                                                                                                                                                               | 2.1 kB  00:00:00
amzn-updates                                                                                                                                                                            | 2.5 kB  00:00:00
Resolving Dependencies
--> Running transaction check
---> Package kernel.x86_64 0:4.9.76-3.78.amzn1 will be installed
---> Package kernel-headers.x86_64 0:4.9.75-25.55.amzn1 will be updated
---> Package kernel-headers.x86_64 0:4.9.76-3.78.amzn1 will be an update
---> Package kernel-tools.x86_64 0:4.9.75-25.55.amzn1 will be updated
---> Package kernel-tools.x86_64 0:4.9.76-3.78.amzn1 will be an update
--> Finished Dependency Resolution

Dependencies Resolved

===============================================================================================================================================================================================================
 Package                                            Arch                                       Version                                                  Repository                                        Size
===============================================================================================================================================================================================================
Installing:
 kernel                                             x86_64                                     4.9.76-3.78.amzn1                                        amzn-updates                                      18 M
Updating:
 kernel-headers                                     x86_64                                     4.9.76-3.78.amzn1                                        amzn-updates                                     1.1 M
 kernel-tools                                       x86_64                                     4.9.76-3.78.amzn1                                        amzn-updates                                     108 k

Transaction Summary
===============================================================================================================================================================================================================
Install  1 Package
Upgrade  2 Packages

Total download size: 19 M
Is this ok [y/d/N]: y
Downloading packages:
(1/3): kernel-headers-4.9.76-3.78.amzn1.x86_64.rpm                                                                                                                                      | 1.1 MB  00:00:00
(2/3): kernel-tools-4.9.76-3.78.amzn1.x86_64.rpm                                                                                                                                        | 108 kB  00:00:00
(3/3): kernel-4.9.76-3.78.amzn1.x86_64.rpm                                                                                                                                              |  18 MB  00:00:00
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                           50 MB/s |  19 MB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : kernel-4.9.76-3.78.amzn1.x86_64                                                                                                                                                             1/5
  Updating   : kernel-headers-4.9.76-3.78.amzn1.x86_64                                                                                                                                                     2/5
  Updating   : kernel-tools-4.9.76-3.78.amzn1.x86_64                                                                                                                                                       3/5
  Cleanup    : kernel-headers-4.9.75-25.55.amzn1.x86_64                                                                                                                                                    4/5
  Cleanup    : kernel-tools-4.9.75-25.55.amzn1.x86_64                                                                                                                                                      5/5
  Verifying  : kernel-tools-4.9.76-3.78.amzn1.x86_64                                                                                                                                                       1/5
  Verifying  : kernel-headers-4.9.76-3.78.amzn1.x86_64                                                                                                                                                     2/5
  Verifying  : kernel-4.9.76-3.78.amzn1.x86_64                                                                                                                                                             3/5
  Verifying  : kernel-headers-4.9.75-25.55.amzn1.x86_64                                                                                                                                                    4/5
  Verifying  : kernel-tools-4.9.75-25.55.amzn1.x86_64                                                                                                                                                      5/5

Installed:
  kernel.x86_64 0:4.9.76-3.78.amzn1

Updated:
  kernel-headers.x86_64 0:4.9.76-3.78.amzn1                                                               kernel-tools.x86_64 0:4.9.76-3.78.amzn1

Complete!
[ec2-user@ip-10-0-0-129 ~]$ sudo yum install ruby
Loaded plugins: priorities, update-motd, upgrade-helper
Package 1:ruby-2.0-0.3.amzn1.noarch already installed and latest version
Nothing to do
[ec2-user@ip-10-0-0-129 ~]$ sudo yum install wget
Loaded plugins: priorities, update-motd, upgrade-helper
Package wget-1.18-3.28.amzn1.x86_64 already installed and latest version
Nothing to do
[ec2-user@ip-10-0-0-129 ~]$ cd /home/ec2-user
[ec2-user@ip-10-0-0-129 ~]$ wget https://aws-codedeploy-ap-northeast-2.s3.amazonaws.com/latest/install
--2018-01-18 04:00:40--  https://aws-codedeploy-ap-northeast-2.s3.amazonaws.com/latest/install
Resolving aws-codedeploy-ap-northeast-2.s3.amazonaws.com (aws-codedeploy-ap-northeast-2.s3.amazonaws.com)... 52.92.8.18
Connecting to aws-codedeploy-ap-northeast-2.s3.amazonaws.com (aws-codedeploy-ap-northeast-2.s3.amazonaws.com)|52.92.8.18|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 13510 (13K) []
Saving to: ‘install’

install                                             100%[==================================================================================================================>]  13.19K  --.-KB/s    in 0.001s

2018-01-18 04:00:40 (21.6 MB/s) - ‘install’ saved [13510/13510]

[ec2-user@ip-10-0-0-129 ~]$ chmod +x ./install
[ec2-user@ip-10-0-0-129 ~]$ sudo ./install auto
I, [2018-01-18T04:00:52.792474 #22930]  INFO -- : Starting Ruby version check.
I, [2018-01-18T04:00:52.792683 #22930]  INFO -- : Starting update check.
I, [2018-01-18T04:00:52.792761 #22930]  INFO -- : Attempting to automatically detect supported package manager type for system...
I, [2018-01-18T04:00:52.800207 #22930]  INFO -- : Checking AWS_REGION environment variable for region information...
I, [2018-01-18T04:00:52.800292 #22930]  INFO -- : Checking EC2 metadata service for region information...
I, [2018-01-18T04:00:52.855990 #22930]  INFO -- : Downloading version file from bucket aws-codedeploy-ap-northeast-2 and key latest/VERSION...
I, [2018-01-18T04:00:52.902632 #22930]  INFO -- : Downloading version file from bucket aws-codedeploy-ap-northeast-2 and key latest/VERSION...
I, [2018-01-18T04:00:52.926740 #22930]  INFO -- : Downloading package from bucket aws-codedeploy-ap-northeast-2 and key releases/codedeploy-agent-1.0-1.1352.noarch.rpm...
I, [2018-01-18T04:00:53.016794 #22930]  INFO -- : Executing `/usr/bin/yum -y localinstall /tmp/codedeploy-agent-1.0-1.1352.noarch.tmp-20180118-22930-apifm3.rpm`...
Loaded plugins: priorities, update-motd, upgrade-helper
Examining /tmp/codedeploy-agent-1.0-1.1352.noarch.tmp-20180118-22930-apifm3.rpm: codedeploy-agent-1.0-1.1352.noarch
Marking /tmp/codedeploy-agent-1.0-1.1352.noarch.tmp-20180118-22930-apifm3.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package codedeploy-agent.noarch 0:1.0-1.1352 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===============================================================================================================================================================================================================
 Package                                   Arch                            Version                                Repository                                                                              Size
===============================================================================================================================================================================================================
Installing:
 codedeploy-agent                          noarch                          1.0-1.1352                             /codedeploy-agent-1.0-1.1352.noarch.tmp-20180118-22930-apifm3                           16 M

Transaction Summary
===============================================================================================================================================================================================================
Install  1 Package

Total size: 16 M
Installed size: 16 M
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction

pre hook : 1
Checking the ruby version.
Checking if there is already a process named codedeploy-agent running.
  Installing : codedeploy-agent-1.0-1.1352.noarch                                                                                                                                                          1/1

post hook : 1
Check if there is a codedeployagent config file.
Start codedeploy-agent in post hook if this is an install or update.
Installing codedeploy-agent auto-update cron in '/etc/cron.d/codedeploy-agent-update'...
Installing codedeploy-agent auto-update cron in '/etc/cron.d/codedeploy-agent-update'...Complete
  Verifying  : codedeploy-agent-1.0-1.1352.noarch                                                                                                                                                          1/1

Installed:
  codedeploy-agent.noarch 0:1.0-1.1352

Complete!
I, [2018-01-18T04:00:54.729244 #22930]  INFO -- : Update check complete.
I, [2018-01-18T04:00:54.729340 #22930]  INFO -- : Stopping updater.
[ec2-user@ip-10-0-0-129 ~]$ sudo service codedeploy-agent status
The AWS CodeDeploy agent is running as PID 22976

만약 에이전트가 설치되어 있지 않다면,

$ sudo service codedeploy-agent status
codedeploy-agent: unrecognized service

9. 문제해결

9.1. 애플리케이션 생성 시 Cannot assume role provided codedeploy 발생

연결하고자 하는 role에서 신뢰 관계를 확인하여 본다.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

위와 같이 되어 있다면 3-1. 에서 설명한 role과 같이 수정한다.

9.2. Error code: HEALTH_CONSTRAINTS

로그 파일 /var/log/aws/codedeploy-agent/codedeploy-agent.log 을 확인한다.

9.3. InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Missing credentials

  • 인스턴스 프로파일을 다시 한 번 확인한다.
  • 만약 중간에 인스턴스 프로파일을 뭔가 수정한 적이 있다면 깔끔하게 인스턴스 프로파일 떼고 -> 인스턴스 중지하고 -> 인스턴스 프로파일 붙이고 -> 인스턴스 기동한 후 다시 확인한다.

9.4. The CodeDeploy agent did not find an AppSpec file within the unpacked revision

2018-01-18 04:38:54 ERROR [codedeploy-agent(2657)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Error during perform: RuntimeError - The CodeDeploy agent did not find an AppSpec file within the unpacked revision directory at revision-relative path "appspec.yml". The revision was unpacked to directory "/opt/codedeploy-agent/deployment-root/3e5eb5be-74d3-43e6-b0d8-eb462ae858b9/d-Z6FV28NAP/deployment-archive", and the AppSpec file was expected but not found at path "/opt/codedeploy-agent/deployment-root/3e5eb5be-74d3-43e6-b0d8-eb462ae858b9/d-Z6FV28NAP/deployment-archive/appspec.yml". Consult the AWS CodeDeploy Appspec documentation for more information at http://docs.aws.amazon.com/codedeploy/latest/userguide/reference-appspec-file.html - /opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/hook_executor.rb:213:in `parse_app_spec'

 


10. 참고 (배포방안)

10.1. Rolling Update

한대씩 새로운 버전을 배포한다. 구성이 간단하다. 중요도가 떨어지는 운영 환경이나 개발 환경에서 사용한다. 배포 중에는 인스턴스 수가 줄어들게 된다. 

10.2. Blue/Green

새로운 버전을 배포 후 배포된 버전으로 전환한다. 코드 변경에 따른 사이트 이펙트가 적고 무중단이 필요한 경우 사용한다.

10.3. Canary

새로운 버전의 서버에 일부 트래픽을 분배한다. 오류를 판단하기 위한 기법이며 소스 변경 영향도가 높을 때 주로 사용한다.