Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 知乎專欄 | 視頻教程 | About

第 6 章 Jenkins

目錄

6.1. 安裝 Jenkins
6.1.1. OSCM 一鍵安裝
6.1.2. Mac
6.1.3. CentOS
6.1.4. Ubuntu
6.1.5. Docker
6.1.6. Minikube
6.2. 配置 Jenkins
6.3. Jenkinsfile
6.3.1. Jenkinsfile - Declarative Pipeline
6.3.1.1. stages
6.3.1.2. script
6.3.1.3. junit
6.3.1.4. withEnv
6.3.1.5. parameters
6.3.1.6. options
6.3.1.7. triggers
6.3.1.8. tools
6.3.1.9. post
6.3.1.10. when 條件判斷
6.3.1.11. 拋出錯誤
6.3.1.12. withCredentials
6.3.1.12.1. token
6.3.1.13. withMaven
6.3.1.14. isUnix() 判斷操作系統類型
6.3.1.15. Jenkins pipeline 中使用 sshpass 實現 scp, ssh 遠程運行
6.3.1.15.1. 後台運行
6.3.2. Jenkinsfile - Scripted Pipeline
6.3.2.1. git
6.3.2.2. 切換 JDK 版本
6.3.2.3. groovy
6.3.2.4. Groovy code
6.3.2.4.1. Groovy 函數
6.3.2.5. Ansi Color
6.3.2.6. 寫檔案操作
6.3.2.7. modules 實現模組
6.3.2.8. docker
6.3.2.9. input
6.3.2.10. if 條件判斷
6.3.2.11. Docker
6.3.2.12. conditionalSteps
6.3.2.13. nexus
6.3.3. 設置環境變數
6.3.3.1. 系統環境變數
6.3.4. agent
6.3.4.1. label
6.3.4.2. docker
6.3.4.2.1. 指定docker 鏡像
6.3.4.2.2. args 參數
6.3.4.2.3. Docker outside of Docker (DooD)
6.3.4.2.4. 掛在宿主主機目錄
6.3.4.2.5. 構建鏡像
6.3.4.3. Dockerfile
6.3.5. Steps
6.3.5.1. parallel 平行執行
6.3.5.2. echo
6.3.5.3. catchError 捕獲錯誤
6.3.5.4. 睡眠
6.3.5.5. 限制執行時間
6.3.5.6. 時間截
6.3.6. 版本控制
6.3.6.1. checkout
6.3.6.2. Git
6.3.7. 節點與過程
6.3.7.1. sh
6.3.7.2. Windows 批處理腳本
6.3.7.3. 分配工作空間
6.3.7.4. node
6.3.8. 工作區
6.3.8.1. 變更目錄
6.3.8.2. 判斷檔案是否存在
6.3.8.3. 分配工作區
6.3.8.4. 清理工作區
6.3.8.5. 遞歸刪除目錄
6.3.8.6. 寫檔案
6.3.8.7. 讀檔案
6.4. Jenkins Job DSL / Plugin
6.5. Jenkins Plugin
6.5.1. Blue Ocean
6.5.2. Locale Plugin (國際化插件)
6.5.3. github-plugin 插件
6.5.4. Docker
6.5.4.1. 設置 Docker 主機和代理
6.5.4.2. 持久化
6.5.5. JaCoCo
6.5.5.1. Pipeline
6.5.6. SSH Pipeline Steps
6.5.7. Rancher
6.5.8. Kubernetes 插件
6.5.8.1. Kubernetes
6.5.8.2. Kubernetes :: Pipeline :: Kubernetes Steps
6.5.8.3. Kubernetes Continuous Deploy
6.5.8.4. Kubernetes Cli
6.5.9. HTTP Request Plugin
6.5.10. Skip Certificate Check plugin
6.5.11. Android Sign Plugin
6.6. Jenkinsfile Pipeline Example
6.6.1. Maven 子模組範例
6.6.2. 使用指定鏡像構建
6.6.3. 命令行製作 Docker 鏡像
6.6.4. Yarn
6.6.5. Android

6.1. 安裝 Jenkins

6.1.1. OSCM 一鍵安裝

			
yum install -y java-1.8.0-openjdk			
curl -s https://raw.githubusercontent.com/oscm/shell/master/project/jenkins/jenkins.sh | bash
			
			

6.1.2. Mac

使用 pkg 方式安裝,預設路徑是 /Applications/Jenkins/jenkins.war

			
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home
java -jar jenkins.war --httpPort=8080
			
			

瀏覽器訪問:http://localhost:8080

查看預設密碼 /Users/neo/.jenkins/secrets/initialAdminPassword

			
neo@MacBook-Pro ~ % cat /Users/neo/.jenkins/secrets/initialAdminPassword
6c7369afc6c1414586b6644657dd655a		
			
			

下載 cloudbees 插件

			
neo@MacBook-Pro ~ % cd ~/.jenkins/plugins
neo@MacBook-Pro ~/.jenkins/plugins % wget ftp://ftp.icm.edu.pl/packages/jenkins/plugins/cloudbees-folder//6.7/cloudbees-folder.hpi			
			
			

重啟 Jenkens http://localhost:8080/restart

複製上面的密碼,粘貼到瀏覽器中。

卸載 Jenkens

			
sudo rm -rf /var/root/.jenkins ~/.jenkins
sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins "/Library/Application Support/Jenkins" /Library/Documentation/Jenkins

sudo rm -rf /Users/Shared/Jenkins
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
sudo rm -f /etc/newsyslog.d/jenkins.conf
pkgutil --pkgs | grep 'org\.jenkins-ci\.' | xargs -n 1 sudo pkgutil --forget
			
			

由於我的Mac 模式是 JDK 11,所以需要制定 JAVA_HOME 到 JDK 1.8,否則提示

			
Dec 27, 2018 9:20:33 AM Main main
SEVERE: Running with Java class version 55.0, but 52.0 is required.Run with the --enable-future-java flag to enable such behavior. See https://jenkins.io/redirect/java-support/
java.lang.UnsupportedClassVersionError: 55.0
	at Main.main(Main.java:139)

Jenkins requires Java 8, but you are running 11+28 from /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
java.lang.UnsupportedClassVersionError: 55.0
	at Main.main(Main.java:139)		
			
			

6.1.3. CentOS

			
wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key

yum install -y jenkins			
			
			

cat /etc/sysconfig/jenkins

			
## Path:        Development/Jenkins
## Description: Jenkins Automation Server
## Type:        string
## Default:     "/var/lib/jenkins"
## ServiceRestart: jenkins
#
# Directory where Jenkins store its configuration and working
# files (checkouts, build reports, artifacts, ...).
#
JENKINS_HOME="/var/lib/jenkins"

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Java executable to run Jenkins
# When left empty, we'll try to find the suitable Java.
#
JENKINS_JAVA_CMD=""

## Type:        string
## Default:     "jenkins"
## ServiceRestart: jenkins
#
# Unix user account that runs the Jenkins daemon
# Be careful when you change this, as you need to update
# permissions of $JENKINS_HOME and /var/log/jenkins.
#
JENKINS_USER="jenkins"

## Type:        string
## Default: "false"
## ServiceRestart: jenkins
#
# Whether to skip potentially long-running chown at the
# $JENKINS_HOME location. Do not enable this, "true", unless
# you know what you're doing. See JENKINS-23273.
#
#JENKINS_INSTALL_SKIP_CHOWN="false"

## Type: string
## Default:     "-Djava.awt.headless=true"
## ServiceRestart: jenkins
#
# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true"

## Type:        integer(0:65535)
## Default:     8080
## ServiceRestart: jenkins
#
# Port Jenkins is listening on.
# Set to -1 to disable
#
JENKINS_PORT="8080"

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# IP address Jenkins listens on for HTTP requests.
# Default is all interfaces (0.0.0.0).
#
JENKINS_LISTEN_ADDRESS=""

## Type:        integer(0:65535)
## Default:     ""
## ServiceRestart: jenkins
#
# HTTPS port Jenkins is listening on.
# Default is disabled.
#
JENKINS_HTTPS_PORT=""

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Path to the keystore in JKS format (as created by the JDK 'keytool').
# Default is disabled.
#
JENKINS_HTTPS_KEYSTORE=""

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Password to access the keystore defined in JENKINS_HTTPS_KEYSTORE.
# Default is disabled.
#
JENKINS_HTTPS_KEYSTORE_PASSWORD=""

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# IP address Jenkins listens on for HTTPS requests.
# Default is disabled.
#
JENKINS_HTTPS_LISTEN_ADDRESS=""


## Type:        integer(1:9)
## Default:     5
## ServiceRestart: jenkins
#
# Debug level for logs -- the higher the value, the more verbose.
# 5 is INFO.
#
JENKINS_DEBUG_LEVEL="5"

## Type:        yesno
## Default:     no
## ServiceRestart: jenkins
#
# Whether to enable access logging or not.
#
JENKINS_ENABLE_ACCESS_LOG="no"

## Type:        integer
## Default:     100
## ServiceRestart: jenkins
#
# Maximum number of HTTP worker threads.
#
JENKINS_HANDLER_MAX="100"

## Type:        integer
## Default:     20
## ServiceRestart: jenkins
#
# Maximum number of idle HTTP worker threads.
#
JENKINS_HANDLER_IDLE="20"

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Pass arbitrary arguments to Jenkins.
# Full option list: java -jar jenkins.war --help
#
JENKINS_ARGS=""
			
			

Nginx 配置

			
[root@netkiller ~]# cat /etc/nginx/conf.d/jk.netkiller.cn.conf 
server {
    listen       80;
    server_name  jk.netkiller.cn;

    charset utf-8;

    location / {
    	proxy_pass   http://127.0.0.1:8080;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
			
			

查看管理員密碼

			
cat /var/lib/jenkins/secrets/initialAdminPassword			
			
			

6.1.4. Ubuntu

			
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
deb https://pkg.jenkins.io/debian-stable binary/

sudo apt-get update
sudo apt-get install jenkins			
			
			

6.1.5. Docker

https://github.com/jenkinsci/docker/blob/master/README.md

8080連接埠是jenkins的連接埠,5000連接埠是master和slave通信連接埠

			
docker pull jenkins/jenkins:lts			
docker run -p 8080:8080 -p 50000:50000 --name jenkins jenkins/jenkins:lts
			
			

首次啟動,不要使用 -d 參數,如果使用了 -d 參數可以通過docker logs -f jenkins查看控制台的密碼

docker-compose 配置檔案

			
version: '2'

services:
  jenkins:
    container_name: jenkins-lts
    ports: # 連接埠映射,9001為宿主機上的連接埠,相應的8080是容器運行起來時候jenkins服務的連接埠
      - 9001:8080
      - 50000:50000
    image: jenkins/jenkins:lts # 指定運行用哪一個鏡像來運行容器
    volumes:
      - /home/jenkins/jenkins_home:/var/jenkins_home # 掛載指令,目的在於銷毀容器時,並不影響jenkins數據			
			
			

6.1.6. Minikube

創建 jenkins-namespace.yaml

			
apiVersion: v1
kind: Namespace
metadata:
  name: jenkins-project
			
			

創建命名空間

			
$ kubectl create -f jenkins-namespace.yaml
			
			

創建 jenkins-volume.yaml

			
apiVersion: v1
kind: PersistentVolume
metadata:
  name: jenkins-pv
  namespace: jenkins-project
spec:
  storageClassName: jenkins-pv
  accessModes:
    - ReadWriteOnce
  capacity:
    storage: 20Gi
  persistentVolumeReclaimPolicy: Retain
  hostPath:
    path: /opt/jenkins-volume/	
			
			

創建卷

			
$ kubectl create -f jenkins-volume.yaml
persistentvolume “jenkins-pv” created			
			
			

創建 jenkins-values.yaml 檔案

			
# Default values for jenkins.
# This is a YAML-formatted file.
# Declare name/value pairs to be passed into your templates.
# name: value

## Overrides for generated resource names
# See templates/_helpers.tpl
# nameOverride:
# fullnameOverride:

Master:
  Name: jenkins-master
  Image: "jenkins/jenkins"
  ImageTag: "2.141"
  ImagePullPolicy: "Always"
  Component: "jenkins-master"
  UseSecurity: true
  AdminUser: admin
  # AdminPassword: <defaults to random>
  Cpu: "200m"
  Memory: "256Mi"
  ServicePort: 8080
  # For minikube, set this to NodePort, elsewhere use LoadBalancer
  # <to set explicitly, choose port between 30000-32767>
  ServiceType: NodePort
  NodePort: 32000
  ServiceAnnotations: {}
  ContainerPort: 8080
  # Enable Kubernetes Liveness and Readiness Probes
  HealthProbes: true
  HealthProbesTimeout: 60
  SlaveListenerPort: 50000
  LoadBalancerSourceRanges:
    - 0.0.0.0/0
  # List of plugins to be install during Jenkins master start
  InstallPlugins:
    - kubernetes:1.12.4
    - workflow-aggregator:2.5
    - workflow-job:2.24
    - credentials-binding:1.16
    - git:3.9.1
    - greenballs:1.15
  # Used to approve a list of groovy functions in pipelines used the script-security plugin. Can be viewed under /scriptApproval
  ScriptApproval:
    - "method groovy.json.JsonSlurperClassic parseText java.lang.String"
    - "new groovy.json.JsonSlurperClassic"
    - "staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods leftShift java.util.Map java.util.Map"
    - "staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods split java.lang.String"
  CustomConfigMap: false
  NodeSelector: {}
  Tolerations: {}

Agent:
  Enabled: true
  Image: jenkins/jnlp-slave
  ImageTag: 3.10-1
  Component: "jenkins-slave"
  Privileged: false
  Cpu: "200m"
  Memory: "256Mi"
  # You may want to change this to true while testing a new image
  AlwaysPullImage: false
  # You can define the volumes that you want to mount for this container
  # Allowed types are: ConfigMap, EmptyDir, HostPath, Nfs, Pod, Secret
  volumes:
    - type: HostPath
      hostPath: /var/run/docker.sock
      mountPath: /var/run/docker.sock
  NodeSelector: {}

Persistence:
  Enabled: true
  ## A manually managed Persistent Volume and Claim
  ## Requires Persistence.Enabled: true
  ## If defined, PVC must be created manually before volume will be bound
  # ExistingClaim:
  ## jenkins data Persistent Volume Storage Class
  StorageClass: jenkins-pv

  Annotations: {}
  AccessMode: ReadWriteOnce
  Size: 20Gi
  volumes:
  #  - name: nothing
  #    emptyDir: {}
  mounts:
  #  - mountPath: /var/nothing
  #    name: nothing
  #    readOnly: true

NetworkPolicy:
  # Enable creation of NetworkPolicy resources.
  Enabled: false
  # For Kubernetes v1.4, v1.5 and v1.6, use 'extensions/v1beta1'
  # For Kubernetes v1.7, use 'networking.k8s.io/v1'
  ApiVersion: networking.k8s.io/v1

## Install Default RBAC roles and bindings
rbac:
  install: true
  serviceAccountName: default
  # RBAC api version (currently either v1beta1 or v1alpha1)
  apiVersion: v1beta1
  # Cluster role reference
  roleRef: cluster-admin			
			
			

使用 helm 安裝 jenkins

			
$ cd ~/minikube-helm-jenkins
$ helm init
$ helm install --name jenkins -f helm/jenkins-values.yaml stable/jenkins --namespace jenkins-project
			
			

查看 jenkins 密碼

			
$ printf $(kubectl get secret --namespace jenkins-project jenkins -o jsonpath="{.data.jenkins-admin-password}" | base64 --decode);echo