[Linux] CentOS Stream 9 환경 구축 5 - Podman Jenkins 설치 / Jenkins 에 Github 연동

EUN JY·2024년 4월 16일
1

Linux

목록 보기
7/9
post-thumbnail

15. Jenkins

  • 5. Podman 에 이어서 Podman 작업
  • Docker Hub 와 Podman 은 잘 호환된다고 함 > Docker Hub 의 Jenkins 이미지를 사용

15-1. Podman 설치

  • 이미지 다운로드 (podman pull)
[root@localhost home]# podman pull jenkins/jenkins:lts
✔ docker.io/jenkins/jenkins:lts
Trying to pull docker.io/jenkins/jenkins:lts...
Getting image source signatures
Copying blob 8d7cd7345072 done   |
Copying blob 71215d55680c done   |
Copying blob c8dac3aae91a done   |
Copying blob 1830bd5f9b45 done   |
Copying blob 35af8fb55c2f done   |
Copying blob 234e1154c2a1 done   |
Copying blob a89f7edcbd51 done   |
Copying blob 83597e279c9f done   |
Copying blob 6c39e3e60898 done   |
Copying blob 29150353c9ba done   |
Copying blob 33fe415a6139 done   |
Copying blob c5d8e31128fd done   |
Copying config 2371da2306 done   |
Writing manifest to image destination
2371da23064a2c39b40101d0851ef5c51adff752a013949cc129eb616228d5cd
  • 이미지 태그 설정 (podman tag)
[root@localhost home]# podman tag jenkins/jenkins:lts projyj/jenkins:2.204.2
[root@localhost home]# podman tag jenkins/jenkins:lts docker.io/projyj/jenkins:2.204.2
[root@localhost home]# podman images
REPOSITORY                 TAG         IMAGE ID      CREATED     SIZE
docker.io/projyj/jenkins    2.204.2     2371da23064a  8 days ago  471 MB
localhost/projyj/jenkins    2.204.2     2371da23064a  8 days ago  471 MB
docker.io/jenkins/jenkins  lts         2371da23064a  8 days ago  471 MB

🔶 이미지 확인

  • 이미지 검색 (podman search)
[root@localhost home]# podman search --tls-verify jenkins
NAME                                                                 DESCRIPTION
registry.access.redhat.com/openshift3/jenkins-2-rhel7                This image provides a Jenkins server, primar...
registry.access.redhat.com/openshift3/jenkins-1-rhel7                Jenkins image which can be used to set up a...
############ (중략) ############
docker.io/rancher/jenkins-jnlp-slave
docker.io/jenkins/core-pr-tester                                     Docker image for testing pull-requests sent...
docker.io/jenkins/jnlp-agent-alpine
docker.io/rancher/jenkins-slave                                      Jenkins Build Slave
docker.io/jenkins/jnlp-agent-coresdk
docker.io/jenkins/evergreen                                          An automatically self-updating Jenkins distr...
  • 이미지 목록 출력 (podman images)
[root@localhost home]# podman images
REPOSITORY                 TAG         IMAGE ID      CREATED     SIZE
docker.io/jenkins/jenkins  lts         2371da23064a  8 days ago  471 MB
  • 이미지 세부 정보 확인 (podman inspect)
[root@localhost home]# podman inspect jenkins/jenkins:lts
[
     {
          "Id": "2371da23064a2c39b40101d0851ef5c51adff752a013949cc129eb616228d5cd",
          "Digest": "sha256:1fd79ceb68ce883fb86db70bdbf7f9eaa8b25e580aafe7a240235240396e3916",
          "RepoTags": [
               "docker.io/jenkins/jenkins:lts"
          ],
          "RepoDigests": [
               "docker.io/jenkins/jenkins@sha256:1fd79ceb68ce883fb86db70bdbf7f9eaa8b25e580aafe7a240235240396e3916",
               "docker.io/jenkins/jenkins@sha256:55ca11703b6b90031030be36c9fe9f064b38a4bd2bd253100d0246efd0054a8a"
          ],
          "Parent": "",
          "Comment": "",
          "Created": "2024-03-20T16:37:24.770285139Z",
          "Config": {
               "User": "jenkins",
               "ExposedPorts": {
                    "50000/tcp": {},
                    "8080/tcp": {}
               },
               "Env": [
                    "PATH=/opt/java/openjdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                    "LANG=C.UTF-8",
                    "JENKINS_HOME=/var/jenkins_home",
                    "JENKINS_SLAVE_AGENT_PORT=50000",
                    "REF=/usr/share/jenkins/ref",
                    "JENKINS_VERSION=2.440.2",
                    "JENKINS_UC=https://updates.jenkins.io",
                    "JENKINS_UC_EXPERIMENTAL=https://updates.jenkins.io/experimental",
                    "JENKINS_INCREMENTALS_REPO_MIRROR=https://repo.jenkins-ci.org/incrementals",
                    "COPY_REFERENCE_FILE_LOG=/var/jenkins_home/copy_reference_file.log",
                    "JAVA_HOME=/opt/java/openjdk"
               ],
               "Entrypoint": [
                    "/usr/bin/tini",
                    "--",
                    "/usr/local/bin/jenkins.sh"
               ],
               "Volumes": {
                    "/var/jenkins_home": {}
               },
               "Labels": {
                    "org.opencontainers.image.description": "The Jenkins Continuous Integration and Delivery server",
                    "org.opencontainers.image.licenses": "MIT",
                    "org.opencontainers.image.revision": "8b3d5836ae21390ab374b154b94b7ac33d615243",
                    "org.opencontainers.image.source": "https://github.com/jenkinsci/docker",
                    "org.opencontainers.image.title": "Official Jenkins Docker image",
                    "org.opencontainers.image.url": "https://www.jenkins.io/",
                    "org.opencontainers.image.vendor": "Jenkins project",
                    "org.opencontainers.image.version": "2.440.2"
               }
          },
          "Version": "",
          "Author": "",
          "Architecture": "amd64",
          "Os": "linux",
          "Size": 471191196,
          "VirtualSize": 471191196,
############ (중략) ############
          "Labels": {
               "org.opencontainers.image.description": "The Jenkins Continuous Integration and Delivery server",
               "org.opencontainers.image.licenses": "MIT",
               "org.opencontainers.image.revision": "8b3d5836ae21390ab374b154b94b7ac33d615243",
               "org.opencontainers.image.source": "https://github.com/jenkinsci/docker",
               "org.opencontainers.image.title": "Official Jenkins Docker image",
               "org.opencontainers.image.url": "https://www.jenkins.io/",
               "org.opencontainers.image.vendor": "Jenkins project",
               "org.opencontainers.image.version": "2.440.2"
          },
          "Annotations": {},
          "ManifestType": "application/vnd.oci.image.manifest.v1+json",
          "User": "jenkins",
          "History": [
############ (중략) ############
          ],
          "NamesHistory": [
               "docker.io/jenkins/jenkins:lts"
          ]
     }
]

🔶 이미지 삭제

  • 이미지 삭제 (podman rmi)
$ podman rmi localhost/projyj/jenkins:2.204.2
Untagged: localhost/projyj/jenkins:2.204.2

$ podman rmi docker.io/projyj/jenkins:2.204.2
Untagged: docker.io/projyj/jenkins:2.204.2

15-2. Podman 컨테이너 생성 및 구동

  • 컨테이너 생성 및 백그라운드 실행 (podman run)
[root@localhost home]# podman run --name jenkins -d -p 8080:8080 -p 50000:50000 jenkins/jenkins:lts
e5c906face7a150af68d9672d019e4ca60775a981f21bb516c5ff34d097652b7
  • 컨테이너 목록 확인 (podman ps)
    • 컨테이너 실행 확인과 사용 가능한 모든 컨테이너 출력
[root@localhost home]# podman ps -a
CONTAINER ID  IMAGE                          COMMAND     CREATED         STATUS         PORTS                                             NAMES
d7020c058f90  docker.io/jenkins/jenkins:lts              42 seconds ago  Up 42 seconds  0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp  jenkins
  • 컨테이너 구동 확인 (podman logs)
[root@localhost home]# podman logs -f jenkins
Running from: /usr/share/jenkins/jenkins.war
webroot: /var/jenkins_home/war
2024-03-29 00:34:08.819+0000 [id=1]     INFO    winstone.Logger#logInternal: Beginning extraction from war file
2024-03-29 00:34:09.458+0000 [id=1]     WARNING o.e.j.s.handler.ContextHandler#setContextPath: Empty contextPath
2024-03-29 00:34:09.494+0000 [id=1]     INFO    org.eclipse.jetty.server.Server#doStart: jetty-10.0.20; built: 2024-01-29T20:46:45.278Z; git: 3a745c71c23682146f262b99f4ddc4c1bc41630c; jvm 17.0.10+7
2024-03-29 00:34:09.640+0000 [id=1]     INFO    o.e.j.w.StandardDescriptorProcessor#visitServlet: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet
2024-03-29 00:34:09.670+0000 [id=1]     INFO    o.e.j.s.s.DefaultSessionIdManager#doStart: Session workerName=node0
2024-03-29 00:34:09.940+0000 [id=1]     INFO    hudson.WebAppMain#contextInitialized: Jenkins home directory: /var/jenkins_home found at: EnvVars.masterEnvVars.get("JENKINS_HOME")
2024-03-29 00:34:10.007+0000 [id=1]     INFO    o.e.j.s.handler.ContextHandler#doStart: Started w.@332820f4{Jenkins v2.440.2,/,file:///var/jenkins_home/war/,AVAILABLE}{/var/jenkins_home/war}
2024-03-29 00:34:10.014+0000 [id=1]     INFO    o.e.j.server.AbstractConnector#doStart: Started ServerConnector@68fa0ba8{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
2024-03-29 00:34:10.019+0000 [id=1]     INFO    org.eclipse.jetty.server.Server#doStart: Started Server@2a7686a7{STARTING}[10.0.20,sto=0] @1502ms
2024-03-29 00:34:10.020+0000 [id=27]    INFO    winstone.Logger#logInternal: Winstone Servlet Engine running: controlPort=disabled
2024-03-29 00:34:10.150+0000 [id=35]    INFO    jenkins.InitReactorRunner$1#onAttained: Started initialization
2024-03-29 00:34:10.162+0000 [id=56]    INFO    jenkins.InitReactorRunner$1#onAttained: Listed all plugins
2024-03-29 00:34:10.642+0000 [id=56]    INFO    jenkins.InitReactorRunner$1#onAttained: Prepared all plugins
2024-03-29 00:34:10.645+0000 [id=56]    INFO    jenkins.InitReactorRunner$1#onAttained: Started all plugins
2024-03-29 00:34:10.649+0000 [id=52]    INFO    jenkins.InitReactorRunner$1#onAttained: Augmented all extensions
2024-03-29 00:34:10.758+0000 [id=41]    INFO    jenkins.InitReactorRunner$1#onAttained: System config loaded
2024-03-29 00:34:10.758+0000 [id=40]    INFO    jenkins.InitReactorRunner$1#onAttained: System config adapted
2024-03-29 00:34:10.758+0000 [id=51]    INFO    jenkins.InitReactorRunner$1#onAttained: Loaded all jobs
2024-03-29 00:34:10.759+0000 [id=51]    INFO    jenkins.InitReactorRunner$1#onAttained: Configuration for all jobs updated
2024-03-29 00:34:10.769+0000 [id=69]    INFO    hudson.util.Retrier#start: Attempt #1 to do the action check updates server
2024-03-29 00:34:11.025+0000 [id=48]    INFO    jenkins.install.SetupWizard#init:

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

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

070b01f500e94ca1b1a3c3fa01b0c911

This may also be found at: /var/jenkins_home/secrets/initialAdminPassword

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

2024-03-29 00:34:25.553+0000 [id=55]    INFO    jenkins.InitReactorRunner$1#onAttained: Completed initialization
2024-03-29 00:34:25.564+0000 [id=26]    INFO    hudson.lifecycle.Lifecycle#onReady: Jenkins is fully up and running
2024-03-29 00:34:26.480+0000 [id=69]    INFO    h.m.DownloadService$Downloadable#load: Obtained the updated data file for hudson.tasks.Maven.MavenInstaller
2024-03-29 00:34:26.481+0000 [id=69]    INFO    hudson.util.Retrier#start: Performed the action check updates server successfully at the attempt #1

🔶 Podman 컨테이너 구동/중지/재시작

  • 컨테이너 구동 (podman start) / 중지 (podman stop) / 재시작 (podman restart)
# 컨테이너 중지 (podman stop)
[root@localhost home]# podman stop jenkins
jenkins
[root@localhost home]# podman ps -a
CONTAINER ID  IMAGE                          COMMAND     CREATED        STATUS                       PORTS                                             NAMES
d7020c058f90  docker.io/jenkins/jenkins:lts              7 minutes ago  Exited (143) 16 seconds ago  0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp  jenkins

# 컨테이너 구동 (podman start)
[root@localhost home]# podman start jenkins
jenkins
[root@localhost home]# podman ps -a
CONTAINER ID  IMAGE                          COMMAND     CREATED        STATUS         PORTS                                             NAMES
d7020c058f90  docker.io/jenkins/jenkins:lts              8 minutes ago  Up 11 seconds  0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp  jenkins

# 컨테이너 재시작 (podman restart)
[root@localhost home]# podman restart jenkins
jenkins
[root@localhost home]# podman ps -a
CONTAINER ID  IMAGE                          COMMAND     CREATED        STATUS       PORTS                                             NAMES
d7020c058f90  docker.io/jenkins/jenkins:lts              8 minutes ago  Up 1 second  0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp  jenkins
  • 컨테이너 삭제 (podman rm)
[root@localhost home]# podman rm jenkins

🔶 Podman 컨테이너 사용법

  • 컨테이너의 프로세스 실행 및 접속 (podman exec)
[root@localhost home]# podman exec -it jenkins /bin/bash
jenkins@d7020c058f90:/$ whoami
jenkins
jenkins@d7020c058f90:/$ cd /var/jenkins_home/secrets
jenkins@d7020c058f90:~/secrets$ cat initialAdminPassword
070b01f500e94ca1b1a3c3fa01b0c911
  • 컨테이너의 프로세스 확인 (podman top)
[root@localhost home]# podman top jenkins
USER        PID         PPID        %CPU        ELAPSED          TTY         TIME        COMMAND
jenkins     1           0           0.000       4m19.290914938s  ?           0s          /usr/bin/tini -- /usr/local/bin/jenkins.sh
jenkins     2           1           8.485       4m19.29096756s   ?           22s         java -Duser.home=/var/jenkins_home -Djenkins.model.Jenkins.slaveAgentPort=50000 -Dhudson.lifecycle=hudson.lifecycle.ExitLifecycle -jar /usr/share/jenkins/jenkins.war
  • 컨테이너의 포트 상태 확인 (podman port)
[root@localhost home]# podman port jenkins
8080/tcp -> 0.0.0.0:8080
50000/tcp -> 0.0.0.0:50000

15-4. Jenkins 접속

  • 참고 : Jenkins 설치 가이드
  • 15-2. Podman 컨테이너 생성 및 구동 에서 확인된 비밀번호 복사 : 070b01f500e94ca1b1a3c3fa01b0c911
  • http://192.168.1.111:8080 로 접속하여 구동된 것 확인
  • 비밀번호 입력 > Continue
  • Customize Jenkins > Install suggested plugins
  • Create First Admin User > 계정 정보 입력
    • 계정명 : projyj
    • 암호 : password$$
    • 이름 : projyj
    • 이메일 주소 : projyj@email.addr.com
  • Jenkins URL : Jenkins Web UI에 접근하기 위한 Jenkins URL 설정 (기본으로 유지함)
  • Jenkins is ready! > Start using Jenkins

16. Jenkins 에 Github 연동

16-1. Github Token 발급

  • Github > Settings(https://github.com/settings/profile) > Developer Settings > Personal access tokens > Tokens (classic)
  • Generate new token (classic) 클릭
    • Note : CentOS 9 ProjYj
    • Expiration : No expiration (The token will never expire!)
    • Select scopes : repo, admin:org, admin:repo_hook 선택

  • Generate token : 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 (발급 받은 token 은 다시 볼 수 없으므로 따로 저장)

16-2. Jenkins Credentials 생성

  • Dashboard > Jenkins 관리 > Credentials
  • Stores scoped to Jenkins > System 의 Domains (global) 선택
  • Add Credentials
    • Kind : Username with password
    • Scope : Global (Jenkins, nodes, items, all child items, etc)
    • Username : projyj (GitHub 아이디)
    • Treat username as secret 체크 해제
    • Password : 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 (위에서 발급 받은 GitHub token)
    • ID : github_token (Credentials 이름)
    • Description : github_token (Optional)

16-3. Jenkinsfile 작성

  • 빌드할 GitHub Repository 경로 안에 Jenkinsfile 이 존재해야 함
  • 2024.04.12 > Pipeline 으로 구성할 때만 필요
pipeline {
    agent any
    
    stages {
        
        stage('github-clone') {
            steps {
                git branch: 'ProjYj2024main', credentialsId: 'github_token', url: 'https://github.com/projyj/ProjYj2024.git'
            }
        }
        
   		// stage...
   	}
}

16-4. Jenkins Freestyle project 설정

  • Dashboard > 새로운 Item > Freestyle project 선택
  • item name : ProjYj2024
  • 2024.04.12 > Pipeline 으로 구성했었으나, 빌드 후 조치 사용을 위해 Freestyle project 로 변경하였음 (각 타입별 Configure 는 하단 참고)
  • 자동 실행 등 빌드 후 작업은 21. Jenkins 빌드 및 실행 에서 이어서 확인

🔶 Freestyle project Configure

  • 참고 : Jenkins 새로운 Item 생성 및 설정 / Jenkins와 github 연동하기
  • General > GitHub project 선택
    • Project url : https://github.com/projyj/ (GitHub Repository 경로)
  • 소스 코드 관리 > Git
    • Repository URL : https://github.com/projyj/ProjYj2024.git (GitHub Repository 경로.git)
    • Credentials : (위에서 생성한 Credentials)
    • Branch Specifier : */ProjYj2024main (trigger Branch)
  • 빌드 유발(Build Triggers) > GitHub hook trigger for GITScm polling 선택
    • push에 의한 hook 이벤트가 발생할 경우 저장소를 polling해서 젠킨스의 자동 빌드를 유발
    • GitHub 의 hook trigger 를 받으면 빌드 하겠다는 의미
  • 빌드 환경 > Provide Node & npm bin/ folder to PATH 선택
    • NodeJS Installation : NodeJS 20.9.0
    • npmrc file : - use system default -
    • Cache location : Default (~/.npm or %APP_DATA%\npm-cache)
  • 저장

🔶 Pipeline Configure

  • General > GitHub project 선택
    • Project url : https://github.com/projyj/ (GitHub Repository 경로)
  • Build Triggers > GitHub hook trigger for GITScm polling 선택
  • Pipeline > Definition > Pipeline script from SCM 선택
    • SCM : Git 선택
    • Repository URL : https://github.com/projyj/ProjYj2024.git (GitHub Repository 경로.git)
    • Credentials : (위에서 생성한 Credentials)
    • Branch Specifier : ProjYj2024main (trigger Branch)
    • Script Path : Jenkinsfile (루트 프로젝트에서 Jenkinsfile의 경로 - 기본값 유지)
  • 저장

16-5. GitHub Repository Webhooks 설정

  • GitHub Repository 의 Settings > Webhooks > Add webhook
    • Payload URL : http://192.168.1.111:8080/github-webhook/ (http://Jenkins주소/github-webhook/)
    • Content type : application/json
    • Let me select individual events 선택 > Pull requests, Pushes 선택
    • Active 체크 유지
  • Add webhook

🔶 지금 빌드

  • 지금 빌드 > 아래와 같이 workspace 가 생김
[root@localhost workspace]# pwd
/var/lib/containers/storage/volumes/4e56f41adaca53fa1652bb2d5e0aaa4f80905a278588c911343a283eb21be2fb/_data/workspace
[root@localhost workspace]# ls
ProjYj2024  ProjYj2024@tmp
  • 컨테이너의 프로세스 실행 및 접속 (podman exec)
[root@localhost home]# podman exec -it jenkins /bin/bash
jenkins@d7020c058f90:~/workspace$ cd /var/jenkins_home/workspace
jenkins@d7020c058f90:~/workspace$ ls
ProjYj2024  ProjYj2024@tmp

🔶 Jenkins 를 위한 권한 부여

  • Jenkins 빌드 시 Permission denied 방지
[root@localhost storage]# pwd
/var/lib/containers/storage
[root@localhost storage]# chmod 755 volumes/
[root@localhost storage]# ls -al
total 144
drwxr-xr-x   3 root root     78 Mar 29 14:31 volumes

[root@localhost volumes]# pwd
/var/lib/containers/storage/volumes
[root@localhost volumes]# chmod 755 4e56f41adaca53fa1652bb2d5e0aaa4f80905a278588c911343a283eb21be2fb

[root@localhost _data]# pwd
/var/lib/containers/storage/volumes/4e56f41adaca53fa1652bb2d5e0aaa4f80905a278588c911343a283eb21be2fb/_data
[root@localhost _data]# chmod 777 logs/* #파일 생성 권한
[root@localhost _data]# chmod 777 logs

16-6. Plugin 설치 - Post build task

16-7. Plugin 설치 - NodeJS

  • Jenkins 빌드 시 npm not found error 방지
  • Jenkins > Dashboard > Jenkins 관리 > Plugins > Available plugins
  • NodeJS 선택하여 설치
  • Dashboard > Jenkins 관리 > Tools > NodeJS installations > Add NodeJS 클릭
    • Name : NodeJS 20.9.0
    • Version : NodeJS 20.9.0 (node -version 일치)
profile
개린이

0개의 댓글