第1章 pipeline写法
pipeline{
agent any
parameters {
gitParameter name: 'git_version',
branchFilter: 'origin/(.*)',
type: 'PT_TAG',
defaultValue: 'v1.0',
description: '发布新版本'
choice(name: 'base_image', choices: ['nginx:1.16','nginx:1.17'],description: '请选择基础镜像版本')
choice(name: 'deploy_env', choices: ['deploy','rollback'],description: 'deploy: 发布版本
rollback: 回滚版本')
}
stages{
stage("下载代码"){
steps{
checkout([$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'RelativeTargetDirectory',
relativeTargetDir: 'game']],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'b8c1f793-47ed-4903-995d-2273673d8f87',
url: 'git@10.0.0.200:dev/docker-pipeline.git']]])
}
}
stage("编译镜像"){
when {
environment name: 'deploy_env', value: 'deploy'
}
steps{
writeFile file: "Dockerfile", text: """FROM 10.0.0.205/base_image/${params.base_image}
ADD game /usr/share/nginx/html/"""
sh "docker build -t 10.0.0.205/image/game:${params.git_version} . && docker push 10.0.0.205/image/game:${params.git_version}"
}
}
stage("推送镜像"){
when {
environment name: 'deploy_env', value: 'deploy'
}
steps{
sh "docker build -t 10.0.0.205/image/game:${params.git_version} . && docker push 10.0.0.205/image/game:${params.git_version}"
}
}
stage("部署容器"){
when {
environment name: 'deploy_env', value: 'deploy'
}
steps{
sh 'ssh 10.0.0.204 "docker stop game && docker rm game && docker run --name game -p 80:80 -d 10.0.0.205/image/game:${git_version} && docker ps"'
}
}
stage("清理构建镜像"){
when {
environment name: 'deploy_env', value: 'deploy'
}
steps{
sh "docker rmi 10.0.0.205/image/game:${params.git_version}"
}
}
stage("回滚容器"){
when {
environment name: 'deploy_env', value: 'rollback'
}
steps{
sh 'ssh 10.0.0.204 "docker stop game && docker rm game && docker run --name game -p 80:80 -d 10.0.0.205/image/game:${git_version} && docker ps"'
}
}
}
}