使用gitlab CI/CD 完成自动部署

使用gitlab CI/CD 完成自动部署

二月 15, 2019

添加Gitlab的官方源:

1
2
3
4
5
# For Debian/Ubuntu
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-ci-multi-runner/script.deb.sh | sudo bash

# For CentOS
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-ci-multi-runner/script.rpm.sh | sudo bash

安装

1
2
3
4
5
# For Debian/Ubuntu
sudo apt-get install gitlab-ci-multi-runner

# For CentOS
sudo yum install gitlab-ci-multi-runner

注册Runner
Runner需要注册到Gitlab才可以被项目所使用,一个gitlab-ci-multi-runner服务可以注册多个Runner。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ sudo gitlab-ci-multi-runner register

Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com )
https://mygitlab.com/ci
Please enter the gitlab-ci token for this runner
xxx-xxx-xxx
Please enter the gitlab-ci description for this runner
my-runner
INFO[0034] fcf5c619 Registering runner... succeeded
Please enter the executor: shell, docker, docker-ssh, ssh?
docker
Please enter the Docker image (eg. ruby:2.1):
node:4.5.0
INFO[0037] Runner registered successfully. Feel free to start it, but if it's
running already the config should be automatically reloaded!

更新Runner
如果需要更新Runner,只需要执行以下脚本:

1
2
3
4
5
6
7
# For Debian/Ubuntu
sudo apt-get update
sudo apt-get install gitlab-ci-multi-runner

# For CentOS
sudo yum update
sudo yum install gitlab-ci-multi-runner

Runner高级配置
通过gitlab-ci-multi-runner register注册的Runner配置会存储在/etc/gitlab-runner/config.toml中,如果需要修改可直接编辑该文件。详见这里
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
concurrent = 4
check_interval = 0

[[runners]]
name = "test"
url = "http://your-domain.com/ci"
token = "your-token"
executor = "docker"
[runners.docker]
tls_verify = false
image = "node:4.5.0"
privileged = false
disable_cache = false
volumes = ["/cache"]
[runners.cache]
[runners.kubernetes]
host = ""
cert_file = ""
key_file = ""
ca_file = ""
image = ""
namespace = ""
privileged = false
cpus = ""
memory = ""
service_cpus = ""
service_memory = ""

到这里我们的Runner就安装配置好了,接下来是对项目根目录中.gitlab-ci.yml进行配置。

配置构建任务
在项目根目录添加.gitlab-ci.yml文件
关于该文件的各项配置请见

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 这里使用了我自己的docker image,配置了自己需要的环境
image: wuyanxin/node

variables:
MYSQL_DATABASE: wan_ark-unit
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

# 关于service请见: http://docs.gitlab.com/ce/ci/docker/using_docker_images.html#what-is-service
services:
- mysql:5.6
- redis:3.2.4

stages:
- test
- eslint
- deploy

before_script:
- echo 'REDIS_HOST=redis' >> .env
- echo 'DB_HOST=mysql' >> .env
- yarn install

test_service:
stage: test
script:
- npm run build
- npm test

eslint_src:
stage: eslint
script:
- npm run lint
allow_failure: true

deploy:
stage: deploy
script:
- echo 'deployd!'
only:
- master

这里使用了nodejs项目作为例子,其他语言类似语法。