简介:gitlab-runner是一个开源项目,用于运行Pipeline作业并将结果发送回GitLab。它与GitLab CI一起使用,GitLab CI是GitLab随附的开源持续集成服务,用于协调作业。gitlab-runner是用Go编写,可以作为单个二进制文件运行,不需要语言特定的要求。
环境:centOS
1.在web服务器上安装所需工具Nodejs,yarn,git,Gitlab Runner##
# 下载node包
wget https://nodejs.org/dist/v16.13.0/node-v16.13.0-linux-x64.tar.xz
# 解压Node包
tar -xf node-v16.13.0-linux-x64.tar.xz
# 在配置文件(位置多在/etc/profile)末尾添加:
export PATH=$PATH:/root/node-v16.13.0-linux-x64/bin
# 刷新shell环境:
source /etc/profile
# 查看版本(输出版本号则安装成功):
node -v
npm i yarn -g
#or
npm i pnpm -g
# 利用yum安装git
yum -y install git
# 查看git版本
git --version
# 安装程序 gitlab-runner
wget -O /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64
# 等待下载完成后分配权限
chmod +x /usr/local/bin/gitlab-runner
# 创建runner用户
useradd --comment 'test' --create-home gitlab-runner --shell /bin/bash
# 安装程序
gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
# 启动程序
gitlab-runner start
# 安装完成后可使用gitlab-runner --version查看是否成功
2.在gitlab配置项目的Runner及CI/CD##
2.1配置Gitlab Runner
首先打开待添加自动部署功能的gitlab仓库,在其中设置 > CI/CD > Runner中找到runner配置信息备用:

在web服务器中配置runner:
gitlab-runner register
>> Enter the GitLab instance URL (for example, https://gitlab.com/):
# 输入刚才获取到的gitlab仓库地址
>> Enter the registration token:
# 输入刚才获取到的token
>> Enter a description for the runner:
# 自定runner描述
>> Enter tags for the runner (comma-separated):
# 自定runner标签
>> Enter an executor: docker-ssh, docker+machine, docker-ssh+machine, docker, parallels, shell, ssh, virtualbox, kubernetes, custom:
# 选择执行器,此处我们输入shell
完整示例:

2.2配置.gitlab-ci.yml
.gitlab-ci.yml文件是流水线执行的流程文件,Runner会据此完成规定的一系列流程。
我们在项目根目录中创建.gitlab-ci.yml文件,然后在其中编写内容:
# 阶段
stages:
- install
- build
- deploy
cache:
paths:
- node_modules/
# 安装依赖
install:
stage: install
# 此处的tags必须填入之前注册时自定的tag
tags:
- deploy
# 规定仅在package.json提交时才触发此阶段
only:
changes:
- package.json
# 执行脚本
script:
yarn
# 打包项目
build:
stage: build
tags:
- deploy
script:
- yarn build
# 将此阶段产物传递至下一阶段
artifacts:
paths:
- dist/
# 部署项目
deploy:
stage: deploy
tags:
- deploy
script:
# 清空网站根目录,目录请根据服务器实际情况填写
- rm -rf /www/wwwroot/stjerne/salary/*
# 复制打包后的文件至网站根目录,目录请根据服务器实际情况填写
- cp -rf ${CI_PROJECT_DIR}/dist/* /www/wwwroot/stjerne/salary/
保存并推送至gitlab后即可自动开始构建部署。
构建中可在gitlab CI/CD面板查看构建进程

3.运行时报错##
运行时报类似:"bash: yarn: command not found" 的错误,其实是权限的问题,需要将默认的gitlab-runner,改为root。

3.1查看gitlab-runner进程
ps aux|grep gitlab-runner

3.2卸载gitlab-runner默认用户
gitlab-runner uninstall
3.3将用户设置为root
gitlab-runner install --working-directory /home/gitlab-runner --user root
3.4重启服务
systemctl restart gitlab-runner.service
3.5再次查看gitlab-runner进程,确认已修改为root
ps aux|grep gitlab-runner

4.常见问题
4.1“Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters”
确认sshpass已安装在gitlab服务器
4.2 gitlab项目gitlab-runner获取不到到设置CI/CD-变量
建议关闭,只应用于保护分支或标签
参考:
https://juejin.cn/post/7037022688493338661
https://blog.csdn.net/hzblucky1314/article/details/125966138
Gitlab CI:https://blog.csdn.net/weixin_38080573/category_8715427.html