使用gitlab的Ci自动部署项目 pipeline gitlab-runner

Posted by admin on 2017, May 15

现今很有项目代码托管在gitlab,当然也有很多公司使用gitlab搭建在本地进行托管,今天来一步步来讲讲如何把gitlab上的代码部署在linux服务器上,当提交到代码到相应的分支,自动进行部署,保留多个版本的代码以及回滚。下面开始步骤:

1:安装GitLab Runner

这里我将使用shell的方式,所以不安装docker了,直接安装GitLab Runner

# 获取官方代码  For RHEL/CentOS
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-ci-multi-runner/script.rpm.sh | sudo bash

# 安装 gitlab-ci-multi-runner
sudo yum install gitlab-ci-multi-runner

根据步骤完成

2:注册runner

先打开https://gitlab.com/akmumu/xxx/settings/ci_cd,看到Specific Runners下面的How to setup a specific Runner for a new project。有相关下面用的信息,url和token。

sudo gitlab-ci-multi-runner register

Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com )
**刚才的url**
Please enter the gitlab-ci token for this runner
**刚才的token**
Please enter the gitlab-ci description for this runner
**起名**
INFO[0034]() XXXX Registering runner... succeeded
Please enter the executor: shell, docker, docker-ssh, ssh?
**shell**
INFO[0037]() Runner registered successfully. Feel free to start it, but if it's
running already the config should be automatically reloaded!

注册完毕,可以从/etc/gitlab-runner/config.toml看到已经有你注册的runner了。 对了,这时候在https://gitlab.com/akmumu/xxx/settings/ci_cd页面上的Shared Runners中的按钮点了,即关掉Shared Runners,不然他运行公共的runner会带来各种问题,一定注意!

3:启动

sudo gitlab-ci-multi-runner start
或者
sudo gitlab-ci-multi-runner run
这个是类似监听模式,不能关命令行的,所以运行start吧
sudo gitlab-ci-multi-runner status
瞅一眼状态,哦了!

https://gitlab.com/akmumu/xxx/settings/ci_cd中能看到绿色运行中的你的runner。

4:设置deploy key

https://gitlab.com/akmumu/xxx/settings/repository 在这里设置deploy key,步骤里面有,不再赘述。完了就可以在服务器上拉取代码了。

5:CI configuration

文档在此,你可以按照文档所说增加配置
https://gitlab.com/help/ci/yaml/README.md

在项目中点击_CI configuration_按钮,即 https://gitlab.com/akmumu/xxx/blob/master/.gitlab-ci.yml增加你的配置文件,这里放我的简单例子。

stages:
  - build
  - test
  - deploy

deploy_online:
  stage: deploy
  script:
    - ./ci-deploy.sh
  only:
    - master

因为我使用的shell模式,所以意思是当master分支有改动(merge request到master也算)直接运行代码库里面的./ci-deploy.sh来完成部署,下面是我的sh脚本实例: https://gitlab.com/akmumu/xxx/blob/master/ci-deploy.sh

# !/bin/sh
DEPLOY_ROOT=/www/deploy/xxx
SHARED_GIT_PATH=$DEPLOY_ROOT/shared
DEPLOY_PATH=$DEPLOY_ROOT/releases/`date '+%Y%m%d%H%M%S'`

echo "copy file to $DEPLOY_PATH"
mkdir -p $DEPLOY_PATH
cp -R * $DEPLOY_PATH/

# link user generated media
ln -s $SHARED_GIT_PATH/media/ $DEPLOY_PATH/media/

# point current to the latest releases
echo "point $DEPLOY_ROOT/current to $DEPLOY_PATH"
rm -rf $DEPLOY_ROOT/current
ln -s $DEPLOY_PATH $DEPLOY_ROOT/current

echo "delete the old releases, keep the latest 5"
# the directories is sorted by datetime from low to high
ls -d -1 $DEPLOY_ROOT/releases/* | head -n -5 | xargs rm -rf

懂shell的自然就都看懂啦,不然的话就去你的服务器目录/www/deploy/xxx 看看就都明白了,回滚的话,就把目录中的current 指向你想要的版本即可。

6:Capistrano

https://github.com/capistrano/capistrano 当然你想更多的功能而不想写shell脚本,那么就用这个工具吧,一样能集成到CI中,Good Luck!