Kubernetes CI/CD 1/3

2022. 5. 25. 17:54·System Engineering/Kubernetes

Vagrantfile 새로 작성

# -*- mode: ruby -*-
# vi: set ft=ruby :
 
Vagrant.configure("2") do |config|
 
  #Jenkins
  config.vm.define "jenkins" do |config|
    config.vm.box = "ubuntu/focal64"
    config.vm.provider "virtualbox" do |vb|
      vb.name = "jenkins"
      vb.cpus = 2
      vb.memory = 2048
    end
    config.vm.hostname = "jenkins"
    config.vm.network "private_network", ip: "192.168.56.101", nic_type: "virtio"
  end
 
  #Tomcat
  config.vm.define "tomcat" do |config|
    config.vm.box = "ubuntu/focal64"
    config.vm.provider "virtualbox" do |vb|
      vb.name = "tomcat"
      vb.cpus = 2
      vb.memory = 2048
    end
    config.vm.hostname = "tomcat"
    config.vm.network "private_network", ip: "192.168.56.102", nic_type: "virtio"
  end
 
  #Docker
  config.vm.define "docker" do |config|
    config.vm.box = "ubuntu/focal64"
    config.vm.provider "virtualbox" do |vb|
      vb.name = "docker"
      vb.cpus = 2
      vb.memory = 2048
    end
    config.vm.hostname = "docker"
    config.vm.network "private_network", ip: "192.168.56.103", nic_type: "virtio"
  end
 
  #Ansible
  config.vm.define "ansible" do |config|
    config.vm.box = "ubuntu/focal64"
    config.vm.provider "virtualbox" do |vb|
      vb.name = "ansible"
      vb.cpus = 2
      vb.memory = 2048
    end
    config.vm.hostname = "ansible"
    config.vm.network "private_network", ip: "192.168.56.104", nic_type: "virtio"
  end
 
  #Kubernetes
  config.vm.define "k8s" do |config|
    config.vm.box = "ubuntu/focal64"
    config.vm.provider "virtualbox" do |vb|
      vb.name = "k8s"
      vb.cpus = 2
      vb.memory = 4096
    end
    config.vm.hostname = "k8s"
    config.vm.network "private_network", ip: "192.168.56.105", nic_type: "virtio"
  end
 
  # Enable SSH Password Authentication
  config.vm.provision "shell", inline: <<-SHELL
    sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/g' /etc/ssh/sshd_config
    sed -i 's/archive.ubuntu.com/ftp.daum.net/g' /etc/apt/sources.list
    sed -i 's/security.ubuntu.com/ftp.daum.net/g' /etc/apt/sources.list
    systemctl reload ssh
  SHELL
end

 

 

 

Jenkins vm에 jenkins 설치

참고) https://www.jenkins.io/doc/book/installing/linux

 

1) java jdk

●     sudo apt update

●     sudo apt -y install openjdk-11-jdk

2) java 설치 확인

●     java --version

3) java 환경변수 변경 및 적용

●     vi ~/.bashrc

(맨 아래부분에 추가)
JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
PATH=$PATH:$JAVA_HOME

●     exec bash

●     echo $JAVA_HOME

●     echo $PATH

4) jenkins 설치

●     wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -

●     sudo sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'

●     sudo apt-get update

●     sudo apt-get -y install jenkins

●     systemctl status jenkins.service

5) jenkins Web UI 접속 : http://192.168.56.101:8080

6) 초기 jenkins Unlock 암호 입력 (파일 위치는 웹페이지에 출력)

●     sudo cat /var/lib/jenkins/secrets/initialAdminPassword

7) 플러그인 설치 선택: Select Plugin to install 선택 => 다음단계로 진행 (설치)

8) 계정 생성 : ID/PW/이름/이메일

9) 접근할 주소 : 기본값 (http://192.168.56.101:8080)

10) 관리 콘솔 메인화면 표시 확인 후 JDK 설정

●     Jenkins 관리

○   Global Tool Configuration

■   JDK

●     이름: JAVA_HOME

●     위치: /usr/lib/jvm/java-11-openjdk-amd64

 

 

 

 

jenkins 동작 테스트

 

샘플 프로젝트 생성

1. 프로젝트 생성

●     새로운 Item

○   이름: My-First-Project

○   타입: Freestyle Project

●     Buid

○   Execute Shell

■   echo Hello

2. 프로젝트 빌드

 build now 실행

 

 

 

Git, Maven 설치 및 구성

1. Git

●     기본적으로 git 설치되어 있는 경우 설치 필요하지 않음

●     설치되어 있지 않을 경우 별도로 설치

○   sudo apt install git

●     jenkins 에서 git 연결 설정

○   Jenkins 관리

■   Global Tool Configuration

●     Git

○   이름: Git

○   위치: git

2. Maven

●     Jenkins에서 빌드를 담당할 도구

●     설치

○   sudo apt install maven

●     PATH등 환경설정

○   vi ~/.bashrc

(맨 아래부분에 추가 및 기존 내용 수정)
JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
M2_HOME=/usr/share/maven
PATH=$PATH:$JAVA_HOME:$M2_HOME

○   exec bash

○   echo $M2_HOME

○   echo $PATH

●     확인: mvn --version

●     jenkins 에서 maven 연결 설정

○   Jenkins 관리

■   Global Tool Configuration

●     Maven (맨 아래 있는 항목)

○   이름: Maven_Home

○   위치: /usr/share/maven

●     플러그인 설치

○   Jenkins 관리

■   Plugin 관리

●     설치 가능 (검색창을 통해 검색 가능)

○   Maven Integration

○   Maven Invoker

●     참고) Maven 동작 라이프사이클

○   clean : 빌드 관련된 내용 정리

○   compile : 소스코드 컴파일

○   test : 컴파일된 코드 테스트

○   package : 컴파일 된 코드를 JAR/WAR 생성

○   verify : 통합 테스트

○   install : 로컬 저장소에 패키지 배포

○   deploy : 원격 저장소에 패키지 배포

 

 

Jenkins, Maven을 사용한 애플리케이션 빌드 테스트

1. maven build 테스트

●     샘플 코드 git 주소: https://github.com/c1t1d0s7/source-java-maven-hello-world.git

○   git clone https://github.com/c1t1d0s7/source-java-maven-hello-world.git

○   cd source-java-maven-hello-world

●     mvn install

○   빌드 후 war 파일 생성 확인 : webapp/target/webapp.war

●     테스트 완료 후 빌드에 사용된 디렉토리 삭제

○   rm -rf ~/source-java-maven-hello-world

2. build에 사용할 소스를 github에 업로드

●     테스트용 샘플코드 다시 clone

○   git clone https://github.com/c1t1d0s7/source-java-maven-hello-world.git

○   cd source-java-maven-hello-world

●     기존 clone으로 복사된 git 설정 삭제

○   rm -rf .git

●     git 초기화설정

○   git init

●     git 기본설정

○   git config

■   git config user.name <github 사용자명>

■   git config user.email <github계정 이메일>

○   git add

■   git add .          // 현재 디렉토리를 git대상으로 등록

○   git commit

■   git commit -m '설명'             // 현재 git 대상 파일 등록

○   git branch

■   git branch -M 'master'         // master 이름의 branch 사용

○   git remote

■   git remote add origin <github repository 주소>
   // origin 이름의 원격 저장소 주소 설정

○   git push

■   git push origin master
   // master 브랜치를 origin 주소로 push
   // 인증이 필요함: Token 발급

3. Jenkins에서 maven을 사용한 빌드 생성

●     새로운 item

○   이름: My-First-Maven-Project

○   타입: Maven Project

■   소스코드 관리

●     git

○   repository: 자신의 github repository주소

○   branch: 사용한 branch

●     Build

○   root POM : pom.xml

○   Goals and options: clean install

4. 프로젝트 build

●     프로젝트 화면에서 Build Now 실행

○   프로젝트 빌드 콘솔화면 확인 가능

●     프로젝트 빌드 결과물 위치

○   /var/lib/jenkins/workspace/<프로젝트명>

 

 

 

참고) github Access Token 발급

●     계정설정

○   Developer Setting

■   Personal Access Token

●     Generate Token

○   Repo 항목 체크

○   Expiration 기간 설정

 

참고) gitgub 계정 설정 저장

●     git config credential.helper

○   git config credential.helper store                     // 설정에 인증정보 저장

○   git config credential.helper cache
  // 캐시에 인증정보 저장 (유효기간 있음. 기본값 1시간)

 

 

Jenkins를 사용한 빌드 및 Tomcat 서버에 어플리케이션 배포

 

1. Tomcat VM 구동

●     vagrant up tomcat

 

2. Tomcat 서버 설정

1) java jdk

●     sudo apt update

●     sudo apt -y install openjdk-11-jdk

2) java 설치 확인

●     java --version

3) java 환경변수 변경 및 적용

●     vi ~/.bashrc

(맨 아래부분에 추가)
JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
PATH=$PATH:$JAVA_HOME

●     exec bash

●     echo $JAVA_HOME

●     echo $PATH

4) Tomcat 설치 및 확인

●     sudo apt -y install tomcat9 tomcat9-admin

●     sudo systemctl status tomcat9

5) Tomcat 서버 설정 확인 및 수정, 설정 반영

●     sudo vi /etc/tomcat9/tomcat-users.xml

<tomcat-users>
...
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <user username="admin" password="admin" roles="manager-gui, manager-script, manager-jmx, manager-status"/>
  <user username="deployer" password="deployer" roles="manager-script"/>
  <user username="tomcat" password="tomcat" roles="manager-gui"/>
</tomcat-users>

●     서비스 재시작: sudo systemctl restart tomcat9.service

●     웹 UI 연결 및 tomcat-admin manager 연결 확인 (http://192.168.56.102:8080)

5) Jenkins 플러그인 추가

●     Jenkins 관리

○   Plugin 관리

■   설치 가능 (검색창을 통해 검색 가능)

●     Deploy to Container

6) Jenkins에서 빌드 및 배포 수행하는 프로젝트를 생성

●     이전 단계와 동일한 부분 : git 및 maven 설정

●     빌드 후 조치 부분 추가

○   Deploy war/ear to a container

■   WAR/EAR files: **/*.war (빌드 workspace 내 war 파일 경로)

■   Container: Tomcat 9.x remote

●     Credential

○   add

■   Username: deployer

■   Password: deployer

■   ID: tomcat_deployer_id

○   tomcat_deployer_id 선택

●     Tomcat URL: http://192.168.56.102:8080

●     설정 완료 후 저장

7) 프로젝트 빌드

●     빌드 후 확인

○   http://192.168.56.102:8080/webapp               // 빌드된 앱 접속

○   http://192.168.56.102:8080/manager            // 빌드 설정 확인

 

 

Jenkins와 Docker를 사용한 배포

 

1.Docker VM 구동

●     vagrant up docker

 

2. docker 서버 설정 (docker vm에서)

1) Docker 설치를 위한 Repository 설정

●     sudo apt update

●     sudo apt -y install apt-transport-https ca-certificates curl gnupg lsb-release

●     curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

●     echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

2) Docker 설치

●     sudo apt update

●     sudo apt install docker-ce docker-ce-cli containerd.io

3) 사용자 docker 그룹 설정

●     sudo usermod -aG docker vagrant

4) 로그아웃 후 다시 로그인

5) docker 동작 확인

●     systemctl status docker.service

●     docker ps

●     docker run --rm hello-world

6) 빌드된 파일을 사용하기 위한 Tomcat 이미지 정보 확인

●     https://hub.docker.com/_/tomcat

●     docker run -d --name tomcat -p 8080:8080 tomcat:9-jre11

7) jenkins를 통해 빌드된 파일을 배포될 시스템으로 옮기기 위한 플러그인 설치

●     Jenkins 관리

○   Plugin 관리

■   설치 가능 (검색창을 통해 검색 가능)

●     Publish over SSH

8) SSH 로 파일 복사를 하기 위한 설정

●     Jenkins 관리

○   시스템 설정

■   Publish over SSH

●     SSH 서버 추가 (맨 밑에)

○   Name: docker-host      // 현재 설정 이름

○   Hostname: 192.168.56.103

○   Username: vagrant

○   Use password authentication, or use a different key 체크    // 아래 '고급' 버튼 클릭하여 생성

■   Passphrase / Password: vagrant

○   Test Configuration : 연결 테스트

■   설정 완료 후 저장

9) Jenkins에서 빌드 및 파일 복사를 수행하는 프로젝트를 생성

●     이름: Deploy-to-docker-with-Artifact

●     타입: Maven 프로젝트

●     이전 단계와 동일한 부분 : git 및 maven 설정

●     빌드 후 조치 부분 추가

○   Send build artifact over SSH

■   SSH Server: docker-host                // 이전에 생성한 SSH 연결 설정

■   Source file: webapp/target/webapp.war     // 복사할 파일

■   Remove Prefix: webapp/target
   // 파일 복사시 경로에서 제거할 부분

■   Remote Directory: hello-world
   // 복사할 대상에서 지정할 경로.
   // 기본 위치인 홈 디렉토리부터 상대경로

●     저장 및 빌드 실행

●     결과확인: docker vm의 /home/vagrant 홈디렉토리에 hello-world 디렉토리 및 파일

 

 

 

Docker에서 전달받은 파일을 CI에 통합하는 과정

1) Dockerfile을 사용한 전달받은 빌드를 포함한 이미지 생성(docker vm에서)

●     docker vm의 ~/Dockerfile

FROM    tomcat:9-jre11
COPY    ./webapp.war /usr/local/tomcat/webapps

●     docker build -t my-hello-world .

●     테스트: docker run -d --name mytomcat -p 8080:8080 my-hello-world:latest

2) 빌드에 필요한 Dockerfile을 통합 (jenkins vm에서)

●     기존 git으로 관리하던 경로로 이동

○   cd ~/source-java-maven-hello-world

●     Dockerfile을 저장할 경로 및 파일 생성

○   mkdir docker

○   vi docker/Dockerfile

FROM    tomcat:9-jre11
COPY    ./webapp.war /usr/local/tomcat/webapps

●     추가된 내용을 github repository에 반영

○   git add .

○   git commit -m 'add Dockerfile'

○   git push origin master

3)  Jenkins에서 빌드 및 파일 복사, 생성된 이미지를 사용하는 컨테이너 배포 프로젝트

●     이름: Deploy-to-docker-with-container

●     타입: Maven 프로젝트

●     이전 단계와 동일한 부분 : git 및 maven 설정

●     빌드 후 조치 부분 추가

○   Send build artifact over SSH

■   기존 war 파일을 복사하는 부분 동일하게 설정

■   새로운 항목 추가 (Add Transfer Set)

●     Source file: docker/Dockerfile

●     Remove Prefix: docker

●     Remote Directory: hello-world

●     Exec Command

docker build -t my-hello-world ~/hello-world
docker run -d --name my-hello-world-container -p 8080:8080 my-hello-world

4) 프로젝트 생성 완료 후 빌드 실행 및 확인

●     http://192.168.56.103:8080

●     (docker vm에서)

○   docker images

○   docker ps

5) 어플리케이션 컨텐츠 변경 후 재 빌드 테스트 (jenkins vm에서)

●      vi webapp/src/main/webapp/index.jsp                // 페이지 수정

●     github 반영

○   git add .

○   git commit -m 'Modify index.jsp'

○   git push origin master

6) 재 빌드 실행 후 오류 발생 확인

●     빌드 과정 화면(콘솔)에서 오류 확인 가능

ERROR: Exception when publishing, exception message [Exec exit status not zero. Status [125]]
Build step 'Send build artifacts over SSH' changed build result to UNSTABLE
Finished: UNSTABLE

●     오류 원인: 이전 프로젝트 빌드를 통해 생성된 컨테이너와 같은 이름의 컨테이너 생성

 

 

Ansble을 사용하여 배포에 유연함을 더해주기

 

1. ansible 설치

1) ansible vm에서 ansible 기능 설치

●     sudo apt update

●     sudo apt -y install ansible

2) ansible을 사용한 ssh 연결 설정

●     SSH 키 생성 : ssh-keygen

●     SSH 키 복사 : ssh-copy-id vagrant@192.168.56.104
// 자기자신에게 ansible로 작업을 보내기 위해

3) ansible 기본 환경설정

●     사용자 기본 환경설정 ~/.ansible.cfg

[defaults]
inventory = ./inventory.ini

●     사용자 기본 인벤토리 ~/inventory.ini

[ansible_host]
192.168.56.104           ansible_connection=local

●     테스트: ansible -m ping all

4) yaml 파일 편집용 설정 추가 (옵션)

●     vi ~/.vimrc

syntax on
autocmd FileType yaml setlocal ts=2 sts=2 sw=2 ai et

 

2.  docker 설치 (ansible vm에서)

1) Docker 설치를 위한 Repository 설정

●     sudo apt update

●     sudo apt -y install apt-transport-https ca-certificates curl gnupg lsb-release

●     curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

●     echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

2) Docker 설치

●     sudo apt update

●     sudo apt -y install docker-ce docker-ce-cli containerd.io

3) 사용자 docker 그룹 설정

●     sudo usermod -aG docker vagrant

4) 로그아웃 후 다시 로그인

5) docker 동작 확인

●     systemctl status docker.service

●     docker ps

●     docker run --rm hello-world

 

 

3. 배포작업을 위한 플레이북 작성

●     미리 배포작업에 필요한 webapp.war 파일 및 Dockerfile을 ~/hello-world로 복사

●     vi ~/hello-world/test.yaml

---
- name: Jenkins CI/CD Test Playbook
  hosts: ansible_host
  tasks:
  - name: build docker image with war file
    command: docker build -t my-hello-world .
    args:
      chdir: /home/vagrant/hello-world
  - name: run container with my image
    command: docker run -d --name my-hello-world-container -p 8080:8080 my-hello-world

●     vi ~/hello-world/repeatable.yaml

---
- name: Jenkins CI/CD Test Playbook (Repeatable)
  hosts: ansible_host
  tasks:
  - name: clean docker image and container
    block:
    - name: stop container
      command: docker stop my-hello-world-container
    - name: remove container
      command: docker rm my-hello-world-container
    - name: remove image
      command: docker rmi my-hello-world
    ignore_errors: true
  - name: build docker image with war file
    command: docker build -t my-hello-world .
    args:
      chdir: /home/vagrant/hello-world
  - name: run container with my image
    command: docker run -d --name my-hello-world-container -p 8080:8080 my-hello-world

 

4. Jenkins에 Playbook을 사용하는 작업을 포함한 프로젝트 생성

1) playbook 추가

●     cd ~/source-java-maven-hello-world

●     mkdir playbook

●     vi playbook/docker.yaml

---
- name: Jenkins CI/CD Test Playbook (Repeatable)
  hosts: ansible_host
  tasks:
  - name: clean docker image and container
    block:
    - name: stop container
      command: docker stop my-hello-world-container
    - name: remove container
      command: docker rm my-hello-world-container
    - name: remove image
      command: docker rmi my-hello-world
    ignore_errors: true
  - name: build docker image with war file
    command: docker build -t my-hello-world .
    args:
      chdir: /home/vagrant/hello-world
  - name: run container with my image
    command: docker run -d --name my-hello-world-container -p 8080:8080 my-hello-world

●     github에 반영

○   git add .

○   git commit -m 'add playbook'

○   git push origin master

2) SSH 로 파일 복사를 하기 위한 설정

●     Jenkins 관리

○   시스템 설정

■   Publish over SSH

●     SSH 서버 추가 (맨 밑에)

○   Name: ansible-host     // 현재 설정 이름

○   Hostname: 192.168.56.104

○   Username: vagrant

○   Use password authentication, or use a different key 체크    // 아래 '고급' 버튼 클릭하여 생성

■   Passphrase / Password: vagrant

○   Test Configuration : 연결 테스트

■   설정 완료 후 저장

3)  Jenkins에서 빌드 및 파일 복사, 배포 시 playbook을 사용하는 프로젝트 생성

●     이름: Deploy-to-ansible-with-Playbook

●     타입: Maven 프로젝트

●     이전 단계와 동일한 부분 : git 및 maven 설정

●     빌드 후 조치 부분 추가

○   Send build artifact over SSH

■   Playbook 실행결과를 상세히 보고 싶을 경우, 상단 고급 클릭 후 Verbose Output 옵션 체크

■   SSH Server: ansible-host

■   기존 war 파일을 복사하는 부분 동일하게 설정

●     기존 exec command 부분은 빼고

■   새로운 항목 추가 (Add Transfer Set)

●     Source file: playbook/docker.yaml

●     Remove Prefix: playbook

●     Remote Directory: hello-world

●     Exec Command

ansible-playbook ~/hello-world/docker.yaml

●     프로젝트 빌드 후 결과 확인

 

4) 어플리케이션 소스 업데이트에 따른 빌드 반영여부 확인 (jenkins vm에서)

●     cd ~/source-java-maven-hello-world

●     vi webapp/src/main/webapp/index.jsp       // 내용 수정

●     github 반영

○   git add .

○   git commit -m 'modify index.jsp (ansible)'

○   git push origin master

●     프로젝트 빌드 재실행 (Web UI)

CI/CD 구성에 Kubernetes 포함

 

클러스터 된 Kubernetes 환경에서 이미지를 로드하기 위한 방법

●     외부 저장소(Private Registry) 등을 사용한 이미지 배포

●     Docker Hub, ECR(Elastic Continer Registry) 등

 

구성

●     jenkins : CI/CD 구성을 담당

●     ansible : ansible 기능을 추가. docker image 빌드, docker hub 푸시

●     kubernetes : 파드 구동

 

Docker Hub 계정 준비

●     docker push <Dockerhub계정>/my-hello-world:tagname

 

Docker Hub로 빌드된 이미지를 Push 하는 ansible playbook 작성

---
- name: build image and push to docker hub play
  hosts: ansible_host
  tasks:
  - name: remove image
    command: docker rmi <Dockerhub계정>/my-hello-world
    ignore_errors: true
  - name: build image
    command: docker build -t <Dockerhub계정>/my-hello-world ~/hello-world
  #- name: docker login
  #  command: docker login -u <ID> -p <PW>   // 계정정보 취급주의!
  - name: push image
    command: docker push <Dockerhub계정>/my-hello-world

 

Kubernetes 실습환경구성 (k8s vm에서)

1) kubernetes 클러스터 구성 (k8s 단일노드 구성, control 통합)

●     설치

○   sudo apt update

○   sudo apt install -y python3 python3-pip git

○   git clone --single-branch --branch release-2.16 https://github.com/kubernetes-sigs/kubespray.git

○   cd ~/kubespray

○   sudo pip3 install -r requirements.txt

○   cp -rfp inventory/sample inventory/mycluster

○   vi inventory/mycluster/inventory.ini

[all]
k8s      ansible_host=192.168.56.105 ip=192.168.56.105
 
[kube_control_plane]
k8s
 
[etcd]
k8s
 
[kube_node]
k8s
 
[calico_rr]
 
[k8s_cluster:children]
kube_control_plane
kube_node
calico_rr

●     ssh 키 기반 인증 설정 (ansible로 kubespray 설치를 진행하기 때문에 필요함)

○   ssh-keygen

○   ssh-copy-id vagrant@192.168.56.105

●     연결 테스트 및 설치

○   ansible all -i inventory/mycluster/inventory.ini -m ping

○   ansible-playbook -i inventory/mycluster/inventory.ini cluster.yml --become
  // 이 작업은 시간 좀 걸림

●     설치 완료 후 권한 설정 (k8s VM에서)

○   mkdir ~/.kube

○   sudo cp /etc/kubernetes/admin.conf ~/.kube/config

○   sudo chown $USER:$USER ~/.kube/config

●     쿠버네티스 클러스터 구성 확인

○   kubectl get nodes

○   kubectl cluster-info

●     kubectl 명령 bash-completion 설정

○   kubectl completion bash | sudo tee /etc/bash_completion.d/kubectl

○   exec bash

 

참고) yaml 편집 시 vi에서 간편 설정하는 법

:set ts=2 sts=2 sw=2 ai et

 

kubernetes에서 준비된 이미지를 사용하는 리소스 오브젝트 파일 생성 및 테스트

●     디플로이먼트 deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-hello-world-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-hello-world
  template:
    metadata:
      labels:
        app: my-hello-world
    spec:
      containers:
      - name: my-hello-world-container
        image: deyiho2401/my-hello-world
        ports:
        - containerPort: 8080
          protocol: TCP

●     서비스 service.yaml

apiVersion: v1
kind: Service
metadata:
  name: my-hello-world-service
spec:
  type: NodePort
  selector:
    app: my-hello-world
  ports:
  - port: 8080
    targetPort: 8080
    nodePort: 30880

●     생성한 오브젝트 파일을 사용하여 리소스 생성 테스트

 

 

 

Jenkins를 사용한 이미지 업로드용 CI 프로젝트 생성

●     CI 및 CD 작업 구성에 필요한 파일들을 git 저장소로 복사

○   playbook/push.yaml

○   manifest/deployment.yaml

○   manifest/service.yaml

●     어플리케이션 컨텐츠 수정 (변경 확인을 위해)

○    vi webapp/src/main/webapp/index.jsp

●     github 저장소 변경 반영

○   git add .

○   git commit -m 'CI config'

○   git push origin master

●     기존 Docker Container 배포 내용과 거의 동일

○   프로젝트 이름: Push_image_to_Dockerhub_CI

○   대부분의 설정은 이전 프로젝트와 동일

○   최종 실행되는 플레이북을 push.yaml 로 적용

---
- name: build image and push to docker hub play
  hosts: ansible_host
  tasks:
  - name: remove image
    command: docker rmi deyiho2401/my-hello-world
    ignore_errors: true
  - name: build image
    command: docker build -t deyiho2401/my-hello-world ~/hello-world
  #- name: docker login
  #  command: docker login -u <ID> -p <PW>
  - name: push image
    command: docker push deyiho2401/my-hello-world

 

Jenkins를 사용한 이미지 배포용 CD 프로젝트 생성

●     SSH 파일 배포를 위한 설정

○   Jenkins 관리 - 시스템 설정 - Publish over SSH

■   SSH 서버 추가 (맨 밑에)

●     Name: k8s-host

●     Hostname: 192.168.56.105

●     Username: vagrant

●     Use password authentication, or use a different key 체크       // 아래 '고급' 버튼 클릭하여 생성

○   Passphrase / Password: vagrant

●     CD작업에 필요한 파일 배포 및 리소스 생성 프로젝트 생성

○   프로젝트 이름: Deploy_to_k8s_CD

○   git repository 설정

○   빌드 유발

■   Build after other projects are built

●     CI 빌드 작업의 이름 입력 (Push_image_to_Dockerhub_CI)

●     Trigger only if build is stable

○   빌드 후 조치

■   SSH-Server : k8s-host

■   Transfer

●     Source Files: manifest/*.yaml

●     Remove Prefix: 빈칸

●     Remote Directory: 빈칸

●     Exec Command

kubectl apply -f ~/manifest

●     빌드 테스트 후 어플리케이션 컨텐츠 업데이트 하여 CI에 이어지는 CD 배포 확인

○   jenkins vm의 git 저장소에서

■   vi webapp/src/main/webapp/index.jsp

○   github 변경 반영

■   git add .

■   git commit -m 'CI/CD complete'

■   git push origin master

●     현재 상태에서 CD 빌드 재수행 시 어플리케이션에 변화가 없음

○   CD 빌드가 수행되었으나, k8s 리소스에는 변화가 없음

○   디플로이먼트 리소스에 대해 변경된 이미지로 다시 로드하기 위해서는

■   kubectl rollout restart deployment <Deployment 이름>

○   위 명령을 CD 배포의 exec command 아래에 추가

저작자표시 비영리

'System Engineering > Kubernetes' 카테고리의 다른 글

Kubernetes Network 이론  (0) 2022.07.12
DOIK 스터디 1주차 (Headless, Stateful)  (0) 2022.05.29
Helm이란 무엇이고 왜 써야하는가?  (0) 2022.05.17
Service는 Service Name:port로 접근할 수 있다.  (0) 2022.05.16
kubernetes 10/17  (0) 2022.05.02
'System Engineering/Kubernetes' 카테고리의 다른 글
  • Kubernetes Network 이론
  • DOIK 스터디 1주차 (Headless, Stateful)
  • Helm이란 무엇이고 왜 써야하는가?
  • Service는 Service Name:port로 접근할 수 있다.
Hojae Lee
Hojae Lee
Solutions Architect
  • Hojae Lee
    기억력이 금붕어라
    Hojae Lee
  • 전체
    오늘
    어제
  • 공지사항

    • 참고사항
    • 이 블로그를 잘 활용하는 방법
    • my linkedin
    • 분류 전체보기 (404)
      • Career Path (19)
        • My Achievements (10)
        • About Career (1)
      • Projects for $100 (1)
      • CLOUD (183)
        • Azure Cloud (61)
        • AWS Cloud (120)
      • System Engineering (91)
        • Kubernetes (48)
        • Docker (0)
        • System Design (4)
        • DevOps (2)
        • SRE (5)
        • git (1)
        • 리눅스, 라즈베리파이 (17)
        • Powershell (2)
      • Computer Science (70)
        • Operating System (22)
        • Computer Architecture (5)
        • Network (18)
        • Database (13)
        • Security (9)
        • Machine Learning, AI (1)
      • Cloud Webinar (4)
        • AWS Summit (4)
      • 3D 프린터 (1)
      • IaC (4)
        • CloudFormation (0)
        • Terraform (4)
      • 아두이노 (임베디드) (2)
      • 개발자의 전기 전자 공부 (3)
      • 이전 직장 (11)
        • TMAX Soft (11)
      • 작업 환경 셋업 (3)
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
Hojae Lee
Kubernetes CI/CD 1/3
상단으로

티스토리툴바