Jenkins pipeline 是一套插件,支持將連續輸送管道實施和整合到Jenkins。Pipeline提供了一組可擴展的工具,用於經過管道DSL爲代碼建立簡單到複雜的傳送流水線。他目前支持jenkins 2.x以上版本。pipeline是由groovy語言編寫html
參考:https://www.cnblogs.com/YatHo/p/7856556.htmljava
pipeline分爲兩種一種爲jenkinsfile使用,一種直接在網頁界面中輸入腳本內容,本文介紹第二種使用方法python
新建一個項目:nginx
使用jenkins Groovy腳本實現源碼拉取、源碼打包、包上傳與部署git
首先源碼拉取:web
因爲使用groovy語言,須要先生成pipeline能夠用的git連接地址,生成方法以下:shell
連接格式以下:vim
checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'b96e05e1-193f-4e06-9195-fcaf31f579e9', url: 'http://10.10.10.217/test/test.git']]])
須要將此連接加到pipeline腳本里api
編寫pipeline腳本(本示例只作了拉取和打包):緩存
pipeline { agent any
//此處爲環境變量設置,定義變量須要用加上 "def" environment { def ITEMNAME = "flagship" def SRCCODE_DIR = "/root/.jenkins/workspace/test_pipeline/flagship-bigdata/" }
//此處便可開始進行代碼部署操做 stages { stage('代碼拉取並打包'){ steps { echo "checkout from ${ITEMNAME}"
//生成的git連接地址 checkout ([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'b96e05e1-193f-4e06-9195-fcaf31f579e9', url: 'http://10.10.10.217/test/test.git']]]) echo "開始打包 "
//執行shell命令 sh 'export JAVA_HOME=/usr/local/java/jdk1.7.0_80 && cd $SRCCODE_DIR && mvn clean install -DskipTests -Denv=beta' } } } }
其餘部署操做按照stage{ steps{} }的格式進行編寫便可
構建完成後如圖所示(查看log)
建議方案:jenkins+gitlab+ansible(playbook)
語法示例:
https://jenkins.io/doc/book/pipeline/
https://jenkins.io/doc/book/pipeline/syntax/#stage
上圖中①表示定義執行jenkins pipeline等流程的節點
pipeline腳本內容
pipeline { agent any environment { def maven_home = "/usr/local/maven3.5/" def ITEMNAME = "hzjry" } stages { stage('代碼拉取並打包'){ steps { echo "checkout from ${ITEMNAME}" checkout([$class: 'GitSCM', branches: [[name: '*/${branch}']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '9a3eb706-aa23-4a07-8e00-188d91fbd98d', url: 'http://10.10.10.217/hz-cloud/hz-cloud.git']]]) echo "開始打包 " sh 'export JAVA_HOME=/usr/local/java/jdk1.7.0_80 && cd ${WORKSPACE} && /usr/local/maven3.5/bin/mvn clean install -Dmaven.test.skip=true -Pbeta' } } stage('部署項目'){ steps { echo "上傳部署" sh 'ansible-playbook -i /etc/ansible/hosts /etc/ansible/hzjry/main.yml -e "host=hzjry_admin"' } } } }
說明:由於構建的時候定義了參數化構建,因此在選定源碼倉庫分支的時候用了變量(branch),因此生成的pipeline script裏的git 地址爲 ${branch}
ansible-playbook內容
[root@bogon hzjry]# tree roles/tomcat roles/tomcat ├── files │ └── index.html ├── handlers │ └── main.yaml ├── tasks │ └── main.yml ├── templates │ ├── a.txt │ ├── b.txt │ └── nginx.conf.j2 └── vars └── main.yml [root@bogon hzjry]# cat main.yml --- - hosts: "{{ host }}" gather_facts: False roles: # - init - tomcat [root@bogon tomcat]# cat tasks/main.yml - name: 查看目錄 shell: ls /opt/tomcat-7/webapps | grep admin register: admin_dir ignore_errors: True - name: 建立目錄 file: "path={{ tomcat_dir }}/webapps/admin state=directory" when: admin_dir|failed - name: 關閉tomcat shell: chdir={{ tomcat_dir }}/bin nohup ./shutdown.sh & - name: 檢查進程是否還存在 shell: ps -ef |grep {{ tomcat_dir }}|grep -v "grep"|awk '{print $2}' register: pid_exist ignore_errors: True - name: 進程存在就殺死 shell: ps -ef |grep {{ tomcat_dir }}|grep -v "grep"|awk '{print $2}'|xargs kill -9 when: pid_exist|success #- name: backup old code # shell: chdir={{ tomcat_root }}/webapps tar -czf /root/xxx_$(date -d "today" +"%Y%m%d_%H%M%S").tar.gz - name: clean cache|清除緩存 shell: chdir={{ tomcat_dir }} rm -rf work - name: 解壓war包 unarchive: src={{ war_dir }}/cloud-admin-0.0.1-SNAPSHOT.war dest={{ tomcat_dir }}/webapps/admin copy=yes # when: {{ service }}="admin" - name: 啓動tomcat shell: export {{ item }} && chdir={{ tomcat_dir }}/bin nohup ./startup.sh & with_items: - JAVA_HOME=/usr/local/java/jdk1.8.0_151 - CLASSPATH=.:${JAVA_HOME}/jre/lib/rt.jar:${JAVA_HOME}/lib/dt.jar:${JAVA_HOME}/lib/tools.jar - PATH=$PATH:${JAVA_HOME}/bin
[root@bogon tomcat]# cat vars/main.yml --- tomcat_dir: /opt/tomcat-7 war_dir: /var/lib/jenkins/workspace/test-pipeline/hz-cloud-management/cloud-admin/target/
jenkins構建時,在部署上傳steps處報錯,以下所示:
fatal: [10.20.200.224]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", "unreachable": true} [WARNING]: Failure using method (v2_runner_on_unreachable) in callback plugin (</usr/lib/python2.7/site- packages/ansible/plugins/callback/log_plays.CallbackModule object at 0x1e32fd0>): [Errno 13] Permission denied: u'/var/log/ansible/hosts/10.20.200.224' [WARNING]: Could not create retry file '/etc/ansible/hzjry/main.retry'. [Errno 13] Permission denied: u'/etc/ansible/hzjry/main.retry'
可是在服務器終端頁面執行ansible-playbook則沒有出現問題,推測多是權限問題
jenkins yum安裝,在執行部署的時候默認使用jenkins用戶進行部署,默認jenkins用戶是沒法鏈接遠程服務器的,因此須要配置鏈接認證
解決方法一
//修改Jenkins配置文件 # 打開配置文件 vim /etc/sysconfig/jenkins # 修改$JENKINS_USER,並去掉當前行註釋 $JENKINS_USER="root" //修改Jenkins相關文件夾用戶權限 chown -R root:root /var/lib/jenkins chown -R root:root /var/cache/jenkins chown -R root:root /var/log/jenkins //重啓Jenkins服務並檢查運行Jenkins的用戶是否已經切換爲root # 重啓Jenkins(如果其餘方式安裝的jenkins則重啓方式略不一樣)
service jenkins restart#
//查看Jenkins進程所屬用戶
ps -ef | grep jenkins #若顯示爲root用戶,則表示修改完成機修
繼續執行可部署成功
解決方法二
配置jenkins的用戶終端,修改jenkins用戶shell爲bash
jenkins:x:989:985:Jenkins Automation Server:/var/lib/jenkins:/bin/bash
配置jenkins用戶鏈接ssh免祕鑰
[root@bogon tomcat]# su jenkins bash-4.2$ ssh-keygen -t rsa bash-4.2$ ssh-copy-id root@10.20.200.224
修改ansible主機組信息
cat /etc/ansible/hosts [hzjry_admin] 10.20.200.224 ansible_ssh_private_key_file=/var/lib/jenkins/.ssh/id_rsa ansible_ssh_user='root'
繼續執行