Jenkins-k8s-发布脚本

Jenkins-k8s-发布脚本

发布脚本

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
82
83
84
85
86
def createVersion() {
return new Date().format('yyyyMMddHHmmss')
}
def _version = createVersion()

def service = 'hx-python-tianqi'

def git_url = 'http://192.168.8.1/hx-python.git'
def credentialsId = '0a5e96ae-0443-4e1f-ac0a-e02b3b0e4d81'
def docker_repo = '10.9.127.243:30002/dev'

def namespaces = 'dev'

pipeline {
agent any
stages {
stage('拉取代码') {
when { environment name: 'action', value: 'update' }
steps {
checkout([$class: 'GitSCM', branches: [[name: branch]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: credentialsId, url: git_url]]])

}
}
stage('构建镜像'){
when { environment name: 'action', value: 'update' }
steps {
sh '''
cat << 'EOF' > dockerfile
FROM jfloff/alpine-python
MAINTAINER hxkj
RUN cp -a /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
COPY tianqi.py /opt/app.py
RUN pip install requests pymysql beautifulsoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple
WORKDIR /opt
ENTRYPOINT ["python","app.py"]
EOF

'''
sh "docker build -t ${docker_repo}/${service}:${_version} ."
}
}
stage('推送镜像'){
when { environment name: 'action', value: 'update' }
steps {
sh "docker push ${docker_repo}/${service}:${_version} "
sh "docker rmi ${docker_repo}/${service}:${_version} "
}
}
stage('升级发布'){
when { environment name: 'action', value: 'update' }
steps {
sh """
cat << EOF > ${service}.yaml
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: ${service}
namespace: ${namespaces}
spec:
schedule: "*/15 * * * *"
jobTemplate:
spec:
template:
spec:
nodeSelector:
containers:
- name: ${namespaces}
image: ${docker_repo}/${service}:${_version}
imagePullPolicy: IfNotPresent
restartPolicy: OnFailure
EOF
"""
sh "kubectl apply -f ${service}.yaml"
}
}
stage('紧急回滚'){
when { environment name: 'action', value: 'rollback' }
steps {
sh "kubectl rollout undo deployment/${service} -n ${namespaces}"
}
}


}
}