Chuyển tới nội dung

Lab03: Xây dựng Quy trình build qua gitlab webhook.

Mục tiêu

  • Code được commit lên Gitlab
  • Jenkins tự động build

Cấu hình trong Gitlab

1. Tạo Personal Access Token (PAT) trong gitllab

  • Vào Gitlab -> Preferences -> Access Tokens
  • Tạo token với quyền api read_repository
  • Ghi lại token

2. Thêm Webhook

  • Trong Gitlab Project -> Settings -> Webhooks -> Add new webhook

Cấu hình trong Jenkins

1. Tạo Credentials

Vào Manage Jenkins -> Credentials -> Global

Tạo Username + Password Credentials

  • Kind: Gitlab API token
  • API Token: <PAT>
  • ID: gitlab-cred

2. Tạo pipeline

New Item -> Nhập tên -> Chọn Pipeline -> OK

Cấu hình trigger

Cấu hình pipeline
Pipeline script nhập luôn pipeline script tại Jenkins
Pipeline script from SCM: Pipeline script được lưu ở git (Ở đây tôi chọn Pipeline script from SCM)

Chọn Git trong SCM -> Nhập Repository URL (http://gitlab.local/beobeo/corejs) -> Chọn Credentials -> Nhập Braches (nodejs) to build hoặc để ** để build với mọi branches -> Nhập đường dẫn Jenkinsfile (Ở đây ta đặt ở thư mục gốc)

Tạo Jenkinsfile và push lên gitlab.

Jenkinsfile

pipeline {
  agent any
  stages {
    stage('Hello world') {
      steps {
        echo "Hello world."
      }
    }
  }
}

Commit code và push lên Gitlab

git add .
git commit -m "Hello World"
git push 

Kiểm tra trong Jenkins, không thấy được build.
Kiểm tra trong Webhook thấy có thông báo 403

Có 3 cách sửa:

1. Cho phép Anonymous được phép Build

Vào Manage Jenkins -> Security -> Authorization

      2. Bỏ Enable authentication for '/project' end-point

      3. Tạo token xác thực

      Chọn Admin -> Security -> Add new token

      Nhập tên API Token -> Generate

        Copy và Lưu token

        Cấu hình cho phép job được trigger từ xa (Remotely)
        Chọn job cần cấu hình (build-core) -> Trigger -> Trigger builds remotely (e.g., from scripts) -> Nhập token vào ổ Authentication Token

        Thay đổi URL trong Gitlab Webhook bằng:
        http://<jenkins_user>:<api_token>@<jenkins_host>:8080/job/<job_name>/build?token=<job_token>

        Save -> Test Push

        Push lại code và kiểm tra

        Đến đây là hoàn thành.

        Liên hệ