失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 【Gitlab+Jenkins+Ansible】构建自动化部署

【Gitlab+Jenkins+Ansible】构建自动化部署

时间:2024-01-02 00:06:34

相关推荐

【Gitlab+Jenkins+Ansible】构建自动化部署

说明: Gitlab、Jenkins、生产服务器、测试服务器上都需要安装Git.

一、安装Gitlab

1.主机配置

IP: 10.10.10.105OS: CentOs7.5Gitlab版本:gitlab-ce-10.0.0-ce.0.el6.x86_64

2.关闭防火墙

systemctl stop firewalld

3.下载Gitlab

清华大学开源镜像站:

https://mirrors.tuna./gitlab-ce/

4.安装依赖项(可根据情况选择性操作)

yum install -y curl policycoreutils-python openssh-server openssh-clients cronielokkit -s http -s ssh

yum install postfixsystemctl start postfixchkconfig postfix on

5.安装Gitlab

rpm -ivh gitlab-ce-10.0.0-ce.0.el6.x86_64.rpm

6.配置Gitlab

因为Jenkins使用端口也是8080端口,我们需要对Gitlab的端口做修改。分别改为11000,11001,11002. 这个在/etc/gitlab/gitlab.rb文件中修改: 修改内容如下: 将

external_url ''

修改为

external_url 'http://10.10.10.102:11000'

unicorn['port'] = 8080

修改为

unicorn['port'] = 11001

prometheus['listen_address'] = '10.10.10.102:8081'

修改为

prometheus['listen_address'] = '10.10.10.102:11002'

每次重新配置,都需要执行gitlab-ctl reconfigure使之生效。

7.启动Gitlab

载入配置信息:

gitlab-ctl reconfigure

启动Gitlab:

gitlab-ctl start

常用管理命令:

gitlab-ctl startgitlab-ctl restartgitlab-ctl stopgitlab-ctl status

8.访问Gitlab

http://10.10.10.105:11000

访问上述地址即可打开Gitlab页面。首次登录时,需要修改root密码。

9.Gitlab其他信息

日志位置:/var/log/gitlab #可以查看访问日志以及报错日志等,供访问查看以及异常排查。

gitlab-ctl tail #查看所有日志gitlab-ctl tail nginx/gitlab_access.log #查看nginx访问日志

Gitlab仓库位置:

/var/opt/gitlab/git-data/repositories

查看Gitlab版本信息:

gitlab-rake gitlab:env:info

cat /opt/gitlab/embedded/service/gitlab-rails/VERSION

10.重置root密码

gitlab-rails console productionirb(main):001:0> user = User.where(id: 1).first=> #<User id: 1, email: "admin@", ...irb(main):002:0> user.password=12345678=> 12345678irb(main):003:0> user.password_confirmation=12345678 => 12345678irb(main):004:0> user.save!=> trueirb(main):005:0> quit

二、Gitlab汉化

1.停止Gitlab服务

gitlab-ctl stop

2.查看Gitlab版本

cat /opt/gitlab/embedded/service/gitlab-rails/VERSION 10.0.0 yum -y install git

3.克隆获取汉化版本库

cd /rootgit clone /xhang/gitlab.git

4.查看汉化版本

cat gitlab/VERSION 10.2.3

cd /root/gitlab/ git diff v10.0.0 v10.0.0-zh >/tmp/10.0.0-zh.diff

yum install patch -y patch -d /opt/gitlab/embedded/service/gitlab-rails -p1 < /tmp/10.0.0-zh.diff

5.启动和重新配置Gitlab

gitlab-ctl startgitlab-ctl reconfigure

三、升级Gitlab

1.关闭部分Gitlab服务

gitlab-ctl stop unicorngitlab-ctl stop sidekiqgitlab-ctl stop nginx

2.升级

rpm -Uvh gitlab-ce-10.0.0-ce.0.el6.x86_64.rpm

3.重新配置Gitlab

gitlab-ctl reconfigure

4.重启Gitlab

gitlab-ctl restart

四、安装Jenkins

参见:/xialiaoliao0911/p/8638495.html

五、安装Gitlab插件

1.首先登录Jenkins,点击“系统管理”>"插件管理"。在插件管理中可以看到“可更新”、“可选插件”、“已安装”插件。

2.我们切换到“可选插件”选项卡,在搜索框中输入gitlab,找到gitlab pulgin。选中点击安装。如下是已经安装好的Gitlab插件。

六、配置Gitlab插件

1.打开Gitlab,点击右上角头像下拉框中的“Setting”>"Account",复制“Private token”备用。

2.打开Jenkins,点击“系统管理”>"系统设置。

3.点击“配置”下拉框,选择Gitlab选项。

4.配置Gitlab.

Connection name: 填写一个有意义的名字

Gitlab host URL : 填写Gitlab的实际地址

然后点击“Add”>Jenkins.

在弹出框里,“类型” 选择“Gitlab API token”, API token 中输入之前复制的Private token.然后点击“添加”。

在选择刚才新建的Credentials:

设置完成后,点击“Test Connection” 来测试一下是否可以成功连接。显示“Success” 则说明测试成功。

之后点击“应用”后,再点击“保存”。

七、配置Git插件

1.打开Jenkins,点击“系统管理”>“系统设置”。

2.点击“配置”下拉框,选择“Git plugin”.

然后设置Git插件的全局配置。然后点击“应用”并“保存”。

注: 关于git的全局配置,这里说明一下。首先在git安装完成后,可以对git进行一些全局设置。刚才的user.name和user.email就是在git中设置的。

设置方法就是执行如下两条命令:

[root@CentOS7 ~]# git config --global user.name "Sakura"[root@CentOS7 ~]# git config --global user.email "122480579@"

查看配置信息:

[root@CentOS7 ~]# git config --listuser.name=Sakurauser.email=122480579@core.repositoryformatversion=0core.filemode=truecore.bare=falsecore.logallrefupdates=true

八、创建一个Jenkins Job

在Jenkins里,一个任务叫做一个job。一般我们的项目会有多个分支,比如开发分支和产品分支,我们可以对每一个分支都新建一个job.

比如,我们对开发分支创建一个测试的job,每次有代码提交就自动运行一次测试,对产品分支创建一个打包的job,每次有代码提交就运行打包任务。

不过在这里,我们只是单纯的创建一个job,来演示jenkins自动运行任务的过程。首先,点击“创建一个新任务”.

任务名称:根据任务内容起一个见名知意的名字。

然后选择“构建一个自由风格的软件项目”。之后点击“确定”。

九、生成访问Gitlab的ssh密钥

1.在Linux下生成ssh密钥

在Jenkins服务器的命令行输入如下命令来生成公钥和私钥。

[root@CentOS7 ~]# ssh-keygenGenerating public/private rsa key pair.Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa.Your public key has been saved in /root/.ssh/id_rsa.pub.The key fingerprint is:SHA256:XsMCl46+G81iIrIGR75xI8m0yElOLHESQmVNwcROS2E root@CentOS7.5-103The key's randomart image is:+---[RSA 2048]----+|+o.o*Eo||+ o .* . ||.+ + o o ||.+o o = . ||**.o . S +||o+O o. + o .||o..=..= + || +.. o + ||oo. |+----[SHA256]-----+

记录下私钥的存放路径以备用。

2. 复制公钥文件里的全部内容,然后打开Gitlab,找到SSH Keys. 然后将刚才复制的公钥文件内容粘贴进Key中。

Title : 自定义,起一个见名知意的名字。

然后点击“Add Key”。填写成功后,会在下方的“Your SSH keys”中显示已添加的Key.

添加后的结果:

十、配置Job

1.打开Jenkins,点击刚刚创建的Job的名称“deployfrontend”.

2.然后点击“配置”

3.配置Job的“源码管理”

(1)首先打开GitLab,新建一个Project,命名为monkey.

点击扳手图标,即可看到新建按钮。

新建成功后,效果如下:

(2)再在GitLab中,新建用户coldplay. 并设置密码为coldplay.

(3)在新建的Project加入成员coldplay.

首先点击扳手图标,查看所有Project.

然后点击需要添加的Project,这里是Administrator/monkey.

进入如下页面后,点击后边的Manage access.

添加成员用户,并设置角色权限。点击“Add to project”加入到Project.

(4)复制刚才在Gitlab中新建的Project的地址。

(5)在Jenkins中,选择“源码管理”>Git. 将Gitlab的项目地址填写到Repository URL中。然后点击“credentials”后面的“Add”按钮。

这里的Credentials后选择coldplay,并输入它的密码。

如果没报错,说明成功了,点击页面底部的“应用”。如果出错了,会在“Repository URL”和“Credentials”之间显示红色的错误信息。

Jenkins job默认对master分支进行构建,你也可以自定义分支。这要求你的Gitlab代码仓库中要存在这个分支,一般来说,就是要向代码仓库提交一次更改,请自行完成(Gitlab项目刚创建时是空的,一个分支也没有,这样的话,自动构建时会出错)。

4.配置Job的构建触发器

点击“构建触发器”,然后选择“轮询”SCM。这里我们可以设置每十五分钟轮询一次。

其他选项,大家可以根据实际情况设置。

5.配置Job的构建脚本

点击“构建”,然后选择“执行shell”(可根据实际情况选择)

之后,我们就可以设置我们需要执行的shell命令了。

6.配置构建后操作

根据实际情况可选择相应的操作。例如:邮件通知

十一、实例演示

1.需求说明

【服务器说明】

10.10.10.102:Gitlab服务器,这里记作A。

10.10.10.103:Jenkins服务器,这里记作B。

10.10.10.104:生产服务器,即需要部署程序的机器,这里记作C。

10.10.10.105:测试服务器,在该台服务器编写代码,这里记作D。

注:上述4台机器都需要安装Git.

Gitlab-->Jenkins ,Gitlab-->生产服务器,都做免密登录。

【需求】

在D机器上编写好的代码,可以push到A机器上。然后通过Jenkins自动将代码发布到C上。

2.操作步骤

(1)首先在Gitlab(10.10.10.102)上新建用户coldplay,新建项目monkey. 并将coldplay用户加入到monkey项目中;

Gitlab中新建的项目名称要和生产服务器上的项目名称保持一致,这里都叫monkey.

(2)然后打开Jenkins(10.10.10.103),新建任务monkey,并配置monkey项目地址;

(3)在生产服务器上(10.10.10.104)安装tomcat,并设置一个默认页。

在/usr/local/apache-tomcat-9.0.8/conf/server.xml中的如下位置新添加如下内容(红色字体部分):

注意docBase的位置要和你实际的地址相同。

<Host name="localhost" appBase="webapps"unpackWARs="true" autoDeploy="true"><!-- SingleSignOn valve, share authentication between web applicationsDocumentation at: /docs/config/valve.html --><!--<Valve className="org.apache.catalina.authenticator.SingleSignOn" />--><!-- Access log processes all example.Documentation at: /docs/config/valve.htmlNote: The pattern used is equivalent to using pattern="common" --><Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"prefix="localhost_access_log" suffix=".txt"pattern="%h %l %u %t &quot;%r&quot; %s %b" />#############################################add by guanyy#################################################<Context path="" docBase="/usr/local/apache-tomcat-9.0.8/webapps/monkey" debug="0" reloadable="true" />###########################################################################################################</Host>

在/usr/local/apache-tomcat-9.0.8/conf/web.xml中检查默认页设置(注意要和项目中的名字相同);

如下红色字体部分是设置多个默认页,你需要保证你的默认页的名字是如下文件的一个

<welcome-file-list> <welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file></welcome-file-list>

在/usr/local/apache-tomcat-9.0.8/conf/server.xml中修改端口为8090

<Connector port="8090" protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443" /><!-- A "Connector" using the shared thread pool--><!--<Connector executor="tomcatThreadPool"port="8090" protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443" />

(4)设置默认页(10.10.10.104)

在如下目录新建一个文件index.html(和前一步的名字保持一致),monkey可能不存在,需要新建;

/usr/local/apache-tomcat-9.0.8/webapps/monkey/index.html

index.html的内容如下:

[root@CentOS7 monkey]# more index.html <html><H1>Hello World!<br><H1></html>

设置完成后,启动tomcat,在浏览器输入http://10.10.10.104:8090会看到Hello World!

(5)在生产服务器上(10.10.10.104)生成公钥和私钥,并将公钥文件的内容粘贴到Gitlab(10.10.10.102)中的SSH Keys中.

(6)在测试服务器(10.10.10.105)上添加并push代码到Gitlab(10.10.10.102);

测试服务器上现有文件index.html。

#添加远程仓库到本地git remote add origin http://10.10.10.102:11000/root/monkey.git注:http://10.10.10.102:11000/root/monkey.git为远程仓库地址#添加文件git add index.html#提交文件git commit -m "the first commit"#将提交的代码push到远程仓库上git push -u origin master

注意:提交代码到远程仓库时,需要输入远程仓库的用户名和密码。同理,从远程仓库拉取代码到本地也需要用户名和密码。可以通过如下方式设置免密登录:

例如:本地测试服务器拉取的代码存放在/root目录下

#切换到/root目录cd /root#初始化git仓库git init#从远程拉取代码git clone http://10.10.10.102:11000/root/monkey.git#拉取代码后会在本地目录下生成一个隐藏文件夹.git#进入到.git目录并新建空文件.git-credentialscd /root/.gittouch .git-credentials#在.git-credentials中填入如下内容并保存:[root@CentOS7 .git]# more .git-credentials http://{coldplay}:{coldplay}@10.10.10.102:8090第一个coldplay表示的是gitlab的用户;第二个coldplay表示的是gitlab中coldplay用户的密码;@后面的10.10.10.102是Gitlab服务器的IP,8090是Gitlab使用的端口号;#在命令行执行如下命令:git config --global credential.helper store#至此,免密登录设置完毕!下次提交时还需要输入一次用户名和密码。下下次就不用输入用户名和密码啦!!!

(7)在生产服务器(10.10.10.104)添加Gitlab地址并拉取代码

#添加gitlab远程仓库地址git remote add origin http://10.10.10.102:11000/root/monkey.git#为保证拉取代码时不报冲突错误,建议将/usr/local/apache-tomcat-9.0.8/webapps下的monkey目录删除后再拉取#从远程仓库拉取代码git clone http://10.10.10.102:11000/root/monkey.git#拉取成功后,会在/usr/local/apache-tomcat-9.0.8/webapps目录下生成一个monkey目录#此时,生产服务器上的代码就变成最新的了!!

(8)配置Jenkins自动拉取

首先在生产服务器(10.10.10.104)上编写一个部署脚本deploy.sh

[root@CentOS7 script]# more /root/script/deploy.sh #!/bin/bashcd /usr/local/apache-tomcat-9.0.8/webapps/monkeygit pull

然后在Jenkins(10.10.10.103)的构建中输入如下命令,然后“应用”并“保存”。

ssh root@10.10.10.104 "sh -c /root/script/deploy.sh"

(9)至此,Jenkins每隔2分钟都会检查一下Gitlab,当有新代码提交到Gitlab中时,Jenkins就会调取deploy.sh将代码自动发布到生产服务器上。

3. 其他的触发构建方式

(1)使用在浏览器输入URL来触发构建,这里设置的token为StartDeploy.

当用户在浏览器中输入地址http://10.10.10.103:8080/jenkins/job/monkey/build?token=StartDeploy并回车后(刷新也可以)就开始构建!

(2)使用webhook,当Gitlab有更新时,就触发构建

首先打开Jenkins,将如下红框中的URL地址进行复制;打开Gitlab找到需要操作的项目monkey,点击Settings>Integrations,将上一步复制的URL粘贴到框中,然后点击“Add webhook”.添加完成后,会在下面显示已经添加的webhook. 我们点击Test>Push events进行验证。

上述验证过程中,可能会报403错误。

403错误解决方法可参考文档:/saysmy/archive/296681.html

================分割线===============================

下面我们换另一种webhook方式。

打开Jenkins,点击右上角的用户(这里是guanyy),然后点击“设置”点击“Add new Token”,然后输入当前Jenkins用户的密码,然后点击后面的Generate。这里就生成了一个api_token然后根据如下格式填写webhook的URL,把URL粘贴到Gitlab上,并Add webhook.

http://{username}:{api_token}@jenkins_ip:port/jenkins/project/项目名称

例如:

http://admin:11f3d0a5fdb7cdae3bfe6b28e8dc99ead1@10.10.10.103:8080/jenkins/project/monkey

找到添加好的webhook,点击Test>Push events,如果显示200,则说明测试成功。此时,我们向Gitlab提交新代码后,Jenkins就会自动进行构建操作!

十二、常见错误

1. Jenkins构建任务时报错:Host key verification failed.

说明:使用yum方式安装jenkins时,会自动创建jenkins用户和jenkins组。

如果从Jenkins向生产服务器做了免密登录,且可以使用ssh root@product_ip成功登录服务器。但构建时仍提示上述错误。就是和这个jenkins用户和组有关系。

【错误1】

在Jenkins中构建任务报错:

Started by user adminBuilding in workspace /var/lib/jenkins/workspace/DeployWebSite> git rev-parse --is-inside-work-tree # timeout=10Fetching changes from the remote Git repository> git config remote.origin.url http://192.168.10.189:8081/root/web.git # timeout=10Fetching upstream changes from http://192.168.10.189:8081/root/web.git> git --version # timeout=10using GIT_ASKPASS to set credentials > git fetch --tags --progress http://192.168.10.189:8081/root/web.git +refs/heads/*:refs/remotes/origin/*> git rev-parse refs/remotes/origin/master^{commit} # timeout=10> git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10Checking out Revision 734d97bbb476e9265fa533d12aae2f2a68a6d64a (refs/remotes/origin/master)> git config core.sparsecheckout # timeout=10> git checkout -f 734d97bbb476e9265fa533d12aae2f2a68a6d64aCommit message: "txt"> git rev-list --no-walk 734d97bbb476e9265fa533d12aae2f2a68a6d64a # timeout=10[DeployWebSite] $ /bin/sh -xe /tmp/jenkins8632079384544272773.sh+ ssh root@192.168.10.112 'sh -c /root/scripts/deployweb.sh'Host key verification failed.Build step 'Execute shell' marked build as failureFinished: FAILURE

【解决方法】

默认做了免密登录之后,会在/root/.ssh目录下生成公钥和私钥!

我们需要将/root/.ssh下的文件全部复制到/var/lib/jenkins/.ssh目录下(一般yum方式的安装的jenkins会有该目录)。

【错误2】

将/root/.ssh下的文件全部复制到/var/lib/jenkins/.ssh目录下后,报错:

Started by user adminBuilding in workspace /var/lib/jenkins/workspace/DeployWebSite> git rev-parse --is-inside-work-tree # timeout=10Fetching changes from the remote Git repository> git config remote.origin.url http://192.168.10.189:8081/root/web.git # timeout=10Fetching upstream changes from http://192.168.10.189:8081/root/web.git> git --version # timeout=10using GIT_ASKPASS to set credentials > git fetch --tags --progress http://192.168.10.189:8081/root/web.git +refs/heads/*:refs/remotes/origin/*> git rev-parse refs/remotes/origin/master^{commit} # timeout=10> git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10Checking out Revision 734d97bbb476e9265fa533d12aae2f2a68a6d64a (refs/remotes/origin/master)> git config core.sparsecheckout # timeout=10> git checkout -f 734d97bbb476e9265fa533d12aae2f2a68a6d64aCommit message: "txt"> git rev-list --no-walk 734d97bbb476e9265fa533d12aae2f2a68a6d64a # timeout=10[DeployWebSite] $ /bin/sh -xe /tmp/jenkins4724191024465664565.sh+ ssh root@192.168.10.112 'sh -c /root/scripts/deployweb.sh'Permission denied, please try again.Permission denied, please try again.Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).Build step 'Execute shell' marked build as failureFinished: FAILURE

【解决方法】

出现上述错误是由于没有将/var/lib/jenkins/.ssh目录下的文件属主用户和组修改为jenkins。修改一下即可。修改后的结果如下:

[root@web02 .ssh]# pwd/var/lib/jenkins/.ssh[root@web02 .ssh]# ll-rw------- 1 root root 1414 Jul 4 05:53 anaconda-ks.cfg-rw------- 1 jenkins jenkins 995 Aug 14 19:24 authorized_keys-rw------- 1 jenkins jenkins 1675 Aug 14 19:24 id_rsa-rw-r--r-- 1 jenkins jenkins 392 Aug 14 19:24 id_rsa.pub-rw-r--r-- 1 jenkins jenkins 176 Aug 14 19:24 known_hosts

2.在Gitlab中配置了webhook,且可以测试成功,显示:Hook Successfully executed. 手动构建也可以成功。但提交新代码到Gitlab上后却不触发webhook.

【解决方法】

这个可能和Gitlab版本有关系。我之前使用Gitlab7.10.4配置webhook,始终无法触发webhook. 之后将Gitlab版本升级到8.6.7后。再次提交新代码到Gitlab后webhook就能自动触发了。

如果觉得《【Gitlab+Jenkins+Ansible】构建自动化部署》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。