【Gitlab+Jenkins+Ansible】構建自動化部署


說明: Gitlab、Jenkins、生產服務器、測試服務器上都需要安裝Git.

 

 

 一、安裝Gitlab

1.主機配置

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

 

2.關閉防火牆

systemctl stop firewalld

 

3.下載Gitlab

清華大學開源鏡像站:

https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/

 

4.安裝依賴項(可根據情況選擇性操作)

yum install -y curl policycoreutils-python openssh-server openssh-clients cronie
lokkit -s http -s ssh
yum install postfix
systemctl start postfix
chkconfig 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 'http://gitlab.example.com'

修改為

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 start
gitlab-ctl restart
gitlab-ctl stop
gitlab-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 production

irb(main):001:0> user = User.where(id: 1).first
    => #<User id: 1, email: "admin@example.com", ...
irb(main):002:0> user.password=12345678
    => 12345678
irb(main):003:0> user.password_confirmation=12345678
    => 12345678
irb(main):004:0> user.save!
    => true
irb(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  /root
git clone https://gitlab.com/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 start
gitlab-ctl reconfigure

 

 

三、升級Gitlab

1.關閉部分Gitlab服務

 

gitlab-ctl stop unicorn
gitlab-ctl stop sidekiq
gitlab-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

參見:https://www.cnblogs.com/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@qq.com"

      查看配置信息:

[root@CentOS7 ~]# git config --list
user.name=Sakura
user.email=122480579@qq.com
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true

 

八、創建一個Jenkins Job

 

在Jenkins里,一個任務叫做一個job。一般我們的項目會有多個分支,比如開發分支和產品分支,我們可以對每一個分支都新建一個job.

比如,我們對開發分支創建一個測試的job,每次有代碼提交就自動運行一次測試,對產品分支創建一個打包的job,每次有代碼提交就運行打包任務。

 

不過在這里,我們只是單純的創建一個job,來演示jenkins自動運行任務的過程。首先,點擊“創建一個新任務”.

 任務名稱:根據任務內容起一個見名知意的名字。

然后選擇“構建一個自由風格的軟件項目”。之后點擊“確定”。

 

 

 

九、生成訪問Gitlab的ssh密鑰

1.在Linux下生成ssh密鑰

在Jenkins服務器的命令行輸入如下命令來生成公鑰和私鑰。

[root@CentOS7 ~]# ssh-keygen
Generating 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-103
The key's randomart image is:
+---[RSA 2048]----+
|+o.o*Eo          |
|+ o .*   .       |
|.+  + o o        |
|.+o  o = .       |
|**.o  . S +      |
|o+O o. + o .     |
|o..=..= +        |
| +.. o +         |
|o     o.         |
+----[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 applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: 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-credentials
cd /root/.git
touch .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/bash

cd  /usr/local/apache-tomcat-9.0.8/webapps/monkey
git 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錯誤解決方法可參考文檔:http://doc.okbase.net/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 admin
Building in workspace /var/lib/jenkins/workspace/DeployWebSite
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url http://192.168.10.189:8081/root/web.git # timeout=10
Fetching upstream changes from http://192.168.10.189:8081/root/web.git
 > git --version # timeout=10
using 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=10
Checking out Revision 734d97bbb476e9265fa533d12aae2f2a68a6d64a (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 734d97bbb476e9265fa533d12aae2f2a68a6d64a
Commit 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 failure
Finished: FAILURE

 

【解決方法】

默認做了免密登錄之后,會在/root/.ssh目錄下生成公鑰和私鑰!

我們需要將/root/.ssh下的文件全部復制到/var/lib/jenkins/.ssh目錄下(一般yum方式的安裝的jenkins會有該目錄)。

 

【錯誤2】

將/root/.ssh下的文件全部復制到/var/lib/jenkins/.ssh目錄下后,報錯:

Started by user admin
Building in workspace /var/lib/jenkins/workspace/DeployWebSite
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url http://192.168.10.189:8081/root/web.git # timeout=10
Fetching upstream changes from http://192.168.10.189:8081/root/web.git
 > git --version # timeout=10
using 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=10
Checking out Revision 734d97bbb476e9265fa533d12aae2f2a68a6d64a (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 734d97bbb476e9265fa533d12aae2f2a68a6d64a
Commit 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 failure
Finished: 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就能自動觸發了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM