一、设置人工干预,决定是否部署到生产环境
1.1.脚本
stage("确认部署到生产"){
def inputResp = input id: "input_${BUILD_NUMBER}", message: '''确认部署到生产请输入:approve''', parameters: [string(defaultValue: '', description: '''确认是否部署到生产,输入指令后点击Proceed,终止请点击Abort''', name: 'action')]
if(inputResp != "approve")
{
throw new Exception("The input is incorrect, we abort this job..")
}
println "开始部署到生产......"
}
1.2.执行效果
二、设置人工干预,定义执行动作(可从失败的stage执行)
传入stagesRun的参数确定的情况
脚本
def ansible_path = "/etc/ansible/ansible_playbooks"
timestamps{
try {
node(){
stage("配置安装参数"){
echo "配置安装参数"
}
stage("安装docker"){
stagesRun("installDocker",ansible_path)
}
}
}
catch(Exception err){
throw new Exception("*******Caught an exception: ${err}")
}
}
def installDocker(ansible_path){
dir(ansible_path){
ansiblePlaybook become: true,
becomeUser: 'root',
disableHostKeyChecking: true,
inventory: '/etc/ansible/hosts',
playbook: 'install_docker.yml',
colorized: true
}
}
def stagesRun(stage_name,ansible_path){
def nodeId = "node" + new SimpleDateFormat("YYYYMMddHHmmss").format(Calendar.getInstance().getTime())
def errorFlag = false
while(true)
{
if (errorFlag)
{
def desc = '''请选择下一步动作指令后点击Proceed,要终止请点击Abort'''
def inputResp = input id: "input_${nodeId}",
message: "${stage_name}执行失败,请选择下一步动作:",
parameters: [choice(choices:['retry','skip'], description: desc, name: 'action')]
if ('skip' == inputResp)
{
return
}
if('retry' == inputResp)
{
echo "重试"
}
}
try
{
"${stage_name}"("${ansible_path}")
break
}
catch(Exception err)
{
errorFlag = true
echo "Caught: ${err}"
}
}
}
传入的参数不确定的情况
主程序
function = load "${WORKSPACE}/jenkinsfile/common.groovy"
def parmList = [a,b,c,d]
function.stagesRun("flywayUpgradeSql",gitProduct,parmList)
common.groovy
def flywayUpgradeSql(paramList){
def dbUser = paramList[0]
def dbPwd = paramList[1]
def dbUrl = paramList[2]
def sqlPath = paramList[3]
sh """
source /etc/profile
[[ ! -d ${sqlPath} ]] && echo "ERROR:${sqlPath} Not Found" && exit 1
/home/admin/flyway-4.2.0/flyway \\
-user=${dbUser} -password=${dbPwd} \\
-url=${dbUrl} -locations=filesystem:${sqlPath} \\
-baselineOnMigrate=true -validateOnMigrate=false -placeholderReplacement=false \\
repair migrate
"""
}
def stagesRun(stageName,gitProduct,parmList){
def errorFlag = false
while(true)
{
if (errorFlag)
{
def desc = '''请选择下一步动作指令后点击Proceed,要终止请点击Abort'''
def inputResp = input id: "input_${BUILD_NUMBER}",
message: "${stageName}执行失败,请选择下一步动作:",
parameters: [choice(choices:['retry','skip'], description: desc, name: 'action')]
if ('skip' == inputResp)
{
return
}
if('retry' == inputResp)
{
echo "重试"
sh """
for name in `echo ${gitProduct}`
do
{
name=\${name##*/}
cd ${WORKSPACE}/\$name
git pull
} &
done
wait
cd ${WORKSPACE}/devops && git pull
"""
}
}
try
{
"${stageName}"(parmList)
break
}
catch(Exception err)
{
errorFlag = true
echo "Caught: ${err}"
}
}
}
return this
2.2.执行效果