GitLab CI/CD

使用docker下载gitlab镜像

1
docker pull gitlab/gitlab-ce

检查镜像下载是否成功

1
2
3
[root@public ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
gitlab/gitlab-ce latest 85ef0c92d667 3 days ago 1.98GB

创建数据存储目录

1
2
3
[root@public ~]# mkdir -p /opt/gitlab/data
[root@public ~]# mkdir /opt/gitlab/logs
[root@public ~]# mkdir /opt/gitlab/config

启动gitlab

1
2
3
4
5
6
7
8
9
10
[root@public gitlab]# docker run --detach \
--hostname 192.168.229.8 \
--publish 8443:443 --publish 9080:80 --publish 2222:22 \
--name gitlab \
--restart always \
--privileged=true \
--volume /file/gitlab/config:/etc/gitlab \
--volume /file/gitlab/logs:/var/log/gitlab \
--volume /file/gitlab/data:/var/opt/gitlab \
docker.io/gitlab/gitlab-ce:latest

gitlab如使用单台服务器可使用默认配置,若跟别的服务放一起会出现gitlab占用内存过多问题

1
2
3
4
5
6
7
8
9
10
11
vi /file/gitlab/config/gitlab.rb

#去掉下面的注释

unicorn['worker_processes'] = 2

#之后执行

docker exec -it gitlab gitlab-ctl reconfigure

docker exec -it gitlab gitlab-ctl restart

gitlab初始用户名密码

1
2
3
4
5
6
7
8
9
10
[root@deployment /]# cat /opt/gitlab/config/initial_root_password 
# WARNING: This value is valid only in the following conditions
# 1. If provided manually (either via `GITLAB_ROOT_PASSWORD` environment variable or via `gitlab_rails['initial_root_password']` setting in `gitlab.rb`, it was provided before database was seeded for the first time (usually, the first reconfigure run).
# 2. Password hasn't been changed manually, either via UI or via command line.
#
# If the password shown here doesn't work, you must reset the admin password following https://docs.gitlab.com/ee/security/reset_user_password.html#reset-your-root-password.

Password: GHztfkIk0eg4qdTTNn5owN+7jK3ojlUHLrXMibB5Pj8=

# NOTE: This file will be automatically deleted in the first reconfigure run after 24 hours.

安装GitLab Runner

下载并安装二进制文件

1
2
3
4
5
6
7
8
9
10
11
12
# Download the binary for your system
curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64

# Give it permissions to execute
chmod +x /usr/local/bin/gitlab-runner

# Create a GitLab CI user
useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash

# Install and run as service
gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
gitlab-runner start

注册runner的命令

注册的地址要填写为ip+port.不要使用web页面展示的http://ip// 否则注册失败

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@deployment /]# gitlab-runner register
Runtime platform arch=amd64 os=linux pid=86642 revision=58ba2b95 version=14.2.0
Running in system-mode.

Enter the GitLab instance URL (for example, https://gitlab.com/):
http://192.168.50.52:9090/
Enter the registration token:
cZ8xxddc9zciAHAsJpqB
Enter a description for the runner:
[deployment]: test
Enter tags for the runner (comma-separated):
test
Registering runner... succeeded runner=cZ8xxddc
Enter an executor: docker, docker-ssh, parallels, shell, virtualbox, kubernetes, custom, ssh, docker+machine, docker-ssh+machine:
shell
Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded!

Runner连接

不要把Runner和gitlab部署在一台机器 不然会一直显示未连接

Runner的构建目录

1
/home/gitlab-runner/builds/ymVX6kY7/0/

Runner的注册后的配置文件

1
/etc/gitlab-runner/config.toml

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
variables:
GIT_STRATEGY: clone

before_script:
- pwd

stages:
- build
- deploy

build-job:
stage: build
tags:
- nimingkun
only:
- release
script:
- mvn clean install -Dmaven.test.skip=true
- cp ymall/target/ymall-0.0.1-SNAPSHOT.jar dockerfile/
- cd dockerfile && sh build.sh ymall
artifacts:
paths:
- ymall/target/ymall-0.0.1-SNAPSHOT.jar

deploy-job:
stage: deploy
tags:
- nimingkun
only:
- release
script:
- sh CD.sh

会出现报错,因为git版本告知的错误

1
2
fatal: git fetch-pack: expected shallow list
fatal: The remote end hung up unexpectedly

解决方法

1
2
yum install  http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-2.noarch.rpm
yum update git

CI中出现打包镜像错误

1
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.24/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=192.168.50.52%3A8551%2Fymall%3Alatest&target=&ulimits=null&version=1: dial unix /var/run/docker.sock: connect: permission denied

原因:

1
使用root账户直接yum安装docker,然后service docker start启动docker服务。Gitlab-CI默认以gitlab-runner用户执行,因此对/var/run/docker.sock无访问权限,无法与docker daemon通信

解决方法

1
2
3
4
5
6
7
8
groupadd -r docker
useradd -g docker -r docker -p 'password'

usermod -aG docker gitlab-runner

service docker stop
su docker
sudo service docker start

我这里仅为测试GitLab-CI,故直接添加docker到gitlab-runner组

1
usermod -aG  docker gitlab-runner

拉取Git仓库时报错

1
2
3
4
5
6
7
8
9
10
11
Initialized empty Git repository in /private/var/folders/g5/8twmk1xj481_6btvppyw5j4h0000gp/T/.tmpNYVg6H/.git/
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint: git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint: git branch -m <name>

解决方法

1
git config --global init.defaultBranch master

GitLab-CI 文件详解

关键字 是否必须 描述
variables 非必须 在job级别上定义的变量
before_script 非必须 提前执行的脚本
stages 必须 指定一组job在不同场景阶段执行。在相同stage下的job(任务)将会被并行的执行
job-name 必须 流水线的任务的名称
stage 必须 与stages内的场景阶段对应
tags 非必须 定义了哪些runner适用该job
only 非必须 定义哪些git引用(分支)适用该job
except 非必须 定义了哪些git引用(分支)不适用该job
script 必须 定义Runner需要执行的脚本或命令
artifacts 非必须 产物,通过paths指定文件后,可在gitlab页面下载改产物
after_script 非必须 后执行的脚本
environment 非必须 定义让job完成部署的环境名称

onlyexcept两个参数说明了job什么时候将会被创建:

  1. only定义了job需要执行的所在分支或者标签
  2. except定义了job不会执行的所在分支或者标签

以下是这两个参数的几条用法规则:

  1. onlyexcept如果都存在在一个job声明中,则所需引用将会被onlyexcept所定义的分支过滤.
  2. onlyexcept允许使用正则
  3. onlyexcept允许使用指定仓库地址,但是不forks仓库

此外,onlyexcept允许使用以下一些特殊关键字:

描述
branches 当一个分支被push上来
tags 当一个打了tag的分支被push上来
api 当一个pipline被piplines api所触发调起,详见piplines api
external 当使用了GitLab以外的CI服务
pipelines 针对多项目触发器而言,当使用CI_JOB_TOKEN并使用gitlab所提供的api创建多个pipelines的时候
pushes 当pipeline被用户的git push操作所触发的时候
schedules 针对预定好的pipline而言(每日构建一类~,具体请看链接
triggers 用token创建piplines的时候
web 在GitLab页面上Pipelines标签页下,你按了run pipline的时候

下面的例子,job将会只在issue-开头的refs下执行,反之则其他所有分支被跳过:

1
2
3
4
5
6
7
job:
# use regexp
only:
- /^issue-.*$/
# use special keyword
except:
- branches

在这个例子中,job只会在打了tag的分支,或者被api所触发,或者每日构建任务上运行,

1
2
3
4
5
6
job:
# use special keywords
only:
- tags
- triggers
- schedules

Git Strategy(git策略)

你可以通过在全局变量设置位置或者job局部变量设置位置来设置GIT_STRATEGY用以获取应用最近更新的代码。如果没有指定,默认的项目设置将会被使用。

该选项有三个可能的值:clone,fetch和none

clone是最慢的选项,如果设置该值,每个job将会都克隆一遍仓库,确保项目工作空间总是原始的正确的。

1
2
variables:
GIT_STRATEGY: clone

fetch是更快的操作选项,因为他重用了项目的工作空间(如果没有的话,会去clone), git clean用于撤销上一个job的任何操作,git fetch是用来重新获取上一个job运行到当前job产生的commit

1
2
variables:
GIT_STRATEGY: fetch

none也同样重用了项目空间(但是他会跳过所有git操作,包括如果存在的gitlab runner的预克隆脚本)。其主要用于只是为了操作artifacts的job上(例如depoly部署行为)。此时Git仓库的数据可能是存在的,但它一定不是最新的。所以在设置了none的job里你应该依赖从cache或者artifacts来的数据,而不是仓库数据。

1
2
variables:
GIT_STRATEGY: none

Shallow cloning (浅克隆)

抓取或者克隆最新三条commits:

1
2
variables:
GIT_DEPTH: "3"

查看流水线阶段完成情况

查看每个阶段的运行日志

下载yml中定义的产物

后续可深入了解 gitlab集成Kubernetes,Prometheus和Grafana.可在gitlab查看部署情况,查看Kubernetes日志,审核是否发布等操作

备份gitlab

1
2
3
4
5
6
7
8
9
10
11
12
[root@iZ2zeaxvb40ng4w24tpogoZ file]# crontab -l
0 0 */3 * * sh /file/backup.sh

[root@iZ2zeaxvb40ng4w24tpogoZ file]# cat /file/gitlab/push_aliyun.sh
docker commit -m "gitlab" 5f36554b62b3 registry-vpc.cn-beijing.aliyuncs.com/lepeng/gitlab:`date +%F`
docker push registry-vpc.cn-beijing.aliyuncs.com/lepeng/gitlab:`date +%F`

[root@iZ2zeaxvb40ng4w24tpogoZ file]# cat /file/backup.sh
cd /file/
tar zcvf gitlabconfig`date +%F`.tar config
tar zcvf gitlabdata`date +%F`.tar data
mv *.tar /data1/gitlab/backup/

gitlab配置ldap

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
vim /file/config/gitlab.rb
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = YAML.load <<-'EOS'
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'LDAP'
host: '39.107.142.154'
port: 389
uid: 'cn'
bind_dn: 'cn=admin,dc=gzlplink,dc=com'
password: 'Lpldap123456'
encryption: 'plain' # "start_tls" or "simple_tls" or "plain"
verify_certificates: true
active_directory: true
#邮箱 用户名均可登录
allow_username_or_email_login: true
lowercase_usernames: false
#不允许用户注册
block_auto_created_users: false
base: 'ou=研发部,cn=admin,dc=gzlplink,dc=com'
user_filter: ''
attributes:
username: ['cn']
email: ['mail']
name: 'description'
first_name: 'givenName'
last_name: 'sn'
EOS
  • hostport 是 LDAP 服务的主机地址及端口
  • bind_dnpassword 是一个管理 LDAP 的 dn 及密码
  • base 表示 LDAP 将以该 dn 为 节点,向下查找用户
  • user_filter 表示以某种过滤条件筛选用户,比如假设我们只希望所属组为 Developers 的用户来访问 GitLab,则可以在这里设置 (memberOf=cn=Developers,cn=Groups,dc=xinhua,dc=org)
  • attributes 表示 GitLab 中的字段与 LDAP 中哪些字段可以相互对应,比如可以用 LDAP 中的 uid 来作为 GitLab 用户名

配置修改完成之后,运行下面命令重启 GitLab 服务:

1
gitlab-ctl reconfigure

开启 HTTPS

GitLab 默认没有开启 HTTPS,如果需要开启的话,需要按照下面的步骤执行:

首先,在配置文件 /etc/gitlab/gitlab.rb 中将下面一行中的协议由 HTTP 改成 HTTPS,并设置从 HTTP 到 HTTPS 的重定向:

1
2
3
4
external_url "https://gitlab.example.com"

# Redirect HTTP requests to HTTPS
nginx['redirect_http_to_https'] = true

然后创建一个 SSL 目录,并将网站证书导入进去:

1
2
3
# mkdir -p /etc/gitlab/ssl
# chmod 700 /etc/gitlab/ssl
# cp gitlab.xinhua.io.key gitlab.xinhua.io.crt /etc/gitlab/ssl/

注意上面的证书必须以配置中的域名(如本文中的 gitlab.xinhua.io)为其文件名。

最后再执行 gitlab-ctl reconfigure 命令,即可通过 HTTPS 方式访问 GitLab 了