Jenkins Pipeline脚本

1. pipeline-java-ansible-tomcat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
pipeline {
agent {
label "web2"
}
environment {
gitlab_address = "http://192.168.64.17:100443/microservice/demo.git"
gitlab_auth = "d09717ec-47c2-48f2-9c1c-f182b4589e74"
ansible_ssh_auth = "84ea22bc-c2c6-4f8f-88bb-9ed885819f9e"
}
parameters {
gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '请选择要发布的分支名称', name: 'selectBranch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH'
choice choices: ['webservers1', 'webservers2', 'webservers3'], description: '灰度发布策略,分批次部署', name: 'ENV'
}
triggers {
pollSCM('*/1 * * * *')
}
stages {
stage('拉取代码') {
steps {
checkout([$class: 'GitSCM', branches: [[name: "${params.selectBranch}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: "${gitlab_auth}", url: "${gitlab_address}"]]])
}
}
stage('编译构建') {
steps {
sh "/usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true"
}
}
stage('拷贝构建文件到远程主机并部署') {
steps {
// 读取连接Jenkins服务器用户名和密码
withCredentials([usernamePassword(credentialsId: '3e642bd1-ac6d-4c08-b01f-1125bf5bed9d', passwordVariable: 'password', usernameVariable: 'username')]) {
// ===========================================
sh """
###################### 主机清单文件 ############################
cat > /opt/jenkins_home/.hosts << EOF
[webservers1]
192.168.64.72
192.168.64.73
[webservers2]
192.168.64.72
[webservers3]
192.168.64.72
EOF
###################### Playbook文件 ############################
cat > /opt/jenkins_home/.playbook.yaml << "EOF"
- hosts: $ENV # Jenkins参数化变量
gather_facts: no
vars: # 定义playbook变量,下面{{}}引用这里的变量
workspace: $WORKSPACE # WORKSPACE和BUILD_NUMBER引用Jenkins变量
build_number: $BUILD_NUMBER
tomcat_dir: "/usr/local/tomcat" # 自定义变量
backup_dir: "/data/backup"
backup_filename: "demo-ROOT-\$(date +%F)-{{ build_number }}.war" # 格式:项目名-文件名-日期-构建编号
tasks:
- name: 推送部署包到远程服务器
copy: src="{{ item }}" dest={{ tomcat_dir }}/webapps
with_fileglob:
- "{{ workspace }}/target/*.war"
- name: 部署新程序并重启Tomcat
# 脚本中\$必须转义,否则会认为是Jenkins变量
shell: |
cd {{ tomcat_dir }}/webapps
mv ROOT.war {{ backup_dir }}/{{ backup_filename }}
mv *.war ROOT.war
pid=\$(ps -ef |grep {{ tomcat_dir }} |egrep -v 'grep' |awk '{print \$2}')
[ -n "\$pid" ] && kill -9 \$pid
export JAVA_HOME=/usr/local/jdk
nohup {{ tomcat_dir }}/bin/startup.sh
EOF
"""
// ===========================================
}
ansiblePlaybook(
playbook: '/opt/jenkins_home/.playbook.yaml',
inventory: '/opt/jenkins_home/.hosts',
credentialsId: "${ansible_ssh_auth}"
)
}
}
}
}

2. pipeline-java-docker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
pipeline {
agent {
label "web"
}
environment {
harbor_address = "192.168.64.17" //镜像仓库地址
project = "microservice" // 对应Harbor项目名
app_name = "demo" // 应用名称
image_name = "${harbor_address}/${project}/${app_name}:${selectBranch}-${BUILD_NUMBER}" // 镜像完整地址
gitlab_address = "http://192.168.64.17/microservice/demo.git" //
gitlab_auth = "96b60e82-a827-48ba-ba52-f5cab7e9aa49" // 拉取代码认证凭据ID
harbor_auth = "bba6b30d-cb39-454a-8a7a-832db3d18da4" // 推送镜像认证凭据ID
}
parameters {
gitParameter branch: '', branchFilter: 'origin/(.*)', defaultValue: 'master', description: '请选择要发布的分支名称', name: 'selectBranch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH'
}
stages {
stage('拉取代码'){
steps {
checkout([$class: 'GitSCM', branches: [[name: "${params.selectBranch}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: "${gitlab_auth}", url: "${gitlab_address}"]]])
}
}

stage('代码编译'){
steps {
sh "/usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true"
}
}

stage('构建镜像'){
steps {
withCredentials([usernamePassword(credentialsId: "${harbor_auth}", passwordVariable: 'password', usernameVariable: 'username')]) {
sh """
echo '
FROM tomcat
ADD target/*.war /usr/local/tomcat/webapps/ROOT.war
' > Dockerfile
docker build -t ${image_name} .
docker login -u ${username} -p '${password}' ${harbor_address}
docker push ${image_name}
"""
}
}
}

stage('部署到Docker'){
steps {
sh """
docker rm -f java-demo |true
docker container run -d --name java-demo -p 88:8080 ${image_name}
"""
}
}
}
}

3. pipeline-java-shell-tomcat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
pipeline {
agent any
environment {
gitlab_address = "http://192.168.64.17/microservice/demo.git"
gitlab_auth = "96b60e82-a827-48ba-ba52-f5cab7e9aa49"
}
parameters {
gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '请选择要发布的分支名称', name: 'selectBranch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH'
}
triggers {
pollSCM('*/1 * * * *')
}
stages {
stage('拉取代码') {
steps {
checkout([$class: 'GitSCM', branches: [[name: "${params.selectBranch}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: "${gitlab_auth}", url: "${gitlab_address}"]]])
}
}
stage('编译构建') {
steps {
sh "/usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true"
}
}
stage('拷贝构建文件到远程主机并部署') {
steps {
sshPublisher(publishers: [sshPublisherDesc(configName: '192.168.31.73', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''# 备份已部署的程序
tomcat=/usr/local/tomcat
cd $tomcat/webapps
mv ROOT.war /data/backup/ROOT-$(date +%F-%T).war
# 部署新程序并重启Tomcat
mv *.war ROOT.war
pid=$(ps -ef |grep $tomcat |egrep -v \'grep\' |awk \'{print $2}\')
export JAVA_HOME=/usr/local/jdk
[ -n "$pid" ] && kill -9 $pid
/usr/local/tomcat/bin/startup.sh
''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '$JOB_NAME', remoteDirectorySDF: false, removePrefix: 'target', sourceFiles: 'target/*.war')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
}
}
}
}

4. rollback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
pipeline {
agent {
label "web2"
}
environment {
gitlab_address = "http://192.168.31.64.17/microservice/demo.git"
gitlab_auth = "d09717ec-47c2-48f2-9c1c-f182b4589e74"
ansible_ssh_auth = "84ea22bc-c2c6-4f8f-88bb-9ed885819f9e"
}
parameters {
extendedChoice description: '请选择回滚的备份版本', multiSelectDelimiter: ',', name: 'BackupVersion', propertyFile: '/var/jenkins_home/rollback/backup_version.txt', propertyKey: 'bak', quoteValue: false, saveJSONParameterToFile: false, type: 'PT_SINGLE_SELECT', visibleItemCount: 5
choice choices: ['webservers1', 'webservers2', 'webservers3'], description: '灰度发布策略,分批次部署', name: 'ENV'
}

stages {
stage('回滚') {
steps {
sh """
###################### 主机清单文件 ############################
cat > /opt/jenkins_home/.hosts << EOF
[webservers1]
192.168.64.72
192.168.64.73
[webservers2]
192.168.64.72
[webservers3]
192.168.64.72
EOF
###################### Playbook文件 ############################
cat > /opt/jenkins_home/.playbook.yaml << "EOF"
- hosts: $ENV
gather_facts: no
vars:
tomcat_dir: "/usr/local/tomcat"
backup_dir: "/data/backup"
backup_filename: $BackupVersion
tasks:
- name: 使用备份文件重新部署
shell: |
cd {{ tomcat_dir }}/webapps
[ ! -d {{ backup_dir }}/rollback ] && mkdir -p {{ backup_dir }}/rollback
mv ROOT.war {{ backup_dir }}/rollback/ROOT-\$(date +%F-%T).war
cp {{ backup_dir }}/{{ backup_filename }} ROOT.war
pid=\$(ps -ef |grep {{ tomcat_dir }} |egrep -v 'grep' |awk '{print \$2}')
[ -n "\$pid" ] && kill -9 \$pid
export JAVA_HOME=/usr/local/jdk
nohup {{ tomcat_dir }}/bin/startup.sh
EOF
"""
// ===========================================
ansiblePlaybook(
playbook: '/opt/jenkins_home/.playbook.yaml',
inventory: '/tmp/.hosts',
credentialsId: "${ansible_ssh_auth}"
)
}
}
}
}