使用 Gitlab+Jenkins 实现自动化构建

使用 Gitlab+Jenkins 实现自动化构建

准备工作

Jenkins 密钥配置

  • 设置jenkins的shell终端为/bin/bash
1
2
[root@caoxl ~]# grep jenkins /etc/passwd
jenkins:x:990:987:Jenkins Automation Server:/var/lib/jenkins:/bin/false
  • 登录到jenkins用户生成密钥
1
2
3
4
[root@caoxl ~]# su - jenkins
Last login: Wed Jun 3 15:27:02 CST 2020 on pts/3
[root@caoxl ~]# ssh-keygen -t rsa
[root@caoxl ~]# cat ~/.ssh/id_rsa.pub
  • 添加公钥到gitlab服务器,用来clone代码
  • 添加完成之后从gitlab服务器clone下自己的工程,会在.ssh/known_hosts添加gitlab服务器记录
  • 添加公钥到jenkins服务器root用户,用来执行部署脚本
1
2
3
4
5
6
7
8
9
10
11
// 输入以下, 并且输入服务器密码即可
[root@caoxl ~]# ssh-copy-id -i .ssh/id_rsa.pub root@47.107.169.233
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@47.107.169.233's password:

Number of key(s) added: 1

Now try logging into the machine, with: "ssh 'root@47.107.169.233'"
and check to make sure that only the key(s) you wanted were added.

准备一个脚本

script
1
2
3
[root@caoxl deploy]# cat /shell/deploy/jenkins_deploy.sh
#!/bin/bash
echo "部署脚本被执行"

注意:如果是生产配置,直接把这个脚本换成对应项目的上线脚本即可,jenkins配置无须修改。

  • 正式脚本

/bin/sh /shell/deploy/jenkins_deploy.sh ${WORKSPACE} ${JOB_NAME} ${BUILD_NUMBER}

1
2
3
4
5
6
7
8
cd /${WORKSPACE}
tar -zcvf /var/www/code_backup/${JOB_NAME}_${BUILD_NUMBER}.tar.gz ${JOB_NAME}
tar -zcvf /var/www/code_backup/${JOB_NAME}_${BUILD_NUMBER}_bak.tar.gz /var/www/lumen6.caoxl.com
mv /var/www/code_backup/${JOB_NAME}_${BUILD_NUMBER}.tar.gz /var/www/
cd /var/www/
tar -zxvf ${JOB_NAME}_${BUILD_NUMBER}.tar.gz
rm ${JOB_NAME}_${BUILD_NUMBER}.tar.gz
chown -Rf www:www *

Jenkins 触发式构建

用于开发环境部署,开发人员push代码或者合并代码到gitlab项目的master分支,jenkins就部署代码到对应服务器。

Jenkins 参数化构建

用于测试环境预上线环境部署,开发push代码或者合并代码到gitlab项目的master分支之后,并不会部署代码,而是需要登录到jenkins的web界面,点击构建按钮,传入对应的参数(比如参数需要构建的tag,需要部署的分支)然后才会部署。

Jenkins 定时构建

用于APP自动打包,定时构建是在参数化构建的基础上添加的,开发人员可以登录jenkins手动传入tag进行打包,如果不手动打包,那么jenkins就每天凌晨从gitlab拉取最新的APP代码打包。

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2023 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :