fullmoon's bright IT blog

[AWS study] Jenkins를 사용한 AWS CICD (극한의 오류수정인데 무한삽질과 허망한 이유) 본문

STUDY

[AWS study] Jenkins를 사용한 AWS CICD (극한의 오류수정인데 무한삽질과 허망한 이유)

휘영청 2021. 8. 31. 23:35
728x90

 

안녕하세요 휘영청입니다

 

오늘은

 

creating a functioning CI/CD pipeline

 

작동하는 파이프라인은 소스 코드를 컴파일하고 단위 테스트를 실행하는 완전 관리형 빌드 서비스를 생성 후

 CodeDeploy에서 프로덕션 환경에 자동으로 배포하는 데 사용할 수 있는 코드 artifacts를 생성해 볼겁니다

 

 

third-party-integration-codebuild-codedeploy-plugins

AWS CICD with Jenkins In this workshop, we will integrate AWS CodeBuild and AWS CodeDeploy with Jenkins and execute the CICD pipeline to build and deploy the application. We will also spin up an infrastructure with ALB and EC2’s on which the application

third-party-integration-codebuild-codedeploy-plugins.workshop.aws

하지말라고 했습니다 하지말라고...이거 보고해...요...

 


[Architect]

사용하는 서비스

 

  • Amazon S3 버킷
    • CodeDeploy에서 사용하는 GitHub 리포지토리 파일과 CodeBuild 아티팩트 애플리케이션 파일을 저장합니다.
  • IAM S3 버킷 정책 -
    • Jenkins 서버가 S3 버킷에 액세스할 수 있도록 허용합니다.
  • JenkinsRole 
    • Jenkins 서버로 사용할 Amazon EC2 인스턴스에 대한 IAM 역할 및 인스턴스 프로필입니다. 이 역할을 통해 EC2 인스턴스의 Jenkins는 S3 버킷에 액세스하여 파일을 작성하고 CodeDeploy 배포를 생성할 수 있습니다.
  • CodeDeploy 서비스 역할 
    • CodeDeploy가 인스턴스에 적용된 태그 또는 인스턴스와 연결된 EC2 Auto Scaling 그룹 이름을 읽을 수 있도록 하는 IAM 역할입니다.
  • CodeDeployRole 
    • CodeDeploy 의 EC2 인스턴스에 대한 IAM 역할 및 인스턴스 프로필입니다. 이 역할에는 이 템플릿으로 생성된 S3 버킷에 파일을 쓰고 CodeDeploy에서 배포를 생성할 수 있는 권한이 있습니다.
  • CodeBuild 프로젝트 
    • S3 버킷 및 S3 아티팩트로 구성됩니다.
  • CodeBuildRole 
    • CodeBuild에서 S3 버킷에 액세스하고 빌드 프로젝트를 생성하는 데 사용할 IAM 역할입니다.
  • Jenkins 서버
    • 필요한 모든 Jenkins 플러그인이 필수 종속성과 함께 설치된 Jenkins를 실행하는 EC2 인스턴스입니다.
  • Auto Scaling 그룹 
    • Apache를 실행하는 EC2 인스턴스와 Elastic Load Balancer가 전면에 있는 CodeDeploy 에이전트를 포함합니다.
  • Auto Scaling 시작 구성
    • Auto Scaling 그룹에서 사용합니다.
  • 보안 그룹 
    • Jenkins 서버, 로드 밸런서 및 CodeDeploy EC2 인스턴스용.

 

1. 배포 워크플로 : GitHub 리포지토리에 애플리케이션 코드를 배치

자동화하기 위해 소스 코드 섹션 아래의 Jenkins 프로젝트에 소스 코드 관리를 추가합니다.

* GitHub는 설계상 Jenkins 로컬 작업 공간 디렉터리 안의 GitHub 리포지토리 콘텐츠에서 복사본을 복제하는 SCM 옵션 선택

2.  "SCM 폴링" 옵션을 사용하여 Jenkins 서버에 대한 트리거를 활성화합니다

* Jenkins가 지정된 빈도로 새로운 커밋/코드 변경 사항이 있는지 구성된 리포지토리를 확인 합니다.

 


 

[사전 작업]

샘플 Application을 채우기 위해서 github 계정과 파일을 업로드해야합니다.

sample-application.zip
0.01MB

 

파일은 친절하게 올려드림

개인 Github 계정에 로그인 하고

새 저장소를 만들고 이름을입력합니다 .

업로드는 Public으로 !

uploading an existiong file로 Drag and Drop으로 파일을 업로드합니다.

나도 맥 사고싶다

 

Uploading Sample Application as first workshop

Commit Comments를 입력하고 첫 번째 커밋실행!


 

1. Cloudformation 배포

 

Cloudformation stack을 만드는데 

여기는 프랑크푸르트에서 만들더라구요 저는 그거 싫어서 그냥 오하이오에 했어요

CodeDeployTemplate.json
0.03MB
배포 완료!

 

2. JENKINS 서버에 액세스

cloudformation에서 출력된 결과를 보고 jenkins 서버에 엑세스 해보도록 합시다.

JenkinsServerDNSName 값을 브라우저에 붙입니다

 

이때 [ Jenkins 서버의 잠금을 해제 ] 해야합니다. 

방법 1.

EC2 인스턴스로 가면  Public IP주소와 기존에 다운받은 pem 키로 Jenkins Serverdp 접속합니다.

[root@ip-10-0-1-28 ~]# cat /var/lib/jenkins/secrets/initialAdminPassword
c13a762f90434572bca0d349dad146ad

 

방법 2.

로그 파일(/var/log/jenkins/jenkins.log)을 확인합니다.

[root@ip-10-0-1-28 ~]# cat /var/log/jenkins/jenkins.log

자동으로 생성된 영숫자 암호(별표 두 세트 사이)를 확인 하고 이것을 사용하여 Jenkins 서버의 잠금을 해제시킵니다.

*************************************************************
*************************************************************
*************************************************************

Jenkins initial setup is required. An admin user has been created and a password generated.
Please use the following password to proceed to installation:

c13a762f90434572bca0d349dad146ad

This may also be found at: /var/lib/jenkins/secrets/initialAdminPassword

*************************************************************
*************************************************************
*************************************************************

 

 

비밀번호를 확인 후 Unlock Jenkins를 합니다.

Install suggested plugins 선택

Jenkins 사용자의 사용자 이름, 암호, 전체 이름 및 이메일 주소를 입력하고 설정을 끝낸 후 Jenkins is ready가 나올 때까지 기다립니다!

 

2-1. JENKINS 구성빌드(1)

CodeDeploy Jenkins 플러그인을 구성해볼게요.

*** CloudFormation 출력 탭의 출력이랑 값을 알아둬야해요!!

* CodeBuildProjectName : Codebuildtest
* CodeDeployApplicationName : Codedepolytest-DemoApplication-KHTEGKPDYMYY
* CodeDeployDeploymentGroup : Codedepolytest-DemoFleet-13UQ1A58Z8CU9
* S3BucketName : codedepolytest-codedeploybucket-1o3y8pkbc33xa
* AWS 리전 : us-east-2 
* AWS 액세스 및 비밀 키 : 다운받은 pem키

 

먼저 Jenkins에 로그인하고 Manage Jenkins 를 클릭 한 다음 Manage Plugins 선택

그리고 플러그인을 검색해서 다시시작 X  설치로 선택 

[플러그인]
a. AWS CodeDeploy b. AWS Codebuild c. Http Request d. File Operations

 

 

설치가 완료되면 New item으로 가셔서 프로젝트 이름 : CodeDeployApp과 

Freestyle project 선택합니다

 

프로젝트 구성 페이지

➕ 소스 코드 관리

✔ Git

✔ 리포지토리 URL :  GitHub 리포지토리의 URL을 입력합니다.

Branch Specifier (blank for 'any') : */main 으로 ! (thx martin)

 

 

➕ 빌드 트리거

✔ Poll SCM

✔ 일정에 H/2 * * * *를 입력

이 항목은 업데이트를 위해 2분마다 Jenkins에서 GitHub를 폴링하도록 합니다.

 

➕ 빌드 환경 작업

✔ 공간 삭제 확인

 각 Jenkins 프로젝트에는 전용 작업 공간 디렉토리가 있는데 공간 삭제를 하면

새로운 Jenkins 빌드마다 작업 공간 디렉토리를 지워서 깨끗하게 유지할 수 있다는 장점이 있습니다.

 

 

 

 

2개 생성해야함!!!!

 

 

고급  >  Response > Output response to file : codebuild-artifact.zip

 

 

 

 

3.. JENKINS CICD test

제가 여기서 이틀동안 삽질했습니다

도움주신 리눅서님, 성주님, 야매님 정말 복받으십시오.

 

깃헙에서 젠킨스에서 배포를 하는데

[AWS CodeBuild Plugin] Collecting Flask
[AWS CodeBuild Plugin] /usr/local/lib/python2.7/dist-packages/pip/_vendor/urllib3/util/ssl_.py:339: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
[AWS CodeBuild Plugin]   SNIMissingWarning
[AWS CodeBuild Plugin] /usr/local/lib/python2.7/dist-packages/pip/_vendor/urllib3/util/ssl_.py:137: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
[AWS CodeBuild Plugin]   InsecurePlatformWarning
[AWS CodeBuild Plugin]   Could not find a version that satisfies the requirement Flask (from versions: )
[AWS CodeBuild Plugin] No matching distribution found for Flask

자꾸 이딴게 뜬다.

성주님 : 사설 인증서가 위험하다는 건뎅..? 문제 없어

난 이거 처음봐서 엄청 삽질했다 

 

그래서 이게 문제있는건가 생각해봄 

buildspec.yml 파일에 있는 것들은 수정해보고 설치해보고 별 난리부르스 해봄

version: 0.2
  
phases:
  install:
    commands:
- python -m pip install pyopenssl --upgrade
- python -m pip install flask

이걸 해봐도 또 오류 나고 오류 나고 오류 나고 

진정해라

 

일단 네일을 받고 진정을 함

 

근데 AWS 콘솔에 코드빌드를 한번 보자 했죠

깃헙 - 젠킨스는 잘 되니까 

CodeBuild >  빌드 프로젝트 >  Codedeploytest(이름) > 환경 편집

현재 환경이미지가 ubuntu 14.04가 되어있어서

파이썬도 읍고 pip도 읍고 도통 아무것도 없었떤거임 ^_^

 

낡아빠진....ㅎ.ㅎ.ㅎ.ㅎ.

 

그래서 새로 최신으로 그냥 바꿈!

그리고 돌림

Running as SYSTEM
Building in workspace /var/lib/jenkins/workspace/CodeDeployApp
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Deferred wipeout is used...
[WS-CLEANUP] Done
The recommended git tool is: NONE
No credentials specified
Cloning the remote Git repository
Cloning repository https://github.com/fullmoonhwi1116/AWSJenkinsWorkshop.git
 > git init /var/lib/jenkins/workspace/CodeDeployApp # timeout=10
Fetching upstream changes from https://github.com/fullmoonhwi1116/AWSJenkinsWorkshop.git
 > git --version # timeout=10
 > git --version # 'git version 2.32.0'
 > git fetch --tags --force --progress -- https://github.com/fullmoonhwi1116/AWSJenkinsWorkshop.git +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git config remote.origin.url https://github.com/fullmoonhwi1116/AWSJenkinsWorkshop.git # timeout=10
 > git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/* # timeout=10
Avoid second fetch
 > git rev-parse refs/remotes/origin/main^{commit} # timeout=10
Checking out Revision 2b2c6d4591ddca6f5c0a5ecb36132856ee92c95e (refs/remotes/origin/main)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 2b2c6d4591ddca6f5c0a5ecb36132856ee92c95e # timeout=10
Commit message: "commit"
 > git rev-list --no-walk 2b2c6d4591ddca6f5c0a5ecb36132856ee92c95e # timeout=10
[AWS CodeBuild Plugin] Using given AWS access and secret key for authorization
[AWS CodeBuild Plugin] Zipping directory to upload to S3: /var/lib/jenkins/workspace/CodeDeployApp
[AWS CodeBuild Plugin] Uploading to S3 at location codedeploytest-codedeploybucket-ub40kil5izdm/test. MD5 checksum is Q1Be15XNZdoovXEZOzwAjA==
[AWS CodeBuild Plugin] S3 object version id for uploaded source is d_z8q_h0.DrANeMKMKu9EH9N2MAUSMyS
[AWS CodeBuild Plugin] Starting build with 
	> project name: Codedeploytest
	> source version: d_z8q_h0.DrANeMKMKu9EH9N2MAUSMyS
	> Download build artifacts: false
[AWS CodeBuild Plugin] Build id: Codedeploytest:e4454b49-d4f1-4dfb-9309-cf25fe493f17
[AWS CodeBuild Plugin] CodeBuild dashboard: https://us-east-2.console.aws.amazon.com/codesuite/codebuild/projects/Codedeploytest/build/Codedeploytest:e4454b49-d4f1-4dfb-9309-cf25fe493f17/log?region=us-east-2
[AWS CodeBuild Plugin] CloudWatch dashboard: https://console.aws.amazon.com/cloudwatch/home?region=us-east-2#logEvent:group=/aws/codebuild/Codedeploytest;stream=e4454b49-d4f1-4dfb-9309-cf25fe493f17
[AWS CodeBuild Plugin] 2021/09/01 15:12:31 Waiting for agent ping
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Waiting for DOWNLOAD_SOURCE
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Phase is DOWNLOAD_SOURCE
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 CODEBUILD_SRC_DIR=/codebuild/output/src590171318/src
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 YAML location is /codebuild/output/src590171318/src/buildspec.yml
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Processing environment variables
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 No runtime version selected in buildspec.
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Moving to directory /codebuild/output/src590171318/src
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Registering with agent
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Phases found in YAML: 3
[AWS CodeBuild Plugin] 2021/09/01 15:12:34  INSTALL: 1 commands
[AWS CodeBuild Plugin] 2021/09/01 15:12:34  BUILD: 3 commands
[AWS CodeBuild Plugin] 2021/09/01 15:12:34  POST_BUILD: 1 commands
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Phase complete: DOWNLOAD_SOURCE State: SUCCEEDED
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Phase context status code:  Message: 
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Entering phase INSTALL
[AWS CodeBuild Plugin] 2021/09/01 15:12:34 Running command pip3 install Flask
[AWS CodeBuild Plugin] Requirement already satisfied: Flask in /root/.pyenv/versions/3.9.5/lib/python3.9/site-packages (1.1.4)
[AWS CodeBuild Plugin] Requirement already satisfied: Jinja2<3.0,>=2.10.1 in /root/.pyenv/versions/3.9.5/lib/python3.9/site-packages (from Flask) (2.11.3)
[AWS CodeBuild Plugin] Requirement already satisfied: itsdangerous<2.0,>=0.24 in /root/.pyenv/versions/3.9.5/lib/python3.9/site-packages (from Flask) (1.1.0)
[AWS CodeBuild Plugin] Requirement already satisfied: Werkzeug<2.0,>=0.15 in /root/.pyenv/versions/3.9.5/lib/python3.9/site-packages (from Flask) (1.0.1)
[AWS CodeBuild Plugin] Requirement already satisfied: click<8.0,>=5.1 in /root/.pyenv/versions/3.9.5/lib/python3.9/site-packages (from Flask) (7.1.2)
[AWS CodeBuild Plugin] Requirement already satisfied: MarkupSafe>=0.23 in /root/.pyenv/versions/3.9.5/lib/python3.9/site-packages (from Jinja2<3.0,>=2.10.1->Flask) (2.0.1)
[AWS CodeBuild Plugin] WARNING: Running pip as root will break packages and permissions. You should install packages reliably by using venv: https://pip.pypa.io/warnings/venv
[AWS CodeBuild Plugin] WARNING: You are using pip version 21.1.2; however, version 21.2.4 is available.
[AWS CodeBuild Plugin] You should consider upgrading via the '/root/.pyenv/versions/3.9.5/bin/python3.9 -m pip install --upgrade pip' command.
[AWS CodeBuild Plugin] 
[AWS CodeBuild Plugin] 2021/09/01 15:12:43 Phase complete: INSTALL State: SUCCEEDED
[AWS CodeBuild Plugin] 2021/09/01 15:12:43 Phase context status code:  Message: 
[AWS CodeBuild Plugin] 2021/09/01 15:12:43 Entering phase PRE_BUILD
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Phase complete: PRE_BUILD State: SUCCEEDED
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Phase context status code:  Message: 
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Entering phase BUILD
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Running command echo Build started on `date`
[AWS CodeBuild Plugin] Build started on Wed Sep 1 15:12:44 UTC 2021
[AWS CodeBuild Plugin] 
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Running command echo Compiling the Python code...
[AWS CodeBuild Plugin] Compiling the Python code...
[AWS CodeBuild Plugin] 
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Running command python3 test_app.py
[AWS CodeBuild Plugin] ..
[AWS CodeBuild Plugin] ----------------------------------------------------------------------
[AWS CodeBuild Plugin] Ran 2 tests in 0.012s
[AWS CodeBuild Plugin] 
[AWS CodeBuild Plugin] OK
[AWS CodeBuild Plugin] 
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Phase complete: BUILD State: SUCCEEDED
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Phase context status code:  Message: 
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Entering phase POST_BUILD
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Running command echo Build completed on `date`
[AWS CodeBuild Plugin] Build completed on Wed Sep 1 15:12:44 UTC 2021
[AWS CodeBuild Plugin] 
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Phase complete: POST_BUILD State: SUCCEEDED
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Phase context status code:  Message: 
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding base directory path: .
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Assembling file list
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding .
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding file paths for base directory .
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Assembling file list
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding web.py
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding appspec.yml
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding templates/layout.html
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding templates/test.html
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding scripts/mkdir.sh
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding scripts/start_flask.sh
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding scripts/stop_flask1.sh
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Expanding scripts/stop_flask.py
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Found 8 file(s)
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Phase complete: UPLOAD_ARTIFACTS State: SUCCEEDED
[AWS CodeBuild Plugin] 2021/09/01 15:12:44 Phase context status code:  Message: 
Build step 'AWS CodeBuild' changed build result to SUCCESS
File Delete Operation:
/var/lib/jenkins/workspace/CodeDeployApp/appspec.yml deleting....
Success.
/var/lib/jenkins/workspace/CodeDeployApp/buildspec.yml deleting....
Success.
/var/lib/jenkins/workspace/CodeDeployApp/requirements.txt deleting....
Success.
/var/lib/jenkins/workspace/CodeDeployApp/test_app.py deleting....
Success.
/var/lib/jenkins/workspace/CodeDeployApp/web.py deleting....
Success.
HttpMethod: GET
URL: http://s3-us-east-2.amazonaws.com/codedeploytest-codedeploybucket-ub40kil5izdm/codebuild-artifact.zip
Sending request to url: http://s3-us-east-2.amazonaws.com/codedeploytest-codedeploybucket-ub40kil5izdm/codebuild-artifact.zip
Response Code: HTTP/1.1 200 OK
Success: Status code 200 is in the accepted range: 100:399
Saving response body to /var/lib/jenkins/workspace/CodeDeployApp/codebuild-artifact.zip
Unzip File Operation:
Unzipping codebuild-artifact.zip to /var/lib/jenkins/workspace/CodeDeployApp
Unzip completed.
Folder Delete Operation:
Deleting folder: /var/lib/jenkins/workspace/CodeDeployApp/codebuild-artifact.zip
Finished: SUCCESS

 

오우 쒯ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ

지저스 크라이스트!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 

드디어 올라갔다 이게 올라가면 EBSDNSName을 확인할 수 있음

 

http://Codedeploytest-ELB-1M7LLE6MDYHEC-1028237727.us-east-2.elb.amazonaws.com

 

 

 

 

 

 

이거 지우고 다시만든거임

그냥 다 셌으면 한 70번 돌렸을걸?..

ㅋㅋㅎㅎㅎㅎ

 

아 미쳤다ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ 성공 삽질 미쳤음

 

다시한번 말하지만 이거 만든 사람 죽일거당,,,수정할거면 제대로하라고..ㅠㅠㅠㅠㅠㅠㅠ

728x90