Press "Enter" to skip to content

gitlab-runner 搭配Deployer 实现CI(持续集成) 和 CD(持续部署)

整体思路是gitlab-runner部署在公司内网环境,内网更新项目下来后然后通过Deployer同步到线上服务器。一开始想通过所有线上服务器安装gitlab-runner来更新代码,测试之后gitlab-ruuner只能有一台执行,还需要通过其他工具来批量发布,后面根据php项目情况调研了 Deployer ,通过Deployer 来发布到所有线上服务器。

首先在内网测试服务器,新建一个用户www ,然后设置密码,切换www用户安装gitlab-runner

//下载文件
sudo curl -L --output /usr/local/bin/gitlab-runner "https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64"

//设置可以执行权限
sudo chmod +x /usr/local/bin/gitlab-runner

//安装
sudo /usr/local/bin/gitlab-runner install --user=www --working-directory=/home/www/gitlab-runner

//设置文件夹所属用户
chown www:www -R /home/www/gitlab-runner/

chmod 777 -R /home/www/gitlab-runner/

//关联gitlab项目
sudo /usr/local/bin/gitlab-runner register --url https://gitlab.com/ --registration-token xxxyyzzz

//启动
sudo /usr/local/bin/gitlab-runner start


//设置密钥
ssh-keygen -t rsa -b 4096 -f  ~/.ssh/deployerkey

//设置在某个服务器 通过www用户登录的公钥(这个用户需要在服务器上面先添加)
ssh-copy-id -i  ~/.ssh/deployerkey.pub [email protected]

//测试 www通过密密钥链接 服务器
ssh [email protected]  -i ~/.ssh/deployerkey

//上面链接OK 说明密钥配置OK

deploy.php 代码文件内容
<?php
namespace Deployer;

//配置服务器
host('aa.bb.cc.zz')
    ->user('www')
    ->port(22)
    ->identityFile('~/.ssh/deployerkey')
    ->forwardAgent(true)
    ->multiplexing(true)
    ->addSshOption('UserKnownHostsFile', '/dev/null')
    ->addSshOption('StrictHostKeyChecking', 'no');
//多个服务器
host('aa1.bb1.cc1.zz1')
    ->user('www')
    ->port(22)
    ->identityFile('~/.ssh/deployerkey')
    ->forwardAgent(true)
    ->multiplexing(true)
    ->addSshOption('UserKnownHostsFile', '/dev/null')
    ->addSshOption('StrictHostKeyChecking', 'no');

task('test_run', function () {

    if (test('[ -d /data/web/xxx ]')) {
        writeln('/data/web/xxx exists');
    } else {
        writeln('/data/web/xxx not exists');
    }
    writeln("Current dir:");

    $deployPath = '/data/web/zzz';
    $appFiles = [
        'Application/Admin',
    ];
    foreach ($appFiles as $file)
        {
            //生成文件夹
            run("mkdir -p {$deployPath}/{$file}");
            //上传文件
            upload($file.'/', "{$deployPath}/{$file}");
        }
});

?>

//然后执行 验证链接服务器执行代码是否OK
dep test_run

//如果执行OK话 代码更新


在gitlab项目配置.gitlab-ci.yml文件
stages:
    - build
    - deploy

build:
  stage: build
  only:
    - develop
    - main
  artifacts:
    paths:
      - ./
  script:
    - pwd
    - cp -rf Application/Admin/* /data/web/trunk/Application/Admin/

deploy:
  stage: deploy
  only:
    - main
  script:
    - echo "=====start install====="
    - pwd
    - whoami
    - cd /data/web/trunk
    - dep test_run
Leave a Reply

Your email address will not be published. Required fields are marked *