搭建一個GitLab CI環境分兩步
在服務器配置GitLab Runner
GitLab Runner是一個用來執行持續集成腳本的網絡服務,它的工作模式是
- 輪詢GitLab倉庫
- 一旦發現GitLab倉庫中的代碼分支有變化,就在服務器的工作空間內
pull
(拉取)最新代碼 - 並執行項目目錄下
.gitlab-ci.yml
中的持續集成腳本 - 把服務器終端的命令行日誌返回給GitLab CI
下面我們在Ubuntu中配置GitLab Runner項目
安裝GitLab Runner
Ubuntu系統安裝什麼都很簡單,GitLab Runner也不例外,就下面兩行代碼
# 命令增加GitLab官方倉庫
$ curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash
# 安裝最新版本的GitLab Runner
$ sudo apt-get install gitlab-runner
註冊GitLab Runner
還需要配置一下GitLab倉庫的相關信息,這樣GitLab Runner才能輪詢GitLab倉庫與GitLab CI持續集成
# 註冊GitLab Runner對應的GitLab信息
$ sudo gitlab-runner register
上面的命令會要我們輸入5個信息,分別是
$ Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com)
$ [GitLab URL,在GitLab倉庫的`Settings -> CI/CD -> Runners`下查看]
$ Please enter the gitlab-ci token for this runner
$ [註冊token,在GitLab倉庫的`Settings -> CI/CD -> Runners`下查看]
$ Please enter the gitlab-ci description for this runner
$ [這個Runner的名稱]
$ Please enter the gitlab-ci tags for this runner (comma separated):
$ [這個Runner的tag]
$ Please enter the executor: ssh, docker+machine, docker-ssh+machine, kubernetes, docker, parallels, virtualbox, docker-ssh, shell:
$ [這個Runner的執行器類型,這裏用最簡單的shell就好了]
註冊如果順利的話,後面的兩步就非常簡單了
通過.gitlab-ci.yml編寫腳本
在GitLab倉庫的目錄下新建.gitlab-ci.yml
腳本文件,正常情況下GitLab的項目主頁頂部會提供快捷方式,可以一鍵創建.gitlab-ci.yml
腳本文件
編輯.gitlab-ci.yml
腳本文件,這裏爲了演示,就使用最簡單的方式寫了一個輸出“GitLab倉庫代碼在服務器的工作空間目錄”的shell腳本
stages:
- test
test-job:
stage: test
script:
- echo `pwd`
tags:
- [上一步配置的Runner的tag名稱]
當你編輯完.gitlab-ci.yml
腳本文件,點擊保存後,在GitLab倉庫的Settings -> CI/CD -> Pipelines
下,就會發現你剛纔保存的代碼更改,成功觸發了GitLab Runner服務,在服務器上執行了持續集成腳本,並可以直接看到服務器終端的執行輸出及結果
到這裏就已經完成了GitLab CI的搭建