본문 바로가기
IT와 코딩

멀티클라우드를 고려한 컨테이너 기반의 CI/CD 파이프라인 구축

by 불타는통닭 2024. 7. 4.

멀티클라우드를 고려한 컨테이너 기반의 CI/CD 파이프라인 구축 

 

목차

Ch01. DevOps 및 CI/CD 이해

Ch02. Jenkins 구성 및 Pipeline

Ch03. Docker Container와 Jenkins 통합

Ch04. Ansible 구성 관리 및 Jenkins 통합

Ch05. Kubernetes Orchestration과 Jenkins 통합

 

 

Ch01. DevOps 및 CI/CD 이해

 

DevOps

  - Development + Operations

    (개발, QA, 운영)

  - 소프트웨어 개발자와 IT 인프라 전문가 간의 소통 및 협업을 강조하는 문화

  - 신규 서비스/제품을 발빠르게 개발 및 배포하는 것을 목적으로 함.

 

DevOps Toolchain
  - DevOps를 구현하기 위한 도구들의 모임

 

 

DevOps 관련 기술

 구성 요소 및 배치 크기를 세분화

 상향식의 유연한 방법

 

  Agile 

  ArchOps

  CI/CD

  SRE(Site Reliability Engineering)

  DevSecOps

 

DevOps

  Microservices

  DevOps Automation

  Automation with Version Control



 

DevOps Toolchain

 - 기획

 - 개발

 - 검증

 - 패키징

 - 릴리즈

 - 구성

 - 모니터링

 - 버전 관리

 

소프트웨어 개발 모델

Waterfall 모델

 - 순차적으로 소프트웨어를 개발하는 개발 프로세스로 개발 흐름이 마치 폭포수처럼 지속적으로 아래로 향하는 것처럼 보이는 데에서 유래함.

  - 소프트웨어 요구사항 분석

  - 소프트웨어 설계

  - 소프트웨어 구현

  - 소프트웨어 테스트

  - 소프트웨어 통합

  - 소프트웨어 유지보수

 

Agile 모델

  소프트웨어 개발에 있어 아무런 계획이 없는 것과 지나치게 계획이 많은 것의 절충점을 찾고자하는 소프트웨어 개발 방법론/개발 모델

  일정한 주기를 가지고 끊임없이 프로토타입을 개발하며 필요한 요구사항을 반영하여 커다란 소프트웨어를 개발하는 개발 방법

 

Cloud Native

  현대적이고 동적인 클라우드 환경에서 확장 가능한 애플리케이션을 개발하는 것

   Container, Service Mesh, Microservice, Immutable Infrastructure, 선언형 API

 

Application Architecture

  Monolithic Architecture

   - 애플리케이션의 모든 기능을 하나의 애플리케이션 안에 모두 구현하는 아키텍처

   - 애플리케이션 개발이 간편함.

   - 애플리케이션의 단순한 확장

   - 단순 기능 업데이트 시에도 전체 애플리케이션을 빌드 및 패키징해야함.

 

  Microservice Architecture

   - 애플리케이션/서비스의 각각의 기능을 마이크로서비스라는 단위로 분리하여 개발하는 아키텍처

   - 마이크로서비스 마다 독립적으로 운영되고 마이크로서비스마다 최적의 개발환경으로 개발할 수 있음.

   - 마이크로서비스는 API 메시지 통신을 통해 서로 연동됨.

   - Architecture의 복잡도가 올라가 유지보수를 하는데 어려움이 있을 수 있음.




 

CI/CD

  소프트웨어 엔지니어링에서 CI(Continuous Integration)와 CD(Continuous Delivery/Deployment)

  CI(Continuous Integration) : 작은 변경사항이 발생하는 경우 이를 즉시 메인 브랜치와 통합

  CD(Continuous Delivery) :  소프트웨어를 짧은 주기로 생산하여 언제든지 신뢰할 수 있는 소프트웨어로 출시할 수 있도록 하는 것

  CD(Continuous Deployment) : 소프트웨어 기능을 완전히 자동으로 롤아웃 하는 것



소프트웨어 버전 관리 시스템(VCS, Version Control System)

  파일의 변화를 시간에 따라 기록해두었다가 특정 시점의 버전을 꺼내올 수 있는 시스템

 

버전 관리 시스템의 장점

  - 버전 별로 데이터를 보존

  - 각 버전 별로 작업 내역 관리

  - 오류 발생 시 이전 버전으로 롤백 가능함

 

버전 관리 시스템의 종류

 - 로컬 버전 관리

      파일/디렉터리를 수동으로 복사

      RCS(Revision Control System) : Patch Set 관리

 - 중앙 집중식 버전 관리

      CVS

      Subversion

       Perforce

 - 분산형 버전 관리

       Git

       Mercurial

       Bazar

       Darcs

 

Git

  Linus Torvalds가 개발한 오픈소스 형태의 분산형 버전 관리 시스템

  작업시 별도의 중앙 서버에 대한 접속 없이 독립적인 작업이 가능함

  빠른 속도가 장점이며 언제든지 원하는 시점에 작업을 마무리하고 통합할 수 있음

 

Git 특징

  - 데이터를 파일시스템 스냅샷의 연속으로 취급하고 크기가 매우 작음

  - 커밋을 하거나 프로젝트의 상태를 저장할 때마다 변경된 파일의 내용만 저장함.

  - 변경되지 않은 파일의 경우 이전 상태에 대한 링크만 저장

  - 데이터가 변경되는 시점에서 Checksum으로 데이터의 무결성을 보장함

 

Git 상태

  - Committed : 데이터가 로컬 DB에 안전하게 저장됨

  - Modified : 데이터를 수정하였고 이를 아직 로컬  DB에 Commit하지 않은 상태

  - Staged : 현재 수정한 파일을 곧 Commit할 예정이라고 표시한 상태

 

 Working Directory : 파일을 작업하는 디렉터리

 Staging Area : 곧 Commit 할 파일의 데이터를 저장하는 곳

 Repository : 프로젝트에 대해 버전관리를 하는 저장 공간

 

 

실습 환경 : 가상머신

  Oracle VirtualBox

  HashiCorp Vagrant

 

시스템 요구사항

  CPU : Dual Core 이상 

  RAM : 16GB RAM 이상

  SSD/HDD :  여유 공간 80GB 이상

Git 실습

 

Git 설치 (Ubuntu/Debian)

$ sudo apt-get update

$ sudo apt-get install git





 Git 사용자 설정/설정 해제

vagrant@jenkins:~$ ls -l /etc/gitconfig
ls: cannot access '/etc/gitconfig': No such file or directory
vagrant@jenkins:~$ git config --system user.name "USER" 
vagrant@jenkins:~$ git config --system user.email "USER@example.com" 
vagrant@jenkins:~$
vagrant@jenkins:~$ git config --system user.name "Hyoseok Cho"
error: could not lock config file /etc/gitconfig: Permission denied
vagrant@jenkins:~$ sudo git config --system user.name "Hyoseok Cho"
vagrant@jenkins:~$ sudo git config --system user.email "devops2341@gmail.com"
vagrant@jenkins:~$
vagrant@jenkins:~$ ls -l /etc/gitconfig
-rw-r--r-- 1 root root 57 Jul  1 05:54 /etc/gitconfig
vagrant@jenkins:~$ cat /etc/gitconfig
[user]
        name = Hyoseok Cho
        email = devops2341@gmail.com
vagrant@jenkins:~$
vagrant@jenkins:~$ git config --global user.name "Hyoseok Cho.global"
vagrant@jenkins:~$ git config --global user.email "devops2341@gmail.net"
vagrant@jenkins:~$
vagrant@jenkins:~$ ls -l ~/.gitconfig
-rw-rw-r-- 1 vagrant vagrant 64 Jul  1 05:56 /home/vagrant/.gitconfig
vagrant@jenkins:~$ cat ~/.gitconfig
[user]
        name = Hyoseok Cho.global
        email = devops2341@gmail.net
vagrant@jenkins:~$
vagrant@jenkins:~$ mkdir study
vagrant@jenkins:~$ mkdir study/git-config-test01
vagrant@jenkins:~$ cd study/git-config-test01/
vagrant@jenkins:~/study/git-config-test01$ ls -al
total 8
drwxrwxr-x 2 vagrant vagrant 4096 Jul  1 05:58 .
drwxrwxr-x 3 vagrant vagrant 4096 Jul  1 05:58 ..
vagrant@jenkins:~/study/git-config-test01$
vagrant@jenkins:~/study/git-config-test01$ git config --local user.name "Hyoseok Cho.local"
fatal: --local can only be used inside a git repository
vagrant@jenkins:~/study/git-config-test01$
vagrant@jenkins:~/study/git-config-test01$ git init
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint:   git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint:   git branch -m <name>
Initialized empty Git repository in /home/vagrant/study/git-config-test01/.git/
vagrant@jenkins:~/study/git-config-test01$ ls -al
total 12
drwxrwxr-x 3 vagrant vagrant 4096 Jul  1 05:59 .
drwxrwxr-x 3 vagrant vagrant 4096 Jul  1 05:58 ..
drwxrwxr-x 7 vagrant vagrant 4096 Jul  1 05:59 .git
vagrant@jenkins:~/study/git-config-test01$ git config --local user.name "Hyoseok Cho.local"
vagrant@jenkins:~/study/git-config-test01$ git config --local user.email "devops2341@gmail.org"
vagrant@jenkins:~/study/git-config-test01$
vagrant@jenkins:~/study/git-config-test01$ ls -al .git/config
-rw-rw-r-- 1 vagrant vagrant 155 Jul  1 06:01 .git/config
vagrant@jenkins:~/study/git-config-test01$ ls -al .git/
total 40
drwxrwxr-x 7 vagrant vagrant 4096 Jul  1 06:01 .
drwxrwxr-x 3 vagrant vagrant 4096 Jul  1 05:59 ..
-rw-rw-r-- 1 vagrant vagrant   23 Jul  1 05:59 HEAD
drwxrwxr-x 2 vagrant vagrant 4096 Jul  1 05:59 branches
-rw-rw-r-- 1 vagrant vagrant  155 Jul  1 06:01 config
-rw-rw-r-- 1 vagrant vagrant   73 Jul  1 05:59 description
drwxrwxr-x 2 vagrant vagrant 4096 Jul  1 05:59 hooks
drwxrwxr-x 2 vagrant vagrant 4096 Jul  1 05:59 info
drwxrwxr-x 4 vagrant vagrant 4096 Jul  1 05:59 objects
drwxrwxr-x 4 vagrant vagrant 4096 Jul  1 05:59 refs
vagrant@jenkins:~/study/git-config-test01$ cat .git/config
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
[user]
        name = Hyoseok Cho.local
        email = devops2341@gmail.org
vagrant@jenkins:~/study/git-config-test01$
vagrant@jenkins:~/study/git-config-test01$ sudo git config --system --unset user.name
vagrant@jenkins:~/study/git-config-test01$ sudo git config --system --unset user.email
vagrant@jenkins:~/study/git-config-test01$
vagrant@jenkins:~/study/git-config-test01$ cat /etc/gitconfig
vagrant@jenkins:~/study/git-config-test01$
vagrant@jenkins:~/study/git-config-test01$ git config --global --unset user.name
vagrant@jenkins:~/study/git-config-test01$ git config --global --unset user.email
vagrant@jenkins:~/study/git-config-test01$
vagrant@jenkins:~/study/git-config-test01$ cat ~/.gitconfig
vagrant@jenkins:~/study/git-config-test01$

vagrant@jenkins:~/study/git-config-test01$ git config --local --unset user.name
vagrant@jenkins:~/study/git-config-test01$ git config --local --unset user.email
vagrant@jenkins:~/study/git-config-test01$
vagrant@jenkins:~/study/git-config-test01$ cat ./.git/config
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true




특정 Repository에 사용자 설정하여 버전 관리

 

vagrant@jenkins:~/study/git-config-test01$ git init

Reinitialized existing Git repository in /home/vagrant/study/git-config-test01/.git/

vagrant@jenkins:~/study/git-config-test01$ git config --local user.name "Hyoseok Cho"

vagrant@jenkins:~/study/git-config-test01$ git config --local user.email "devops2341@gmail.com"

vagrant@jenkins:~/study/git-config-test01$

vagrant@jenkins:~/study/git-config-test01$ cat ./.git/config

[core]

        repositoryformatversion = 0

        filemode = true

        bare = false

        logallrefupdates = true

[user]

        name = Hyoseok Cho

        email = devops2341@gmail.com

vagrant@jenkins:~/study/git-config-test01$

vagrant@jenkins:~/study/git-config-test01$ git config --list

core.repositoryformatversion=0

core.filemode=true

core.bare=false

core.logallrefupdates=true

user.name=Hyoseok Cho

user.email=devops2341@gmail.com

 

 

[git 실습01 : add/commit]

vagrant@jenkins:~/study/git-config-test01$ echo "Hello World Git" > file01.txt

vagrant@jenkins:~/study/git-config-test01$ ls -l

total 4

-rw-rw-r-- 1 vagrant vagrant 16 Jul  1 06:12 file01.txt

vagrant@jenkins:~/study/git-config-test01$ cat file01.txt

Hello World Git

vagrant@jenkins:~/study/git-config-test01$

vagrant@jenkins:~/study/git-config-test01$ git status

On branch master

 

No commits yet

 

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        file01.txt

 

nothing added to commit but untracked files present (use "git add" to track)

   (Staging Area에 file01.txt 파일이 추가됨(커밋 전))

 

vagrant@jenkins:~/study/git-config-test01$



vagrant@jenkins:~/study/git-config-test01$ git commit -m "First Commit"

[master (root-commit) 4963f21] First Commit

 1 file changed, 1 insertion(+)

 create mode 100644 file01.txt

vagrant@jenkins:~/study/git-config-test01$

vagrant@jenkins:~/study/git-config-test01$ git status

On branch master

nothing to commit, working tree clean

  (Commit 이후라 Commit 할 내용이 없음을 확인)

 

vagrant@jenkins:~/study/git-config-test01$ echo "File for second commit" > file02.txt

vagrant@jenkins:~/study/git-config-test01$ ls -l

total 8

-rw-rw-r-- 1 vagrant vagrant 16 Jul  1 06:12 file01.txt

-rw-rw-r-- 1 vagrant vagrant 23 Jul  1 06:21 file02.txt

vagrant@jenkins:~/study/git-config-test01$

vagrant@jenkins:~/study/git-config-test01$ git status

On branch master

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        file02.txt

 

nothing added to commit but untracked files present (use "git add" to track)

 

vagrant@jenkins:~/study/git-config-test01$ git add file02.txt

vagrant@jenkins:~/study/git-config-test01$

vagrant@jenkins:~/study/git-config-test01$ git status

On branch master

Changes to be committed:

  (use "git restore --staged <file>..." to unstage)

        new file:   file02.txt

 

vagrant@jenkins:~/study/git-config-test01$ git commit -m "Second Commit"

[master 000ced3] Second Commit

 1 file changed, 1 insertion(+)

 create mode 100644 file02.txt

vagrant@jenkins:~/study/git-config-test01$

vagrant@jenkins:~/study/git-config-test01$ git status

On branch master

nothing to commit, working tree clean



vagrant@jenkins:~/study/git-config-test01$ git log

commit 000ced3eb17d0e70dc25a69550ec0b466f56d78d (HEAD -> master)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:22:56 2024 +0000

 

    Second Commit

 

commit 4963f2143313835e22c89f46193822479ac77ab8

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:19:50 2024 +0000

 

    First Commit

 

file01.txt  파일 관련 Commit 이력 조회

vagrant@jenkins:~/study/git-config-test01$ git log --follow file01.txt

commit 4963f2143313835e22c89f46193822479ac77ab8

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:19:50 2024 +0000

 

    First Commit

 

 

[git config 설정]

vagrant@jenkins:~/study/$ git config --global user.name "Hyoseok Cho"

vagrant@jenkins:~/study$ git config --global user.email "devops2341@gmail.com"

vagrant@jenkins:~/study/$

vagrant@jenkins:~/study/$ git config --list

user.name=Hyoseok Cho

user.email=devops2341@gmail.com



 

[git 실습02 - Branch ]

vagrant@jenkins:~/study/git-branch-test01$ git branch

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git branch -m main

vagrant@jenkins:~/study/git-branch-test01$ git branch

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ echo "First Commit" > file01.txt

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch main

 

No commits yet

 

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        file01.txt

 

nothing added to commit but untracked files present (use "git add" to track)

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git add file01.txt

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch main

 

No commits yet

 

Changes to be committed:

  (use "git rm --cached <file>..." to unstage)

        new file:   file01.txt

 

vagrant@jenkins:~/study/git-branch-test01$ git commit -m "First Commit"

[main (root-commit) 4c796a6] First Commit

 1 file changed, 1 insertion(+)

 create mode 100644 file01.txt

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch main

nothing to commit, working tree clean

 

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch main

nothing to commit, working tree clean

vagrant@jenkins:~/study/git-branch-test01$ git branch

* main

vagrant@jenkins:~/study/git-branch-test01$ echo "Second Commit on main branch" > file02.txt

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch main

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        file02.txt

 

nothing added to commit but untracked files present (use "git add" to track)

vagrant@jenkins:~/study/git-branch-test01$ git add .

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch main

Changes to be committed:

  (use "git restore --staged <file>..." to unstage)

        new file:   file02.txt

 

vagrant@jenkins:~/study/git-branch-test01$ git commit -m "Second Commit on main branch"

[main dcfb4cd] Second Commit on main branch

 1 file changed, 1 insertion(+)

 create mode 100644 file02.txt

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git log

commit dcfb4cde027f92fd7ec1b3ddcd24e078d93e9902 (HEAD -> main)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:59:05 2024 +0000

 

    Second Commit on main branch

 

commit 4c796a636a3f65fc161f75baf23ad9b409a15627

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:56:44 2024 +0000

 

    First Commit

 

vagrant@jenkins:~/study/git-branch-test01$ git branch test

vagrant@jenkins:~/study/git-branch-test01$ git branch

* main

  test

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git branch -m test study

vagrant@jenkins:~/study/git-branch-test01$ git branch

* main

  study

 

vagrant@jenkins:~/study/git-branch-test01$ echo "file03.txt on study branch" > file03.txt

vagrant@jenkins:~/study/git-branch-test01$ ls -l

total 12

-rw-rw-r-- 1 vagrant vagrant 13 Jul  1 06:55 file01.txt

-rw-rw-r-- 1 vagrant vagrant 29 Jul  1 06:58 file02.txt

-rw-rw-r-- 1 vagrant vagrant 27 Jul  1 07:03 file03.txt

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch study

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        file03.txt

 

nothing added to commit but untracked files present (use "git add" to track)

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git add file03.txt

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch study

Changes to be committed:

  (use "git restore --staged <file>..." to unstage)

        new file:   file03.txt

 

vagrant@jenkins:~/study/git-branch-test01$ git commit -m "First Commit on study branch"

[study 008a51a] First Commit on study branch

 1 file changed, 1 insertion(+)

 create mode 100644 file03.txt

 

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch study

nothing to commit, working tree clean

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git log

commit 008a51aba70f4ccaf087cb34c05f478728840a6d (HEAD -> study)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 07:05:22 2024 +0000

 

    First Commit on study branch

 

commit dcfb4cde027f92fd7ec1b3ddcd24e078d93e9902 (main)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:59:05 2024 +0000

 

    Second Commit on main branch

 

commit 4c796a636a3f65fc161f75baf23ad9b409a15627

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:56:44 2024 +0000

 

    First Commit

vagrant@jenkins:~/study/git-branch-test01$ ls -l

total 12

-rw-rw-r-- 1 vagrant vagrant 13 Jul  1 06:55 file01.txt

-rw-rw-r-- 1 vagrant vagrant 29 Jul  1 06:58 file02.txt

-rw-rw-r-- 1 vagrant vagrant 27 Jul  1 07:07 file03.txt

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git switch main

Switched to branch 'main'

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch main

nothing to commit, working tree clean

vagrant@jenkins:~/study/git-branch-test01$ ls -l

total 8

-rw-rw-r-- 1 vagrant vagrant 13 Jul  1 06:55 file01.txt

-rw-rw-r-- 1 vagrant vagrant 29 Jul  1 06:58 file02.txt

 

vagrant@jenkins:~/study/git-branch-test01$ git branch -d study

error: The branch 'study' is not fully merged.

If you are sure you want to delete it, run 'git branch -D study'.

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git branch

* main

  study

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git branch -D study

Deleted branch study (was 008a51a).

vagrant@jenkins:~/study/git-branch-test01$ git branch

* main

 

vagrant@jenkins:~/study/git-branch-test01$ git switch -c practice

Switched to a new branch 'practice'

vagrant@jenkins:~/study/git-branch-test01$ git branch

  main

* practice

 

vagrant@jenkins:~/study/git-branch-test01$ git branch -v

  main     dcfb4cd Second Commit on main branch

* practice dcfb4cd Second Commit on main branch

  (branch 생성 직후여서 두 branch가 동일한 포인터를 가리킴)

 

vagrant@jenkins:~/study/git-branch-test01$ echo "file03.txt First Commit on practice branch" > file03.txt

vagrant@jenkins:~/study/git-branch-test01$ git add .

vagrant@jenkins:~/study/git-branch-test01$ git commit -m "First Commit on practice branch"

[practice fe2b8e6] First Commit on practice branch

 1 file changed, 1 insertion(+)

 create mode 100644 file03.txt

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git status

On branch practice

nothing to commit, working tree clean

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git log

commit fe2b8e645272c9c376e30af19f6b2ebf760252e7 (HEAD -> practice)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 07:15:05 2024 +0000

 

    First Commit on practice branch

 

commit dcfb4cde027f92fd7ec1b3ddcd24e078d93e9902 (main)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:59:05 2024 +0000

 

    Second Commit on main branch

 

commit 4c796a636a3f65fc161f75baf23ad9b409a15627

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:56:44 2024 +0000

 

    First Commit

vagrant@jenkins:~/study/git-branch-test01$

vagrant@jenkins:~/study/git-branch-test01$ git branch -v

  main     dcfb4cd Second Commit on main branch

* practice fe2b8e6 First Commit on practice branch

  (practice branch에서 새로운 commit 발생 후 변경된 상태 확인)

 

vagrant@jenkins:~/study/git-branch-test01$ git switch main

Switched to branch 'main'

vagrant@jenkins:~/study/git-branch-test01$ git branch

* main

  practice

 

vagrant@jenkins:~/study/git-branch-test01$ git log

commit dcfb4cde027f92fd7ec1b3ddcd24e078d93e9902 (HEAD -> main)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:59:05 2024 +0000

 

    Second Commit on main branch

 

commit 4c796a636a3f65fc161f75baf23ad9b409a15627

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:56:44 2024 +0000

 

    First Commit

vagrant@jenkins:~/study/git-branch-test01$ git merge practice

Updating dcfb4cd..fe2b8e6

Fast-forward

 file03.txt | 1 +

 1 file changed, 1 insertion(+)

 create mode 100644 file03.txt



vagrant@jenkins:~/study/git-branch-test01$ git log

commit fe2b8e645272c9c376e30af19f6b2ebf760252e7 (HEAD -> main, practice)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 07:15:05 2024 +0000

 

    First Commit on practice branch

 

commit dcfb4cde027f92fd7ec1b3ddcd24e078d93e9902

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:59:05 2024 +0000

 

    Second Commit on main branch

 

commit 4c796a636a3f65fc161f75baf23ad9b409a15627

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 06:56:44 2024 +0000

 

    First Commit

 

  (Merge 내용 확인)

 

—--


Git Branch Merge

  - 두개 이상의 Branch의 변경 사항을 하나의 Branch로 합치는 것

  - 특정 기능을 개발하기 위해 분기했던 Branch를 주 Branch에 합칠 때 사용함

  - Branch Merge 방식은 여러가지이나 Fast-Forward Merge, 3-Way Merge를 주로 사용함




Fast Forward Merge

 - 기존의 Branch의 변경이 없는 상태에서 새로 분기한 Branch의 변경사항만 있는 경우 사용하는 Merge 방식

 - Branch 병합시 높은 Commit을 가리키며 별도의 병합 Commit이 발생하지 않음

 

3-Way Merge

  - 각 Branch의 마지막 Commit 2개와 공통 Parent Commit의 총 3개의 Commit을 사용하여 새로운 Commit을 생성하는 Branch 병합 방식

 

3-Way Merge에서 필요한 Commit

  - 내 Branch의 Commit

  - 다른 Branch의 Commit

  - 두 Branch의 공통 조상이 되는 Commit



[git 실습03 - Git Merge 충돌]

vagrant@jenkins:~/study/git-branch-test01$ cd ..

vagrant@jenkins:~/study$ mkdir git-branch-test02

vagrant@jenkins:~/study$ ls

git-branch-test01  git-branch-test02  git-config-test01

vagrant@jenkins:~/study$ cd git-branch-test02/

 

vagrant@jenkins:~/study/git-branch-test02$ git init

hint: Using 'master' as the name for the initial branch. This default branch name

hint: is subject to change. To configure the initial branch name to use in all

hint: of your new repositories, which will suppress this warning, call:

hint:

hint:   git config --global init.defaultBranch <name>

hint:

hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and

hint: 'development'. The just-created branch can be renamed via this command:

hint:

hint:   git branch -m <name>

Initialized empty Git repository in /home/vagrant/study/git-branch-test02/.git/

vagrant@jenkins:~/study/git-branch-test02$

vagrant@jenkins:~/study/git-branch-test02$ git branch -m master main

vagrant@jenkins:~/study/git-branch-test02$ git status

On branch main

 

No commits yet

 

nothing to commit (create/copy files and use "git add" to track)

 

vagrant@jenkins:~/study/git-branch-test02$ echo "file01.txt" > file01.txt

vagrant@jenkins:~/study/git-branch-test02$ git add file01.txt

vagrant@jenkins:~/study/git-branch-test02$ git commit -m "First Commit on main branch"

[main (root-commit) f9363e0] First Commit on main branch

 1 file changed, 1 insertion(+)

 create mode 100644 file01.txt

vagrant@jenkins:~/study/git-branch-test02$

vagrant@jenkins:~/study/git-branch-test02$ echo "file02.txt" > file02.txt

vagrant@jenkins:~/study/git-branch-test02$ git add file02.txt

vagrant@jenkins:~/study/git-branch-test02$ git commit -m "Second Commit on main branch"

[main e247269] Second Commit on main branch

 1 file changed, 1 insertion(+)

 create mode 100644 file02.txt

vagrant@jenkins:~/study/git-branch-test02$

vagrant@jenkins:~/study/git-branch-test02$ git branch practice

vagrant@jenkins:~/study/git-branch-test02$ git branch -v

* main     e247269 Second Commit on main branch

  practice e247269 Second Commit on main branch

 

vagrant@jenkins:~/study/git-branch-test02$ echo "1. red" >> file02.txt

vagrant@jenkins:~/study/git-branch-test02$ echo "2. blue" >> file02.txt

vagrant@jenkins:~/study/git-branch-test02$ echo "3. green" >> file02.txt

vagrant@jenkins:~/study/git-branch-test02$

vagrant@jenkins:~/study/git-branch-test02$ cat file02.txt

file02.txt

1. red

2. blue

3. green

vagrant@jenkins:~/study/git-branch-test02$ git add file02.txt

vagrant@jenkins:~/study/git-branch-test02$ git commit -m "Add Color List on main branch"

[main 7d8c2f8] Add Color List on main branch

 1 file changed, 3 insertions(+)

 

vagrant@jenkins:~/study/git-branch-test02$ git log

commit 7d8c2f869c7b54ec4e6b157f49985cb176b34abe (HEAD -> main)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 07:59:41 2024 +0000

 

    Add Color List on main branch

 

commit e2472693bc92d757572b619e21a3e2124ec68330 (practice)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 07:55:59 2024 +0000

 

    Second Commit on main branch

 

commit f9363e04754d384159ea865d4aa5a15bb0a19463

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Mon Jul 1 07:55:06 2024 +0000

 

    First Commit on main branch



vagrant@jenkins:~/study/git-branch-test02$ git switch practice

Switched to branch 'practice'

vagrant@jenkins:~/study/git-branch-test02$ git branch

  main

* practice

 

vagrant@jenkins:~/study/git-branch-test02$ cat file02.txt

file02.txt

vagrant@jenkins:~/study/git-branch-test02$ echo "1. Red" >> file02.txt

vagrant@jenkins:~/study/git-branch-test02$ echo "2. Green" >> file02.txt

vagrant@jenkins:~/study/git-branch-test02$ echo "3. Orange" >> file02.txt

vagrant@jenkins:~/study/git-branch-test02$ cat file02.txt

file02.txt

1. Red

2. Green

3. Orange

vagrant@jenkins:~/study/git-branch-test02$

vagrant@jenkins:~/study/git-branch-test02$ git add file02.txt

 

vagrant@jenkins:~/study/git-branch-test02$ git commit -m "Add Color List on practice branch"

[practice 0716e5d] Add Color List on practice branch

 1 file changed, 3 insertions(+)

 

vagrant@jenkins:~/study/git-branch-test02$ git switch main

Switched to branch 'main'

vagrant@jenkins:~/study/git-branch-test02$ git branch

* main

  practice

 

vagrant@jenkins:~/study/git-branch-test02$ git merge practice

Auto-merging file02.txt

CONFLICT (content): Merge conflict in file02.txt

Automatic merge failed; fix conflicts and then commit the result.

 

vagrant@jenkins:~/study/git-branch-test02$ ls -l

total 8

-rw-rw-r-- 1 vagrant vagrant 11 Jul  1 07:54 file01.txt

-rw-rw-r-- 1 vagrant vagrant 99 Jul  1 08:05 file02.txt

vagrant@jenkins:~/study/git-branch-test02$ cat file02.txt

file02.txt

<<<<<<< HEAD

1. red

2. blue

3. green

=======

1. Red

2. Green

3. Orange

>>>>>>> practice

 

<참고> Branch Merge 실패시 Data 구조

<<<<<<< HEAD
기준 Branch Data
=======
합치고자 한 원본 Branch Data
>>>>>>> SOURCE_BRANCH_NAME

 

Merge 실패한 파일 데이터 수동으로 직접 수정

vagrant@jenkins:~/study/git-branch-test02$ vim file02.txt

file02.txt
1. red
2. blue
3. green
4. Red
5. Green
6. Orange

 

vagrant@jenkins:~/study/git-branch-test02$ git add file02.txt

vagrant@jenkins:~/study/git-branch-test02$ git commit -m "Resolve Conflicts Commit"

[main c6e9fa6] Resolve Conflicts Commit

vagrant@jenkins:~/study/git-branch-test02$

vagrant@jenkins:~/study/git-branch-test02$ git log --oneline

c6e9fa6 (HEAD -> main) Resolve Conflicts Commit

0716e5d (practice) Add Color List on practice branch

7d8c2f8 Add Color List on main branch

e247269 Second Commit on main branch

f9363e0 First Commit on main branch

vagrant@jenkins:~/study/git-branch-test02$



[git 실습 - Git Diff]

vagrant@jenkins:~/study/git-branch-test02$ vim file02.txt

file02.txt
1. Red
2. Green
3. Orange
4. Blue
5. Purple

 

vagrant@jenkins:~/study/git-branch-test02$ git diff

diff --git a/file02.txt b/file02.txt

index d4cd77a..befca3a 100644

--- a/file02.txt

+++ b/file02.txt

@@ -2,3 +2,5 @@ file02.txt

 1. Red

 2. Green

 3. Orange

+4. Blue

+5. Purple

 

vagrant@jenkins:~/study/git-branch-test02$ vim file02.txt

file02.txt
1. Red
2. Green
3. Orange
4. Blue
5. Purple
6. White

 

vagrant@jenkins:~/study/git-branch-test02$ git diff

vagrant@jenkins:~/study/git-branch-test02$ git diff HEAD

diff --git a/file02.txt b/file02.txt

index befca3a..18125b4 100644

--- a/file02.txt

+++ b/file02.txt

@@ -4,3 +4,4 @@ file02.txt

 3. Orange

 4. Blue

 5. Purple

+6. White

 

vagrant@jenkins:~/study/git-branch-test02$ git commit -am "file02.txt Modify Color List"

[practice 7e91e3a] file02.txt Modify Color List

 1 file changed, 1 insertion(+)

 

vagrant@jenkins:~/study/git-branch-test02$ vim file02.txt

file02.txt
1. Red
2. Green
3. Orange
4. Blue
5. Purple
6. White
7. Black



vagrant@jenkins:~/study/git-branch-test02$ git add file02.txt

vagrant@jenkins:~/study/git-branch-test02$ git diff

vagrant@jenkins:~/study/git-branch-test02$ git diff --staged

diff --git a/file02.txt b/file02.txt

index 18125b4..37c85eb 100644

--- a/file02.txt

+++ b/file02.txt

@@ -5,3 +5,4 @@ file02.txt

 4. Blue

 5. Purple

 6. White

+7. Black

   (Staging Area에 있는 내용 확인)

 

day02

 

가상머신 시작

cd cicd

vagrant up

 

가상머신 종료

vagrant halt



[Git Local Repository  실습1]

vagrant@jenkins:~$ mkdir ~/study/git-local-repo01

vagrant@jenkins:~$ cd ~/study/git-local-repo01/

vagrant@jenkins:~/study/git-local-repo01$ echo "Local Repository git-local-repo01 main branch file" > filea.txt

vagrant@jenkins:~/study/git-local-repo01$ ls -l

total 4

-rw-rw-r-- 1 vagrant vagrant 51 Jul  2 00:36 filea.txt

vagrant@jenkins:~/study/git-local-repo01$ git status

On branch master

 

No commits yet

 

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        filea.txt

 

nothing added to commit but untracked files present (use "git add" to track)

vagrant@jenkins:~/study/git-local-repo01$ git branch

vagrant@jenkins:~/study/git-local-repo01$ git branch -m master main

vagrant@jenkins:~/study/git-local-repo01$ git branch

vagrant@jenkins:~/study/git-local-repo01$ git status

On branch main

 

No commits yet

 

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        filea.txt

 

nothing added to commit but untracked files present (use "git add" to track)

vagrant@jenkins:~/study/git-local-repo01$

 

vagrant@jenkins:~/study/git-local-repo01$ git add filea.txt

vagrant@jenkins:~/study/git-local-repo01$ git status

On branch main

 

No commits yet

 

Changes to be committed:

  (use "git rm --cached <file>..." to unstage)

        new file:   filea.txt

 

vagrant@jenkins:~/study/git-local-repo01$ git commit -m "First Commit on main branch"

[main (root-commit) 2e02ea9] First Commit on main branch

 1 file changed, 1 insertion(+)

 create mode 100644 filea.txt

vagrant@jenkins:~/study/git-local-repo01$

vagrant@jenkins:~/study/git-local-repo01$ git log

commit 2e02ea9f800262d4bf0e1dcc3042d883dc9e4206 (HEAD -> main)

Author: Hyoseok Cho <devops2341@gmail.com>

Date:   Tue Jul 2 00:41:16 2024 +0000

 

    First Commit on main branch

vagrant@jenkins:~/study/git-local-repo01$ git log --oneline

2e02ea9 (HEAD -> main) First Commit on main branch



vagrant@jenkins:~/study/git-local-repo01$ git branch

* main

vagrant@jenkins:~/study/git-local-repo01$ git branch -v

* main 2e02ea9 First Commit on main branch

vagrant@jenkins:~/study/git-local-repo01$

vagrant@jenkins:~/study/git-local-repo01$ git branch test

vagrant@jenkins:~/study/git-local-repo01$ git branch

* main

  test

 

vagrant@jenkins:~/study/git-local-repo01$ git switch test

Switched to branch 'test'

vagrant@jenkins:~/study/git-local-repo01$ ls -l

total 4

-rw-rw-r-- 1 vagrant vagrant 51 Jul  2 00:36 filea.txt

vagrant@jenkins:~/study/git-local-repo01$

vagrant@jenkins:~/study/git-local-repo01$ echo "fileb.txt" > fileb.txt

vagrant@jenkins:~/study/git-local-repo01$ echo "filec.txt" > filec.txt

vagrant@jenkins:~/study/git-local-repo01$ ls -l

total 12

-rw-rw-r-- 1 vagrant vagrant 51 Jul  2 00:36 filea.txt

-rw-rw-r-- 1 vagrant vagrant 10 Jul  2 00:46 fileb.txt

-rw-rw-r-- 1 vagrant vagrant 10 Jul  2 00:46 filec.txt

vagrant@jenkins:~/study/git-local-repo01$ git status

On branch test

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        fileb.txt

        filec.txt

 

nothing added to commit but untracked files present (use "git add" to track)

vagrant@jenkins:~/study/git-local-repo01$

 

vagrant@jenkins:~/study/git-local-repo01$ git add fileb.txt filec.txt

 

vagrant@jenkins:~/study/git-local-repo01$ git commit -m "First Commit on test branch"

[test fabb7e6] First Commit on test branch

 2 files changed, 2 insertions(+)

 create mode 100644 fileb.txt

 create mode 100644 filec.txt

 

vagrant@jenkins:~/study/git-local-repo01$ git log --oneline

fabb7e6 (HEAD -> test) First Commit on test branch

2e02ea9 (main) First Commit on main branch

vagrant@jenkins:~/study/git-local-repo01$ ls -l

total 12

-rw-rw-r-- 1 vagrant vagrant 51 Jul  2 00:36 filea.txt

-rw-rw-r-- 1 vagrant vagrant 10 Jul  2 00:46 fileb.txt

-rw-rw-r-- 1 vagrant vagrant 10 Jul  2 00:46 filec.txt

 

vagrant@jenkins:~/study/git-local-repo01$ git switch main

Switched to branch 'main'

vagrant@jenkins:~/study/git-local-repo01$ git branch

* main

  test

 

vagrant@jenkins:~/study/git-local-repo01$ ls -l

total 4

-rw-rw-r-- 1 vagrant vagrant 51 Jul  2 00:36 filea.txt

 

vagrant@jenkins:~/study/git-local-repo01$ git switch main

Already on 'main'

vagrant@jenkins:~/study/git-local-repo01$ git branch

* main

  test

vagrant@jenkins:~/study/git-local-repo01$

vagrant@jenkins:~/study/git-local-repo01$ git merge test

Updating 2e02ea9..fabb7e6

Fast-forward

 fileb.txt | 1 +

 filec.txt | 1 +

 2 files changed, 2 insertions(+)

 create mode 100644 fileb.txt

 create mode 100644 filec.txt

vagrant@jenkins:~/study/git-local-repo01$ git branch

* main

  test

vagrant@jenkins:~/study/git-local-repo01$ git log --oneline

fabb7e6 (HEAD -> main, test) First Commit on test branch

2e02ea9 First Commit on main branch

 

 

Github 인증 방식

  - Token 인증

      사용자 계정에서 Token을 발급받아 Password 대신 사용하는 인증 방식

      기본적으로 매번 Remote Repository 작업시 Token을 입력하여 작업해야 함

  - SSH Keypair 인증

      GitHub Remote Repository에서 사용할 SSH Keypair 생성 후 SSH Public Key를 GitHub 계정에 등록하여 사용하는 인증 방식

 



 

[SSH Key Pair를 사용한 인증]

 

GitHub Remote Repository를 위한 SSH Key Pair 생성

vagrant@jenkins:~/study/git-remote-repo02$ ssh-keygen -f ~/.ssh/id_rsa-git-GITHUB_ID -C "USER@example.com"

Generating public/private rsa key pair.

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/vagrant/.ssh/id_rsa-git-devops2341

Your public key has been saved in /home/vagrant/.ssh/id_rsa-git-devops2341.pub

The key fingerprint is:

SHA256:FZCbrWu3WMba3bKR8AqPUWgKwi689OeW3Ymi/WUK/M8 USER@example.com

The key's randomart image is:

+---[RSA 3072]----+

|        .o.      |

|        .  .     |

|         +.      |

| .      oo.      |

|  o .   S.o      |

|.. ... o.o o .   |

|.o.  o+ =+= +    |

|..o .=ooB&.o.o   |

| . o=oo==E=.oo.  |

+----[SHA256]-----+

 

vagrant@jenkins:~/study/git-remote-repo02$ cat ~/.ssh/id_rsa-git-devops2341.pub

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC5uvcIH8dIKOvEOreDEGGodQB3hdjJ7XkK4Tj9fX~~~~~ devops2341@gmail.com

 

 

SSH Key Pair를 사용한 GitHub 인증

  ssh git@github.com:GITHUB_ID/REPOSITORY.git

 

vagrant@jenkins:~/study/git-remote-repo02$ git remote remove origin

vagrant@jenkins:~/study/git-remote-repo02$ git remote -v

 

vagrant@jenkins:~/study/git-remote-repo02$ git remote add origin git@github.com:devops2341/g

it-remote-repo02.git

vagrant@jenkins:~/study/git-remote-repo02$ git remote -v

origin  git@github.com:devops2341/git-remote-repo02.git (fetch)

origin  git@github.com:devops2341/git-remote-repo02.git (push)

 

vagrant@jenkins:~/study/git-remote-repo02$ vim ~/.ssh/config

Host github.com
        User git
        IdentityFile ~/.ssh/SSH_KEYFILE



vagrant@jenkins:~/study/git-remote-repo02$ ssh -T git@github.com

The authenticity of host 'github.com (20.200.245.247)' can't be established.

ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU.

This key is not known by any other names

Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

Warning: Permanently added 'github.com' (ED25519) to the list of known hosts.

Hi devops2341! You've successfully authenticated, but GitHub does not provide shell access.

 

 

Github Remote Repository 사용

 

GitHub Remote Repository 생성



vagrant@jenkins:~/study/git-remote-repo01$ git pull origin main

From https://github.com/devops2341/git-remote-repo01

 * branch            main       -> FETCH_HEAD

vagrant@jenkins:~/study/git-remote-repo01$

vagrant@jenkins:~/study/git-remote-repo01$ ls -l

total 4

-rw-rw-r-- 1 vagrant vagrant 19 Jul  2 01:29 README.md

vagrant@jenkins:~/study/git-remote-repo01$

vagrant@jenkins:~/study/git-remote-repo01$ git status

On branch master

nothing to commit, working tree clean

vagrant@jenkins:~/study/git-remote-repo01$ git branch -m master main

vagrant@jenkins:~/study/git-remote-repo01$ git branch

* main

 

vagrant@jenkins:~/study/git-remote-repo01$ git push --set-upstream origin main

Username for 'https://github.com': devops2341

Password for 'https://devops2341@github.com':

Branch 'main' set up to track remote branch 'main' from 'origin'.

Everything up-to-date

 

vagrant@jenkins:~/study/git-remote-repo01$ echo "filea.txt local repository file" > filea.tx

t

vagrant@jenkins:~/study/git-remote-repo01$ ls -l

total 8

-rw-rw-r-- 1 vagrant vagrant 19 Jul  2 01:29 README.md

-rw-rw-r-- 1 vagrant vagrant 32 Jul  2 01:49 filea.txt

vagrant@jenkins:~/study/git-remote-repo01$ git status

On branch main

Your branch is up to date with 'origin/main'.

 

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        filea.txt

 

nothing added to commit but untracked files present (use "git add" to track)

vagrant@jenkins:~/study/git-remote-repo01$ git add filea.txt

vagrant@jenkins:~/study/git-remote-repo01$ git status

On branch main

Your branch is up to date with 'origin/main'.

 

Changes to be committed:

  (use "git restore --staged <file>..." to unstage)

        new file:   filea.txt

 

vagrant@jenkins:~/study/git-remote-repo01$ git push

Username for 'https://github.com': devops2341

Password for 'https://devops2341@github.com':

Everything up-to-date

vagrant@jenkins:~/study/git-remote-repo01$

 

 

[Remote Repository 실습2]

vagrant@jenkins:~/study$ git clone https://github.com/devops2341/git-remote-repo02.git

Cloning into 'git-remote-repo02'...

remote: Enumerating objects: 3, done.

remote: Counting objects: 100% (3/3), done.

remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0

Receiving objects: 100% (3/3), done.

vagrant@jenkins:~/study$ ls

git-local-repo01  git-remote-repo01  git-remote-repo02

vagrant@jenkins:~/study$ cd git-remote-repo02

vagrant@jenkins:~/study/git-remote-repo02$

 

vagrant@jenkins:~/study/git-remote-repo02$ git status

On branch main

Your branch is up to date with 'origin/main'.

 

nothing to commit, working tree clean

vagrant@jenkins:~/study/git-remote-repo02$ git branch

* main

vagrant@jenkins:~/study/git-remote-repo02$ git remote -v

origin  https://github.com/devops2341/git-remote-repo02.git (fetch)

origin  https://github.com/devops2341/git-remote-repo02.git (push)

 

vagrant@jenkins:~/study/git-remote-repo02$ echo "filea.txt local repository file" > filea.txt

vagrant@jenkins:~/study/git-remote-repo02$ git status

On branch main

Your branch is up to date with 'origin/main'.

 

Untracked files:

  (use "git add <file>..." to include in what will be committed)

        filea.txt

 

nothing added to commit but untracked files present (use "git add" to track)

vagrant@jenkins:~/study/git-remote-repo02$ git add filea.txt

vagrant@jenkins:~/study/git-remote-repo02$ git commit -m "local repository file filea.txt"

[main 42a27e0] local repository file filea.txt

 1 file changed, 1 insertion(+)

 create mode 100644 filea.txt

 

vagrant@jenkins:~/study/git-remote-repo02$ echo "fileb.txt local file" > fileb.txt

vagrant@jenkins:~/study/git-remote-repo02$ git add .

vagrant@jenkins:~/study/git-remote-repo02$ git commit -m "fileb.txt local repository file"

[main 3f48e8a] fileb.txt local repository file

 1 file changed, 1 insertion(+)

 create mode 100644 fileb.txt

 

vagrant@jenkins:~/study/git-remote-repo02$ git push --set-upstream origin main

Enumerating objects: 4, done.

Counting objects: 100% (4/4), done.

Delta compression using up to 2 threads

Compressing objects: 100% (2/2), done.

Writing objects: 100% (3/3), 341 bytes | 341.00 KiB/s, done.

Total 3 (delta 0), reused 0 (delta 0), pack-reused 0

To github.com:devops2341/git-remote-repo02.git

   42a27e0..3f48e8a  main -> main

Branch 'main' set up to track remote branch 'main' from 'origin'.

vagrant@jenkins:~/study/git-remote-repo02$ git push

Everything up-to-date

 

 

Jenkins

  Java 기반의 오픈소스 자동화 서버

  다양한 플러그인을 사용하여 빌드에 대한 자동화를 할 수 있는 도구

  https://www.jenkins.io/

 

Jenkins 특징

 - 지속적인 통합 및 지속적인 전달

 - 다양한 운영체제 지원

    Java 기반의 독립형 실행 프로그램으로 다양한 환경에 설치 가능함

 - 쉬운 구성 지원(Web 기반의 대시보드)

 - 플러그인

 - 확장 가능

 - 분산형 아키텍처 지원

 

Jenkins 2 특징

 - Pipeline as code 및 Jenkinsfile 을 지원하는 새로운 Jenkins 버전

 

DSL(Domain Specific Language)

  - Scripted Pipeline

  - Declarative Pipeline

 

Jenkins의 주요 컴포넌트

 - Controller : Jenkins 시스템의 핵심 구성요소로 모든 설정, 옵션, 잡에 대해 관리하는 노드

                      Controller 이외에 작업을 실행할 노드가 없는 경우 잡을 실행하는 기본 노드

 - Node : Controller에 의해 관리되는 노드로 잡을 실행하기 위한 모든 시스템, 에이전트가 설치되어야 함

 - Agent : Controller에 연결하는 Java 클라이언트 프로그램

 - Executor : 잡을 실행하기 위한 슬롯, 에이전트의 스레드, 해당노드에서 실행할 수 있는 동시 작업 수



 

On-Premise에서 Jenkins 설치

 

 Package 검증을 위한 Key 추가

  sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \

    https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key

 

Package Repository 구성파일 작성

 

echo "deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc]" \

    https://pkg.jenkins.io/debian-stable binary/ | sudo tee \

    /etc/apt/sources.list.d/jenkins.list > /dev/null

 

패키지 설치

sudo apt-get update

 

sudo apt-get install fontconfig openjdk-17-jre

 

sudo apt-get install jenkins



Jenkins 접속 확인

http://JENKINS_IP:8080/

 

 

vagrant@jenkins:~$ sudo cat /var/lib/jenkins/secrets/initialAdminPassword

 

 

[Jenkins Freestyle Project 실습]

 

Maven Project 생성

 

1. Jenkins에 Maven 설치

(Jenkins에서)

vagrant@jenkins:~$ sudo apt-get update

vagrant@jenkins:~$ sudo apt-get install maven

 

JDK 설치

vagrant@jenkins:~$ sudo apt-get update

vagrant@jenkins:~$ sudo apt-get install openjdk-17-jdk

 

2. Jenkins에 Maven 설정

[Jenkins 관리] -> [Tools]

 

Maven 기반으로 Jenkins에서 새 프로젝트 생성



Maven Git Repository :  https://github.com/devops2341/source-maven-java-spring-hello-webapp

 

 

 

Tomcat

   Apache 재단에서 개발한 오픈소스 WAS 서버



Tomcat 설치 및 구성

vagrant@tomcat:~$ sudo apt-get update

vagrant@tomcat:~$ sudo apt-get install tomcat9 tomcat9-admin

 

Tomcat 관리자 정보 구성

 

vagrant@tomcat:~$ sudo vim /etc/tomcat9/tomcat-users.xml



              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">


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

 

vagrant@tomcat:~$ sudo systemctl restart tomcat9.service

 

http://192.168.56.102:8080/

http://192.168.56.102:8080/manager/html/



https://docs.github.com/ko/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo




 

 



 

 

Jenkins Pipeline

  Jenkins에서 지속적인 통합, 지속적인 배포를 위해 애플리케이션 빌드 및 배포 과정을 자동화 하는 기능

  Jenkins에는 Scripted Pipeline, Declarative Pipeline가 지원됨

  https://www.jenkins.io/doc/book/pipeline/#pipeline-syntax-overview

 

Scripted Pipeline

  - 프로그램의 흐름 및 로직을 실행하기 위한 파이프라인

  - Jenkins가 실행되는 방식과 동떨어진 동작 방식

// Jenkinsfile (Scripted Pipeline)
node {  
    stage('Build') { 
        // COMMAND
    }
    stage('Test') { 
        // COMMAND
    }
    stage('Deploy') { 
        // COMMAND
    }
}




Declarative Pipeline

  - Jenkins Web Dashboard에서 구성하는 구성과 작업을 정의하기 위한 파이프라인

  - Scripted Pipeline 대비 Pipeline 코드 가독성이 우수함

 

// Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any 
    stages {
        stage('Build') { 
            steps {
                // 
            }
        }
        stage('Test') { 
            steps {
                // 
            }
        }
        stage('Deploy') { 
            steps {
                // 
            }
        }
    }
}



Jenkins Pipeline 관련 용어

  Pipeline : Build-Test-Deployment 단계를 포함하는 빌드 및 배포에 대한 전체 과정을 정의하는 것

  Node : (Scripted Pipeline에서 사용되며) Pipeline을 실행할 수 있는 시스템

  Stage : 수행할 작업의 집합

  Step : 수행할 작업 단위

 

Jenkins Section

  agent : Pipeline 실행시 어느 에이전트에서 실행할지 정의

  post : Pipeline 또는 Stage가 완료된 후 실행되는 추가 작업을 정의

  stages : Pipeline을 여러 단계로 구성

  steps : 각 단계에서 실행될 실제 작업을 정의

 

Pipeline 지시어

  environment : 특정 작업을 수행할 때 환경변수를 정의

  options : 특정 작업의 실행 옵션을 정의

  parameters : 사용자가 작업실행시 입력할 수 있는 파라미터 정의

  triggers : 특정 조건을 충족할 때 작업을 자동으로 트리거하도록 정의

  stage : Pipeline 내에서 작업을 단계별로 그룹화

  tools : Pipeline블록 또는 stage 블록 내에서 사용할 도구 정의

  when : 작업에 대한 조건 정의



 

[Jenkins Pipeline 생성 실습 - 기본]




 

 

 

node {
    stage('Checkout') {
        sh 'ls -l /tmp'
    }
    stage('Build') {
        sh 'tar cf /tmp/result.tar /etc/hosts /etc/issue'
    }
}

 

 

 

day3

 

[Pipeline 실습]





pipeline {
agent any


stages {
stage('Checkout') {
steps {
sh 'echo "Checkout Stage" > stage01-checkout.log'
}
}
stage('Build') {
steps {
sh 'echo "Build Stage" > stage02-build.log'
}
}
stage('Test') {
steps {
sh '/bin/true && echo "Test Succeeded"'
}
}
stage('Deploy') {
steps {
sh 'echo "Application Deployed" > stage04-deploy.log'
}
}
}
}



 

[실습 : Pipeline으로 Tomcat에 웹 애플리케이션 배포]

 

GitHub Repository Fork

   https://github.com/devops2341/source-maven-java-spring-hello-webapp

 

Jenkinsfile

pipeline {
  agent any

  triggers {
    pollSCM('* * * * *')
  }

  stages {
    stage('Checkout') {
      steps {
        git branch: 'main', 
        url: 'URL'
      }
    }
    stage('Build') {
      steps {
        sh 'mvn clean package'
      }
    }
    stage('Deploy') {
      steps {
        deploy adapters: [tomcat9(credentialsId: 'CREDENTIAL_ID', url: 'DEPLOY_URL')], contextPath: null, war: 'APPLICATION_WAR_BUILD_PATH'
      }
    }
  }
}



 

Docker Container와 Jenkins 통합

 

가상머신과 컨테이너



도커

쿠버네티스



가상화(Virtualization)

  서버 가상화

  네트워크 가상화

  스토리지 가상화

  컨테이너 가상화



컨테이너

  애플리케이션, 서비스와 이를 실행하기 위한 실행 환경을 묶어서 애플리케이션, 서비스를 배포하는 단위

 

컨테이너 환경을 제공하는 기술

 - chroot

 - Solaris Containers

 - FreeBSD Jail

 - LXC

 - Docker

 - Podman

 - Kata Containers

 

컨테이너 아키텍처

 

리눅스 컨테이너를 구현하기 위한 구성요소

  - CGroups : 프로세스의 CPU, RAM, Network 등의 시스템 리소스 사용량 제한

  - Namespace : 시스템의 리소스를 사용하는 환경을 논리적으로 분리

      - Mount Namespace

      - PID Namespace

      - UID Namespace

      - Network Namespace

      - IPC(Inter-Process Communication) Namespace

      - UTS(UNIX Time Sharing) Namespace

 

 

Docker

  2014년에 Docker Inc가 개발한 컨테이너 도구

  Docker Hub를 통해 컨테이너 이미지를 쉽게 공유할 수 있음.

  https://www.docker.com/

 

Docker 관련 용어

  컨테이너(Container)

    애플리케이션, 서비스가 배포되고 실행되기 위한 단위로 컨테이너 간 또는 컨테이너와 Docker Host 간 실행환경이 완전히 격리됨.

  컨테이너 이미지(Container Image) : 애플리케이션, 서비스가 실행되기 위해  컨테이너에서 필요한 필수 데이터로 실행 전 초기의 데이터를 묶어 둔 단위 

 

  저장소(Registry)

   컨테이너 이미지가 네트워크 상에 저장되는 저장 공간

  여러 사용자들과 이미지 공유할 수 있는 저장 공간

 

Docker Architecture

 

 

Docker 설치

sudo apt-get update

sudo apt-get install ca-certificates curl

sudo install -m 0755 -d /etc/apt/keyrings

sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc

sudo chmod a+r /etc/apt/keyrings/docker.asc

 

Docker Package Repository 구성 정보 추가

echo \

  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \

  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \

  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

 

sudo apt-get update

 

sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

 

sudo usermod -aG docker vagrant

 

 

Docker 명령어 실습

 

도커 정보 확인

$ docker info

 

도커 버전 확인

$ docker version


도커 이미지 목록 확인

$ docker image ls

$ docker images

REPOSITORY   TAG       IMAGE ID   CREATED   SIZE

 

Registry : 이미지 저장소

  Repository : 이미지 저장소에 각 이미지 별로 이미지가 저장되는 공간

 

도커 공식 레지스트리(Docker Hub)

https://hub.docker.com/

 

이미지 이름 지정 형식

  (1) Docker가 직접 올린 이미지

      IMAGE_REPO:TAG

 

  (2) Docker Hub 사용자가 올린 이미지

        DOCKER_ID/IMAGE_REPO:TAG

 

도커 이미지 검색

$ docker search KEYWORD

NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED

centos                            The official build of CentOS.                   7093      [OK]                              bitnami/centos-base-buildpack     Centos base compilation image     0                               [OK]

 

hello-world 도커 컨테이너 실행

$ docker container run hello-world:latest



도커 컨테이너 이미지 다운로드(pull)

$ docker image pull IMG_REPO:TAG

$ docker pull IMG_REPO:TAG

 

새로운 컨테이너 실행

$ docker container run  [OPTION]  IMG_REPO:TAG  [COMMAND]  [ARG…]

$ docker run  [OPTION]  IMG_REPO:TAG  [COMMAND]  [ARG…]

 

$ docker container run -it --name rocky9-1 rockylinux:9



옵션 설명
-i 표준 입력을 컨테이너에 연결(키보드 입력을 컨테이너로 전달)
-t 제어 터미널을 사용(Pseudo Terminal)
-d 백그라운드(Detached Mode)로 컨테이너를 실행



실행중인 컨테이너 목록 확인

$ docker container ls

$ docker ps

 

종료된 컨테이너 포함 모든 컨테이너 목록 확인

$ docker container ls -a

$ docker ps -a



(rocky9-1 컨테이너에서)

[root@3e7a8c6b48c9 /]# ps -ef

bash: ps: command not found

[root@3e7a8c6b48c9 /]# yum install procps

[root@3e7a8c6b48c9 /]# ps -ef

UID          PID    PPID  C STIME TTY          TIME CMD

root           1       0  0 02:58 pts/0    00:00:00 /bin/bash

root          67       1  0 03:18 pts/0    00:00:00 ps -ef



(Docker Host에서)

$ ps -ef | more

UID          PID    PPID  C STIME TTY          TIME CMD

root           1       0  0 11:06 ?        00:00:04 /usr/lib/systemd/systemd rhg

b --switched-root --system --deserialize 31

root           2       0  0 11:06 ?        00:00:00 [kthreadd]

 

(컨테이너와 Docker Host와는 실행환경이 분리되어있다.)



컨테이너 내부에 진입하여 작업하는 방법

  1. 컨테이너 내부에 연결하는 명령어 실행(docker container attach)
  2. 컨테이너 내부에 추가적인 프로세스 실행(docker container exec)



Docker Container에 추가 프로세스 실행

$ docker container exec  [OPTION]  CONTAINER  PROCESS

$ docker exec  [OPTION]  CONTAINER  PROCESS

 

$ docker container exec -i -t CONTAINER /bin/bash

$ docker exec -i -t CONTAINER /bin/bash



Docker Container 종료

$ docker container stop CONTAINER

$ docker stop CONTAINER

 

Docker Container 시작

$ docker container start CONTAINER

$ docker start CONTAINER

 

Docker Container 삭제

$ docker container rm CONTAINER

$ docker rm CONTAINER

 

Docker Container 로그 확인

$ docker container logs CONTAINER

$ docker logs CONTAINER

 

Docker Container에 파일 복사

$ docker container cp SOURCE CONTAINER:/PATH

$ docker cp SOURCE CONTAINER:/PATH

 

Docker Container에서 Docker Host로 파일 복사

$ docker container cp CONTAINER:/PATH/FILE  DESTINATION

$ docker cp CONTAINER:/PATH/FILE  DESTINATION

 

모든 컨테이너 종료

docker container stop $(docker container ls -a -q)

 

모든 컨테이너 삭제

docker container rm $(docker container ls -a -q)

 

Docker Container 내의 파일 변경 상태 확인

$ docker container diff  CONTAINER

$ docker diff  CONTAINER

 

  A : 추가된 파일 

  C : 변경된 파일

  D : 삭제된 파일



Union Mount Filesystem

 

https://docs.docker.com/storage/storagedriver/

 

컨테이너 이미지 목록 확인

$ docker image ls

$ docker images

 

컨테이너 이미지 삭제

$ docker image rm  IMAGE_REPO:TAG

$ docker rmi  IMAGE_REPO:TAG

 

 

Docker Container Image 생성 방법

  1. 명령어를 통한 이미지 생성

     $ docker container commit CONTAINER  IMAGE_REPO:TAG

 

  2. Dockerfile을 통한 이미지 생성(빌드)

     $ docker image build -t IMAGE_REPO:TAG BUILD_PATH




 

Dockerfile

  - Docker Container Image 생성을 위한 코드 형태의 정의 파일

 

Dockerfile 명령어/지시어 정리

https://docs.docker.com/engine/reference/builder/



명령어 설명 비고
FROM  이미지[:태그] Base Image 지정  
RUN  명령어 명령어 실행  
CMD 명령어 컨테이너 실행시 실행 명령어  
LABEL KEY=VALUE 레이블 지정  
EXPOSE  포트
EXPOSE  포트/프로토콜
포트를 공개  
ENV  KEY=VALUE 환경변수 지정  
ADD  원본  대상경로 파일/디렉터리 추가  
COPY  원본  대상경로 파일 복사  
ENTRYPOINT 명령어 컨테이너 시작시 기본 실행 명령어  
VOLUME 컨테이너_내부경로 볼륨 연결  
USER  사용자
USER  UID
사용자 지정(컨테이너에서 특정 사용자 권한으로 실행 필요시)  
WORKDIR 디렉터리_경로 작업 디렉터리  
ARG  NAME
ARG  NAME=VALUE
Dockerfile argument  
ONBUILD  명령어 빌드 완료시 실행 작업  
STOPSIGNAL  시그널 종료 시그널 지정  
HEALTHCHECK  CMD  명령어
HEALTHCHECK  NONE
컨테이너 헬스체크  
SHELL  쉘 기본 쉘 지정  



Dockerfile을 통한 Docker Container image 빌드 방법

 1. Image 빌드를 위한 작업 디렉터리 생성 및 해당 디렉터리로 이동

   $ mkdir DIRECTORY

   $ cd DIRECTORY

 2. Dockerfile 작성

   $ vim Dockerfile

 3. 이미지 빌드 명령어 실행

   $ docker image build -t IMAGE_REPO:TAG BUILD_PATH

   $ docker build -t IMAGE_REPO:TAG BUILD_PATH

 

—-

 

$ vim Dockerfile

FROM rockylinux:9
MAINTAINER "Hong Gildong <hong@example.com>"
RUN yum install httpd -y
CMD /usr/sbin/httpd -D FOREGROUND
EXPOSE 80
COPY index.html /var/www/html/index.html

 

$ vim index.html

my_webserver v0.1

 

$ docker image build -t my_webserver:v0.1 .

 

$ docker image ls

REPOSITORY     TAG       IMAGE ID       CREATED             SIZE

my_webserver   v0.1      ecc3ee3786b1   26 seconds ago      230MB

 

$ docker container run -d -p 8081:80 --name web1 my_webserver:v0.1 

 

$ curl http://localhost:8081/

my_webserver v0.1 index.html

 

$ echo "my_webserver v0.2 index.html" > index.html

$ echo "my_webserver v0.2 test.html" > test.html




$ vim Dockerfile

FROM rockylinux:9
MAINTAINER "Hong Gildong <hong@example.com>"
RUN yum install httpd -y
CMD /usr/sbin/httpd -D FOREGROUND
EXPOSE 80
COPY index.html /var/www/html/
COPY test.html /var/www/html/

 

$ docker image build -t my_webserver:v0.2 . ^C

[user@localhost my_webserver]$ ^C

[user@localhost my_webserver]$ docker image ls

REPOSITORY     TAG       IMAGE ID       CREATED              SIZE

my_webserver   v0.2      28a59802fc39   About a minute ago   230MB

 

$ docker container run -d -p 8082:80 --name web2 my_webserver:v0.2 

 

$ docker container ls

CONTAINER ID   IMAGE               COMMAND                  CREATED          STATUS          PORTS                                   NAMES

f46768d7615a   my_webserver:v0.2   "/bin/sh -c '/usr/sb…"   14 seconds ago   Up 13 seconds   0.0.0.0:8082->80/tcp, :::8082->80/tcp   web2

fe410a69a9a4   my_webserver:v0.1   "/bin/sh -c '/usr/sb…"   8 minutes ago    Up 8 minutes    0.0.0.0:8081->80/tcp, :::8081->80/tcp   web1

 

$ curl http://localhost:8082/

my_webserver v0.2 index.html

 

$ curl http://localhost:8082/test.html

my_webserver v0.2 test.html




Container Registry에 Container Image 업로드(Push)

$ docker image push  IMAGE_REPO:TAG

$ docker push  IMAGE_REPO:TAG

 

docker image tag IMAGE_REPO:TAG NEW_IMAGE_REPO:TAG

docker tag IMAGE_REPO:TAG NEW_IMAGE_REPO:TAG



$ docker login

$ docker logout

 

 

[Docker Container로 Tomcat WAS 실행 및 애플리케이션 배포 실습]

 

$ mkdir ~/work/tomcat-webapp

$ cd ~/work/tomcat-webapp

 

$ vim Dockerfile

FROM maven:3-openjdk-17 AS mbuilder
RUN mkdir /hello
RUN git clone <URL> /hello
WORKDIR /hello
RUN mvn package

FROM tomcat:9-jre11
COPY --from=mbuilder /hello/target/hello-world.war /usr/local/tomcat/webapps/

 

vagrant@docker:~/work/tomcat-webapp$ docker image build -t myhello:v1.0 .

 

vagrant@docker:~/work/tomcat-webapp$ docker image ls

REPOSITORY                TAG       IMAGE ID       CREATED             SIZE

myhello                   v1.0      f7f6b9be33a4   22 seconds ago      283MB

 

vagrant@docker:~/work/tomcat-webapp$ docker container run -d -p 80:8080 --name myhello-web myhello:v1.0

584896a186233e7359985e726fd71acf16985cf7e9e58de04727f78ece0a4aca

 

vagrant@docker:~/work/tomcat-webapp$ docker container ls

CONTAINER ID   IMAGE          COMMAND             CREATED         STATUS         PORTS                                   NAMES

584896a18623   myhello:v1.0   "catalina.sh run"   6 seconds ago   Up 6 seconds   0.0.0.0:80->8080/tcp, :::80->8080/tcp   myhello-web

 

vagrant@docker:~/work/tomcat-webapp$ curl http://192.168.56.103/hello-world/

 

<html>

<head>

<title>Hello World</title>

</head>

<body>

<h1>Hello World</h1>

<h2>Today is 2024-07-03</h2>

<h3>Version: 1.0</h3>

</body>

</html>

 

vagrant@docker:~/work/tomcat-webapp$ docker container stop myhello-web

vagrant@docker:~/work/tomcat-webapp$ docker container rm myhello-web

 

 

Docker in Docker

  Docker Container 내에서 Docker Host의 Container를 다루는 컨테이너 관리 기법



vagrant@docker:~/work$ mkdir ~/work/jenkins-control

vagrant@docker:~/work$ cd ~/work/jenkins-control



vagrant@docker:~/work/jenkins-control$ docker network create -d bridge --subnet 172.18.0.0/16 --gateway 172.18.255.254 jenkins

 

vagrant@docker:~/work/jenkins-control$ docker container run --name docker-dind --detach \

 --privileged --network jenkins --network-alias docker \

 --env DOCKER_TLS_CERTDIR=/certs \

 --volume jenkins-docker-certs:/certs/client \

 --volume jenkins-data:/var/jenkins_home \

 --volume docker:/var/lib/docker \

 --publish 2376:2376 \

 docker:dind --storage-driver overlay2



 

day4

 

Docker in Docker

  Docker Container 내에서 Docker Host의 Container를 다루는 컨테이너 관리 기법



vagrant@docker:~/work$ mkdir ~/work/jenkins-control

vagrant@docker:~/work$ cd ~/work/jenkins-control



vagrant@docker:~/work/jenkins-control$ docker network create -d bridge --subnet 172.18.0.0/16 --gateway 172.18.255.254 jenkins

 

vagrant@docker:~/work/jenkins-control$ docker container run --name docker-dind --detach \

 --privileged --network jenkins --network-alias docker \

 --env DOCKER_TLS_CERTDIR=/certs \

 --volume jenkins-docker-certs:/certs/client \

 --volume jenkins-data:/var/jenkins_home \

 --volume docker:/var/lib/docker \

 --publish 2376:2376 \

 docker:dind --storage-driver overlay2



vagrant@docker:~$ cd ~/work/jenkins-control/

vagrant@docker:~/work/jenkins-control$ vim Dockerfile

FROM jenkins/jenkins:lts-jdk17
USER root
RUN apt-get update && apt-get install -y lsb-release
RUN curl -fsSLo /usr/share/keyrings/docker-archive-keyring.asc \
  https://download.docker.com/linux/debian/gpg
RUN echo "deb [arch=$(dpkg --print-architecture) \
  signed-by=/usr/share/keyrings/docker-archive-keyring.asc] \
  https://download.docker.com/linux/debian \
  $(lsb_release -cs) stable" > /etc/apt/sources.list.d/docker.list
RUN apt-get update && apt-get install -y docker-ce-cli
USER jenkins
RUN jenkins-plugin-cli --plugins "docker-plugin docker-workflow"

 

vagrant@docker:~/work/jenkins-control$ docker image build -t jenkins-docker:lts-jdk17 .

docker container run --name jenkins-docker \

 --restart=always \

 --detach \

 --network jenkins \

 --env DOCKER_HOST=tcp://docker:2376 \

 --env DOCKER_CERT_PATH=/certs/client \

 --env DOCKER_TLS_VERIFY=1 \

 --publish 8080:8080 \

 --publish 50000:50000 \

--volume jenkins-data:/var/jenkins_home \

--volume jenkins-docker-certs:/certs/client:ro \

jenkins-docker:lts-jdk17

 

vagrant@docker:~/work/jenkins-control$ docker container exec jenkins-docker cat /var/jenkins_home/secrets/initialAdminPassword

 

(초기 패스워드 확인 후 Jenkins 웹 대시보드에 접속하여 설치 진행)

 

 



(위 화면에서 아래의 내용 입력)

 

Client Key

vagrant@docker:~/work/tomcat-webapp$ docker container exec jenkins-docker cat /certs/client/key.pem

 

Client Certificate

vagrant@docker:~/work/tomcat-webapp$ docker container exec jenkins-docker cat /certs/client/cert.pem

 

Server CA Certificate

vagrant@docker:~/work/tomcat-webapp$ docker container exec jenkins-docker cat /certs/client/ca.pem

 

(jenkins-docker container를 jenkins 네트워크에 연결

vagrant@docker:~/work/tomcat-webapp$ docker network disconnect bridge jenkins-docker
vagrant@docker:~/work/tomcat-webapp$ docker network connect jenkins jenkins-docker

 

 

 

[Jenkins Container에서 Test Pipeline 생성]

GitHub Repository : https://github.com/darinpope/jenkins-example-docker

 

 

 

vagrant@docker:~$ git config --global user.name "Hyoseok Cho"

vagrant@docker:~$ git config --global user.email "devops2341@gmail.com"

vagrant@docker:~$

vagrant@docker:~$ scp vagrant@192.168.56.101:~/.ssh/id_rsa-git-devops2341 ~/.ssh/

The authenticity of host '192.168.56.101 (192.168.56.101)' can't be established.

ED25519 key fingerprint is SHA256:Zwq/xLrXI8DC4s8X1MJo5MYwjEndTWoonzrCAektL14.

This key is not known by any other names

Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

Warning: Permanently added '192.168.56.101' (ED25519) to the list of known hosts.

vagrant@192.168.56.101's password:

id_rsa-git-devops2341                                 100% 2610     2.0MB/s   00:00

vagrant@docker:~$ scp vagrant@192.168.56.101:~/.ssh/id_rsa-git-devops2341.pub ~/.ssh/

vagrant@192.168.56.101's password:

id_rsa-git-devops2341.pub                             100%  574    47.0KB/s   00:00

vagrant@docker:~$

vagrant@docker:~$ scp vagrant@192.168.56.101:~/.ssh/config ~/.ssh/

vagrant@192.168.56.101's password:

config                                                100%   70    25.4KB/s   00:00

vagrant@docker:~$

vagrant@docker:~$ ssh -T git@github.com

The authenticity of host 'github.com (20.200.245.247)' can't be established.

ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU.

This key is not known by any other names

Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

Warning: Permanently added 'github.com' (ED25519) to the list of known hosts.

Hi devops2341! You've successfully authenticated, but GitHub does not provide shell access.

vagrant@docker:~$

vagrant@docker:~$ git clone git@github.com:devops2341/test-maven-java-spring-hello-webapp.git

Cloning into 'test-maven-java-spring-hello-webapp'...

remote: Enumerating objects: 33, done.

remote: Counting objects: 100% (33/33), done.

remote: Compressing objects: 100% (18/18), done.

remote: Total 33 (delta 1), reused 26 (delta 0), pack-reused 0

Receiving objects: 100% (33/33), 6.09 KiB | 389.00 KiB/s, done.

Resolving deltas: 100% (1/1), done.

vagrant@docker:~$

vagrant@docker:~$ ls

docker-host-filea.txt          source-maven-java-spring-hello-webapp  work

rocky9-1d-container-filea.txt  test-maven-java-spring-hello-webapp

vagrant@docker:~$ cd test-maven-java-spring-hello-webapp

vagrant@docker:~/test-maven-java-spring-hello-webapp$ ls

Jenkinsfile  README.md  pom.xml  src

vagrant@docker:~/test-maven-java-spring-hello-webapp$ git status

On branch main

Your branch is up to date with 'origin/main'.

 

nothing to commit, working tree clean

vagrant@docker:~/test-maven-java-spring-hello-webapp$ git remote -v

origin  git@github.com:devops2341/test-maven-java-spring-hello-webapp.git (fetch)

origin  git@github.com:devops2341/test-maven-java-spring-hello-webapp.git (push)

vagrant@docker:~/test-maven-java-spring-hello-webapp$ vim Jenkinsfile-docker

pipeline {
  agent none

  stages {
    stage('Checkout') {
      agent any
      steps {
        git branch: 'main', url: '<URL>'
      }
    }
    stage('Build') {
      agent {
        docker { image 'maven:3-openjdk-17' }
      }
      steps {
        sh 'mvn clean package'
      }
    }
    stage('Test') {
      agent {
        docker { image 'maven:3-openjdk-17' }
      }
      steps {
        sh 'mvn test'
      }
    }
    stage('Build Docker Image') {
      agent any
      steps {
        sh '<COMMAND>'
      }
    }
    stage('Tag Docker Image') {
      agent any
      steps {
        sh '<COMMAND>'
      }
    }
    stage('Publish Docker Image') {
      agent any
      steps {
        withDockerRegistry(credentialsId: 'docker-hub-token', url: 'https://index.docker.io/v1/') {
          sh '<COMMAND>'
        }
      }
    }
    stage('Run Docker Container') {
      agent {
        docker { image 'docker:dind' }
      }
      steps {
        sh 'docker -H tcp://<DOCKER_HOST_PRIVATE_IP>:2375 container run --detach --name <CONTAINER_NAME> -p 80:8080 <IMAGE>:$BUILD_NUMBER'
      }
    }
  }
}



 

vagrant@docker:~/test-maven-java-spring-hello-webapp$ git add .

vagrant@docker:~/test-maven-java-spring-hello-webapp$ git status

On branch main

Your branch is up to date with 'origin/main'.

 

Changes to be committed:

  (use "git restore --staged <file>..." to unstage)

        new file:   Dockerfile

        new file:   Jenkinsfile-docker

 

vagrant@docker:~/test-maven-java-spring-hello-webapp$ git commit -m "Add Dockerfile, Jenkinsfile-docker"

[main 3de0450] Add Dockerfile, Jenkinsfile-docker

 2 files changed, 68 insertions(+)

 create mode 100644 Dockerfile

 create mode 100644 Jenkinsfile-docker

vagrant@docker:~/test-maven-java-spring-hello-webapp$ git push

Enumerating objects: 5, done.

Counting objects: 100% (5/5), done.

Delta compression using up to 2 threads

Compressing objects: 100% (4/4), done.

Writing objects: 100% (4/4), 1.05 KiB | 359.00 KiB/s, done.

Total 4 (delta 0), reused 0 (delta 0), pack-reused 0

To github.com:devops2341/test-maven-java-spring-hello-webapp.git

   e5b6a1e..3de0450  main -> main



Docker Daemon 원격 접속 허용 구성

vagrant@docker:~/test-maven-java-spring-hello-webapp$ systemctl status docker.service

● docker.service - Docker Application Container Engine

     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enable>

     Active: active (running) since Thu 2024-07-04 00:13:25 UTC; 4h 40min ago

TriggeredBy: ● docker.socket

       Docs: https://docs.docker.com

   Main PID: 795 (dockerd)

      Tasks: 54

     Memory: 132.1M

        CPU: 43.017s

     CGroup: /system.slice/docker.service

             ├─ 795 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.s>

             ├─1815 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 2376 ->

             ├─1821 /usr/bin/docker-proxy -proto tcp -host-ip :: -host-port 2376 -conta>

             ├─4913 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 8080 ->

             ├─4919 /usr/bin/docker-proxy -proto tcp -host-ip :: -host-port 8080 -conta>

             ├─4926 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 50000 >

             └─4932 /usr/bin/docker-proxy -proto tcp -host-ip :: -host-port 50000 -cont>

vagrant@docker:~/test-maven-java-spring-hello-webapp$

vagrant@docker:~/test-maven-java-spring-hello-webapp$ ls -l /lib/systemd/system/docker.service

-rw-r--r-- 1 root root 1709 Jun 29 00:00 /lib/systemd/system/docker.service

vagrant@docker:~/test-maven-java-spring-hello-webapp$ cp /lib/systemd/system/docker.service /tmp

vagrant@docker:~/test-maven-java-spring-hello-webapp$ sudo vim /lib/systemd/system/docker.service


ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:2375 --containerd=/run/containerd/containerd.sock

 

vagrant@docker:~/test-maven-java-spring-hello-webapp$ sudo systemctl daemon-reload

vagrant@docker:~/test-maven-java-spring-hello-webapp$ sudo systemctl restart docker.service



 

vagrant@docker:~/test-maven-java-spring-hello-webapp$ docker container ls

CONTAINER ID   IMAGE                      COMMAND                  CREATED          STATUS          PORTS

               NAMES

1a9ccd50400b   devops2341/tomcat:2        "catalina.sh run"        26 seconds ago   Up 26 seconds   0.0.0.0:80->8080/tcp, :::80->8080/tcp

               webserver

 

vagrant@docker:~/test-maven-java-spring-hello-webapp$ curl http://192.168.56.103/hello-w

orld/



 

IaC(Infrastructure as Code)

 - 인프라를 코드로 정의하고 관리하는 기술

 - IaC 도구에 따라 인프라 생성, 구성 자동화 등을 수행할 수 있음.

 - 다수의 시스템을 효율적으로 관리할 수 있음.

 

IaC 장점

  - 비용 절감

      단순 인프라 관리 작업에 드는 비용, 시간 등을 줄여 다른 곳에 활용할 수 있음.

  - 빠른 작업 속도

  - 안정성

  - 코드화 및 버전 관리

  - 재사용성

 

IaC 도구 및 특징

 - 구성 관리 도구 : Ansible, Chef, Puppet, SaltStack 등

 - 인프라 배포 도구 : AWS CloudFormation, OpenStack Heat, Terraform 등

 

구성 관리 도구(Configuration Management Tool)

  - 인프라가 이미 존재하는 상태에서 해당 인프라의 설정 변경을 수행할 수 있는 IaC 도구

  - 소프트웨어 패키지 설치, 작업 실행, 서비스/애플리케이션 구성, 운영체제의 명령어 실행, 설정 변경 등

 

인프라 배포 도구(Infrastructure Provisioning Tool)

  - 인프라스트럭처를 생성, 변경, 삭제할 수 있는 IaC 도구

  - 네트워크 생성, 가상머신 생성 등

 

가변 인프라(Mutable Infrastructure)

  - 변경이 가능한 인프라를 의미하는 것으로 물리서버, 가상머신 등이 해당됨.

 

불변 인프라(Immutable Infrastructure)

   - 변하지 않는 인프라를 의미하는 것으로 가상머신 이미지, 컨테이너 이미지 등이 해당됨.



Ansible

  - IT 인프라의 구성 관리를 자동화 할 수 있는 IaC 도구

  - 마스터와 에이전트가 없음

  - 파이썬 기반으로 개발됨

  - Ansible은 다양한 운영체제를 지원함

 

Ansible 주요 용어

제어 노드(Control Node)

  - Ansible이 설치된 호스트

  - Ansible의 제어 노드는 Linux를 사용함. (Windows 시스템은 사용 불가)

 

관리 노드(Managed Node)

  - Ansible 제어 노드에 의해 관리되는 노드

 

인벤토리(Inventory)

  - 관리 노드의 목록으로 노드의 호스트네임, IP 주소 등의 정보를 포함 함.

  - 관리 노드를 그룹으로 묶어서 관리 할 수 있음.

 

플러그인(Plugin)

 - Ansible의 기능 확장을 위한 프로그램

 

모듈(Module)

  - Ansible에서 작업을 정의하기 위해 사용되며 Python 기반으로 작성됨

 

작업(Task)

 - Ansible의 기본 작업 실행 단위

 - Ansible 모듈을 사용하여 작업을 정의함.

 

Ad-Hoc 명령어

  - Ansible 작업을 명령어를 작성하여 실행하는 명령어

  - 1회성으로 작업을 실행하고자 하는 경우 주로 사용됨

 

플레이(Play)

 - 1개 이상의 작업(Task)가 모인 Ansible의 실행단위

 

플레이북(Playbook)

 - Ansible 플레이가 1개 이상 모여있는 파일

  - 플레이북은 YAML 언어로 작성됨.



Ansible Architecture



 

Ansible 설치

sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt-get install ansible



vagrant@docker:~$ mkdir ~/work/ansible-web

vagrant@docker:~$ cd ~/work/ansible-web/

vagrant@docker:~/work/ansible-web$ ansible --version

vagrant@docker:~/work/ansible-web$ vim ansible.cfg

[defaults]
inventory=inventory/inventory
remote_user=vagrant

 

vagrant@docker:~/work/ansible-web$ vim ansible.cfg

vagrant@docker:~/work/ansible-web$ mkdir inventory

vagrant@docker:~/work/ansible-web$ vim inventory/inventory

[webservers]
ansible         ansible_host=192.168.56.104



vagrant@docker:~/work/ansible-web$ ansible all -m ping

The authenticity of host '192.168.56.104 (192.168.56.104)' can't be established.

ED25519 key fingerprint is SHA256:oNMmdqSIVeMkZP7E+gVI9BafUrq9Svly+/L7BnmNYYY.

This key is not known by any other names

Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

ansible | UNREACHABLE! => {

    "changed": false,

    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.56.104' (ED25519) to the list of known hosts.\r\nvagrant@192.168.56.104: Permission denied (publickey,password).",

    "unreachable": true

}

vagrant@docker:~/work/ansible-web$ ansible all -m ping

ansible | UNREACHABLE! => {

    "changed": false,

    "msg": "Failed to connect to the host via ssh: vagrant@192.168.56.104: Permission denied (publickey,password).",

    "unreachable": true

}

vagrant@docker:~/work/ansible-web$

vagrant@docker:~/work/ansible-web$ ansible all -m ping --ask-pass

SSH password:

ansible | SUCCESS => {

    "ansible_facts": {

        "discovered_interpreter_python": "/usr/bin/python3"

    },

    "changed": false,

    "ping": "pong"

}

 

SSH Key Pair 생성

vagrant@docker:~/work/ansible-web$ ssh-keygen

Generating public/private rsa key pair.

Enter file in which to save the key (/home/vagrant/.ssh/id_rsa):

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/vagrant/.ssh/id_rsa

Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub

The key fingerprint is:

SHA256:8tD9COq1FUGfMj4nYdSdroZqiwZuNwKOGf17edtdueI vagrant@docker

The key's randomart image is:

+---[RSA 3072]----+

|          o. . . |

|         o ...o  |

|          * o.   |

|       . + =  .  |

| .    o S *...   |

|. o .  = ..Bo  . |

| = + ...o.o.. o  |

|o . =.*o++ ... . |

|   ..*o++o..E..  |

+----[SHA256]-----+

 

vagrant@docker:~/work/ansible-web$ ssh-copy-id vagrant@192.168.56.104

vagrant@docker:~/work/ansible-web$ ssh vagrant@192.168.56.104

vagrant@ansible:~$ exit

 

vagrant@docker:~/work/ansible-web$ ansible all -m ping --ask-pass

SSH password:

ansible | SUCCESS => {

    "ansible_facts": {

        "discovered_interpreter_python": "/usr/bin/python3"

    },

    "changed": false,

    "ping": "pong"

}

vagrant@docker:~/work/ansible-web$ ansible all -m ping

ansible | SUCCESS => {

    "ansible_facts": {

        "discovered_interpreter_python": "/usr/bin/python3"

    },

    "changed": false,

    "ping": "pong"

}

 

Ansible에서 작업을 실행하는 방법

  1. Ad-Hoc 명령어실행 방식

     $ ansible  HOST_PATTERN  -i INVENTORY  -m MODULE  [-a ARGUMENT]

 

  2. Playbook 실행 방식

     $ vim PLAYBOOK.yaml

     $ ansible-playbook -i INVENTORY   PLAYBOOK.yaml



Ad-Hoc 명령어 형태로 Ansible 작업 실행

vagrant@docker:~/work/ansible-web$ ansible webservers -m command -a 'hostname'

ansible | CHANGED | rc=0 >>

ansible

 

vagrant@docker:~/work/ansible-web$ ansible webservers -m command -a 'cat /etc/issue'

ansible | CHANGED | rc=0 >>

Ubuntu 22.04.4 LTS \n \l

 

 

YAML(YAML Ain’t Markup Language)

  - 데이터를 표현하기 위한 언어

  - Key-Value 형식으로 데이터를 표현, JSON 보다 간결한 문법을 추구함

  - https://yaml.org/

  - YAML은 들여쓰기에 민감하며 하나의 들여쓰기 레벨에 공백문자 2칸, 4칸, 8칸 등을 사용함.

     (단, 하나의 YAML 문서에서 들여쓰기 레벨에 사용하는 공백문자의 개수를 통일해야함.)

   - YAML 문서의 시작 "---" 행으로 표시하고 YAML 문서의 끝은 "..." 행으로 표시함

 

YAML 기본 문법

 

주석 : #

# This is a comment line

 

데이터 표현

KEY: VALUE



KEY0: VALUE0

KEY1: 
  KEY2: VALUE2

KEY11:
  KEY12:
    KEY13: VALUE13



기본 자료형(Data Types)

int_data: 1
string_data: "string data value"
boolean_data1: true
boolean_data2: false
boolean_data3: yes
boolean_data4: no

 

Dictionary(Hash)

key0:
  key01: value01
  key02: value02

 

key0: {
  key01: value01
  key02: value02
}



List

list_data:
  - value1
  - value2
  - value3

 

list_data: [value1, value2, value3]

 

list_data: [
  value1, value2, value3
]



Line1
Line2
Line3

 

Multi Line Data

(1) Literal Block Scalar ( : | )

      - 문자열 데이터에서 개행 문자를 포함하여 문자열 값을 저장

string_literal_block_data: |
  Line1
  Line2
  Line3

  string_literal_block_data: "Line1\nLine2\nLine3"

 

(2) Folded Block Scalar ( : > )

      - 문자열 데이터에서 개행 문자를 공백 문자로 치환하여 문자열 값을 저장

string_folded_block_data: > 
  Line1
  Line2
  Line3

  String_folded_block_data: "Line1 Line2 Line3"

 

 

YAML 문서의 기본 틀 예시

--- # This is a comment
document_name: system_log_data
document_body:
  data1:
    data_id: 1
    data_type: temp
    data_content: "Sample Data log"
    data_tags:
      - operation
      - alert
      - networking
… # This is a comment

 

Ansible Playbook

 

YAML 문서 작성을 위한 vim editor 설정

 

$ vim ~/.vimrc

syntax on
autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab autoindent



Ansible Playbook 작성 기본 틀

---
- name: ANSIBLE_PLAY_NAME
  hosts: HOST_PATTERN
  tasks:
    - name: TASK1_NAME
      MODULE:
        field1: value1
        field2: value2
    - name: TASK2_NAME
      MODULE:
        field1: value1
        field2: value2

 

---
- name: ANSIBLE_PLAY_NAME
  hosts: HOST_PATTERN
  tasks:
  - name: TASK1_NAME
    MODULE:
      field1: value1
      field2: value2
  - name: TASK2_NAME
    MODULE:
      field1: value1
      field2: value2



 

첫 Ansible Playbook 작성 실습

$ vim playbook-first.yaml

---
- name: My First Ansible Playbook
  hosts: all
  tasks:
    - name: "task1 - Hello Ansible"
      debug:
        msg: "Hello Ansible"
    - name: "task2 - Print a Message"
      debug:
        msg: "Ansible is running..."
...



vagrant@docker:~/work/ansible-web$ ansible-playbook -i inventory/inventory playbook-first.yaml --syntax-check

 

playbook: playbook-first.yaml

(Playbook 문법 오류 검사)

 

vagrant@docker:~/work/ansible-web$ ansible-playbook -i inventory/inventory playbook-first.yaml

 

PLAY [My First Ansible Playbook] *******************************************************

 

TASK [Gathering Facts] *****************************************************************

ok: [ansible]

 

TASK [task1 - Hello Ansible] ***********************************************************

ok: [ansible] => {

    "msg": "Hello Ansible"

}

 

TASK [task2 - Print a message] *********************************************************

ok: [ansible] => {

    "msg": "Ansible is running..."

}

 

PLAY RECAP *****************************************************************************

ansible                    : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0



 

$ vim playbook-install-apache2.yaml

- name: Install Apache2
  hosts: webservers

  tasks:
  - name: Install Packages
    apt: 
      name: apache2
      state: present
  - name: Start Services
    service: 
      name: apache2
      state: started
      enabled: true

 

vagrant@docker:~/work/ansible-web$ ansible-playbook playbook-install-apache2.yaml --become

 

PLAY [Install Apache2] *****************************************************************

 

TASK [Gathering Facts] *****************************************************************

ok: [ansible]

 

TASK [Install Packages] ****************************************************************

changed: [ansible]

 

TASK [Start Services] ******************************************************************

ok: [ansible]

 

PLAY RECAP *****************************************************************************

ansible                    : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

 

Ansible Playbook Docker 실습

 

vagrant@docker:~/work/ansible-web-container$ sudo apt-get install python3-docker

 

vagrant@docker:~/work/ansible-web$ mkdir ~/work/ansible-web-container

vagrant@docker:~/work/ansible-web$ cd ~/work/ansible-web-container/

vagrant@docker:~/work/ansible-web-container$ vim playbook-deploy-httpd-container.yaml

- name: Deploy Httpd Container
  hosts: localhost
  connection: local

  tasks:
  - name: Create & Start Container
    docker_container:
      name: myapache
      image: httpd:2.4
      state: started

 

vagrant@docker:~/work/ansible-web-container$ ansible-playbook playbook-deploy-httpd-container.yaml

 

[WARNING]: provided hosts list is empty, only localhost is available. Note that the

implicit localhost does not match 'all'

 

PLAY [Deploy Httpd Container] **********************************************************

 

TASK [Gathering Facts] *****************************************************************

ok: [localhost]

 

TASK [Create & Start Container] ********************************************************

changed: [localhost]

 

PLAY RECAP *****************************************************************************

localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0



vagrant@docker:~/work/ansible-web-container$ docker container ls

CONTAINER ID   IMAGE                      COMMAND                  CREATED          STATUS          PORTS

               NAMES

80d4b3df59cf   httpd:2.4                  "httpd-foreground"       26 seconds ago   Up 24 seconds   80/tcp

               myapache

vagrant@docker:~/work/ansible-web-container$ docker container inspect myapache

 

vagrant@docker:~/work/ansible-web-container$ curl http://172.17.0.3/

<html><body><h1>It works!</h1></body></html>



 

1. kubeadm을 사용한 Kubernetes Cluster 수동 구축

 

2. kubespray를 사용한 Kubernetes Cluster 자동 구축

    kubespray

      Ansible 기반으로 Kubernetes Cluster를 구축하는 도구

 

 

kubespray를 통한 Kubernetes Cluster 구축

 

(kube-control1에서만)

ssh vagrant@localhost

ssh vagrant@127.0.0.1

ssh vagrant@192.168.56.11

ssh vagrant@192.168.56.21

ssh vagrant@192.168.56.22

ssh vagrant@192.168.56.23

ssh vagrant@kube-control1

ssh vagrant@kube-node1

ssh vagrant@kube-node2

ssh vagrant@kube-node3

 

SSH Key Pair 생성 및 공개키 배포(SSH 키 기반 인증 설정)

ssh-keygen

ssh-copy-id vagrant@localhost

ssh-copy-id vagrant@192.168.56.11

ssh-copy-id vagrant@192.168.56.21

ssh-copy-id vagrant@192.168.56.22

ssh-copy-id vagrant@192.168.56.23



cd ~

git clone -b v2.25.0 https://github.com/kubernetes-sigs/kubespray

cd ~/kubespray

 

sudo apt-get update

sudo apt-get install python3 python3-pip -y

 

sudo pip3 install -r requirements.txt

 

cp -rfp inventory/sample/ inventory/mycluster/

 

vim inventory/mycluster/inventory.ini



[all]
kube-control1  ansible_host=192.168.56.11  ip=192.168.56.11  ansible_connection=local
kube-node1  ansible_host=192.168.56.21  ip=192.168.56.21
kube-node2  ansible_host=192.168.56.22  ip=192.168.56.22
kube-node3  ansible_host=192.168.56.23  ip=192.168.56.23

[all:vars]
ansible_python_interpreter=/usr/bin/python3


[kube_control_plane]
kube-control1


[etcd]
kube-control1


[kube_node]
kube-node1
kube-node2
kube-node3

[calico_rr]

[k8s_cluster:children]
kube_control_plane
kube_node
calico_rr



vim inventory/mycluster/group_vars/k8s_cluster/addons.yml

16 metrics_server_enabled: true
100 ingress_nginx_enabled: true
172 metallb_enabled: true
179 metallb_config:
196   address_pools:
197     primary:
198       ip_range:
199         - 192.168.56.200-192.168.56.210
200       auto_assign: true
209   layer2:
210     - primary



vim inventory/mycluster/group_vars/k8s_cluster/k8s-cluster.yml

129 kube_proxy_strict_arp: true
229 container_manager: docker

 

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

ansible all -i inventory/mycluster/inventory.ini -m apt -a "update_cache=yes" --become

 

ansible-playbook -i inventory/mycluster/inventory.ini cluster.yml --become

 

Kubernetes Cluster 관리를 위한 인증 정보 추가

mkdir -p $HOME/.kube

sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config

sudo chown $(id -u):$(id -g) $HOME/.kube/config



$ kubectl get nodes

NAME            STATUS   ROLES           AGE   VERSION

kube-control1   Ready    control-plane   25m   v1.29.5

kube-node1      Ready    <none>          24m   v1.29.5

kube-node2      Ready    <none>          24m   v1.29.5

kube-node3      Ready    <none>          24m   v1.29.5



YAML 파일 정의를 위한 vim Editor 설정

 

$ vim ~/.vimrc

syntax on
autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab autoindent



Kubernetes

   구글에서 개발하여 CNCF에서 관리하는 오픈소스 컨테이너 오케스트레이션 도구

 

Kubernetes의 주요 기능

 - Container Platform

 - Microservice Platform

 - 이식성 있는 Cloud Platform 

 

Kubernetes에서 제공하지 않는 기능

 - CI/CD 파이프라인 기능 미제공

 - 애플리케이션 레벨의 서비스 미제공

 - 로깅, 모니터링, 경고 솔루션 미제공

 

Kubernetes Architecture

 - Kubernetes Cluster 구성요소 : Control Plane, Nodes, Add-on

https://kubernetes.io/ko/docs/concepts/overview/components/

 

Control Plane : Kubernetes Cluster를 제어하는 서버

Node : Container를 실행하기 위한 Computing Resource를 제공하는 머신







댓글