gitlab配置自动发布

本文最后更新于:1 年前

centos下载安装gitlab-runner

Download the binary for your system

1
sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64

Give it permission to execute

1
sudo chmod +x /usr/local/bin/gitlab-runner

Create a GitLab Runner user

1
sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash

Install and run as a service 以root用户运行

1
2
sudo gitlab-runner install --user=root --working-directory=/home/gitlab-runner
sudo gitlab-runner start

Command to register runner

1
sudo gitlab-runner register --url https://gitlab.com/ --registration-token GR13489417zyvUYp9bpLGRGkQ3x9e

GR13489417zyvUYp9bpLGRGkQ3x9e gitlab仓库Registration token。项目仓库->Settings->CI/CD->Runners获取。

gitlab-runner目录下配置发布和启动脚本

start.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
if [ $# -ne 2 ]
then
echo "jobs path error!"
exit 99
else
echo "start $1 jobs!"
if [ $1 = "service" ]
then
su - service -s /bin/bash /home/$1/$2/start.sh $1 $2
elif [ $1 = "www" ]
then
su - www -s /bin/bash /home/$1/html/$2/start.sh $1 $2
fi
fi

deploy.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
if [ $# -ne 2 ]
then
echo "jobs path error!"
exit 99
else
echo "deploy $1 jobs!"
if [ $1 = "service" ]
then
su - service -s /bin/bash /home/$1/$2/deploy.sh $1 $2
elif [ $1 = "www" ]
then
su - www -s /bin/bash /home/$1/html/$2/deploy.sh $1 $2
fi
fi

设置可执行权限

1
2
chmod +x start.sh
chmod +x deploy.sh

项目设置.gitlab-ci.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
variables:
PIPELINE_NAME: 'ywblog'

stages:
- deploy

deploy:
stage: deploy
only:
- live
script:
- echo "deploy start ..."
- echo "Hello, $GITLAB_USER_LOGIN!!"
- echo "This job [$PIPELINE_NAME] deploy"
- echo "current branch ****** $CI_COMMIT_REF_NAME ******"
- echo "=============== start deploy ==============="
- echo "current branch - $CI_COMMIT_REF_NAME"
- chmod a+x /home/gitlab-runner/deploy.sh
- bash /home/gitlab-runner/deploy.sh www $PIPELINE_NAME
- echo "=============== end deploy ==================="

live指定live分支触发执行脚本

项目设置deploy.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

if [ $# -ne 2 ]
then
echo "jobs path error!"
exit 1
else
echo "deploy $1/html/$2 jobs!"
deploy_dir="/home/$1/html/$2"
if [ -d "$deploy_dir" ]
then
cd $deploy_dir
git pull
else
echo "Please clone the job($1/html/$2) from gitlab first!"
fi
fi