如何提前退出jenkins流水线阶段

wj8zmpe1  于 2022-11-02  发布在  Jenkins
关注(0)|答案(1)|浏览(588)

我正在尝试创建jenkins管道,以便使用脚本导出数据库。为了保持数据库正常运行,我需要不断刷新它,因为数据库在不活动后会关闭。因此我创建了一个简单的Spring项目,称为“keep-alive”,它在nohup下命中一个数据库查询。数据库导出和轮询都发生在同一阶段。导出最终完成,保活服务无限期地持续进行,我无法走出舞台来关闭我的机器。
下面是我的管道。什么需要改变,这样一次

sudo python3 export_new.py -cl ${CB_HOST}

完成执行后,应退出阶段并执行post部分,这将停止计算机并发送电子邮件。

pipeline {
    agent any

    parameters {
        string (name: 'MACHINE_INSTANCE_ID', defaultValue: '', description: 'AWS EC2 Instance ID ', trim: true)
        string (name: 'MACHINE_IP', defaultValue: '', description: 'AWS EC2 IP ', trim: true)
        string (name: 'CB_HOST', description: 'host to backup e.g. "http://somehost.com" ', trim: true)
    }
     stages{

        stage('Start AWS EC2 Instance') {
         steps {
                 sh label: 'Start AWS EC2 Instance', returnStatus: false, script: '''#!/bin/sh

                   aws ec2 start-instances --instance-ids ${MACHINE_INSTANCE_ID}
                   aws ec2 wait instance-running --instance-ids ${MACHINE_INSTANCE_ID}
                   aws ec2 wait instance-status-ok --instance-ids ${MACHINE_INSTANCE_ID}

                   echo "EC2 Instance ${MACHINE_INSTANCE_ID} successfully started!!"
                 '''
           }
        }

        stage('Perform Backup') {
              steps {
                script {
                 sh label: 'Perform Backup', returnStatus: false, script: '''#!/bin/sh
                       ssh -o StrictHostKeyChecking=no -i /var/lib/jenkins/pem ec2-user@${MACHINE_IP} 'bash -c' "'

                         sudo su -
                         cd /home/ubuntu/keep-alive
                         echo "starting keep alive service.."

                         sudo nohup java -jar keep-alive-1.0-SNAPSHOT.jar --places.dbHost=${CB_HOST} &

                         sleep 5

                         cd /home/ubuntu
                         echo "-- Running backup for ${CB_HOST} env"
                        sudo python3 export_new.py -cl ${CB_HOST}
                       '"
                     '''
              }
           }
         }
     }

     post {
         always {
           emailext attachLog: false,  mimeType: 'text/plain', subject: "export build ",
                 body: "Job completed..\nSee logs for more info:\n${env.BUILD_URL}/console",
                 to: 'abc.ec@xyz.com'

           sh label: 'Stop AWS EC2 Instance', script: '''#!/bin/sh

             aws ec2 stop-instances --instance-ids ${MACHINE_INSTANCE_ID}
             aws ec2 wait instance-stopped --instance-ids ${MACHINE_INSTANCE_ID}
             echo "EC2 Instance ${MACHINE_INSTANCE_ID} successfully stopped!!"
           '''
         }
       }
}
axzmvihb

axzmvihb1#

您可以捕获nohup命令的进程ID,并在执行备份后将其终止。

nohup my_command > my.log 2>&1 &
echo $! > save_pid.txt

# Run the backup

kill -9 `cat save_pid.txt`
exit 0

相关问题