0
user-people-family-house-home

【Gitlab】利用Gitlab執行CI/CD(持續整合/自動部屬)

GitLab什麼是CI/CDCI (Continuous Integration)、CD (Continuous Del...

Posted by Roy on 2023-03-27 03:25:50 Views

GitLab

什麼是CI/CD

CI (Continuous Integration)、CD (Continuous Delivery/Deployment) 目的是從測試、建置到部署自動化,取代原來人工需要做的事情。

  • CI (Continuous Integration): 專注在持續整合,透過程式碼的自動化測試和建置,將穩定品質的程式碼合併,越早頻繁整合,整合難度的就越低且能確保最新版本是可運行的
  • CD (Continuous Delivery/Deployment): 專注在持續部屬和交付,依照需要的環境進行建置和部屬

開始測試CI/CD

首先註冊Gitlab,並且push一個專案上Gitlab的Project。

至 Gitlab -> 專案 -> settings -> CI / CD -> Runners expand 打開

gitlab_ci_cd_runners

這些資訊就是用來設定gitlab-runner時使用的

進入VM安裝gitlab-runner

sudo apt update
sudo apt install curl
sudo curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash sudo apt-get install gitlab-runner

然後進行註冊

sudo gitlab-runner register

根據敘述依據gitlab的資料複製貼上,這裡的executor選擇shell

gitlab_ci_cd

重整Gitlab後會看到runner已經更新了

gitlab_ci_cd_runner

之後舉例會是以Laravel框架為範例

主機上的環境設定就不再多做敘述

.gitlabci.yml 範例

stages:
  - test
  - deploy
  - cache
unit-test-job:   
  stage: test    
  tags:
    - "runner_tag"
  # 限制只有 master branch 會執行此 job
  only:
    - master
  script:
    - cd {project_path}
    - php artisan test
cache-job:   
  stage: cache    
  tags:
    - "runner_tag"
  # 限制只有 master branch 會執行此 job
  only:
    - master
  script:
    - cd {project_path}
    - php artisan cache:clear
    - php artisan optimize
    - php artisan view:cache
deploy-job:
  # 宣告此 job 屬於哪一個 stage
  stage: deploy
  # gitlab runner 的 tags
  tags:
    - "runner_tag"
  # 限制只有 master branch 會執行此 job
  only:
    - master
  # 最後是此 job 要執行哪些動作
  script:
    - cd {project_path}
    - git checkout master
    - git pull origin master
    - composer install

之後測試推master的branch上gitlab,就會看到CI/CD->Jobs上會有執行結果

gitlab_ci_cd_jobs

CI/CD->Pinelins

gitlab_ci_cd_pinelines

View Comments