通过mode参数确定是否发布还是回滚,在满足rollback条件下,列举出我们的所有的备份的目录,根据回滚条件选择索要回滚的目录(目录是根据时间戳来判断创建的文件)
pipeline {
agent any
parameters {
choice(name: 'mode', choices: ['deploy','rollback'], description: '请选择发布或者回滚?')
}
stages {
stage('List Backup Directories') {
when {
expression { params.mode == 'rollback' }
}
steps {
script {
// 备份文件夹的路径
def backupDir = '/var/jenkins_home/biking-front/'
// 获取备份文件夹列表
def backupDirs = sh(returnStdout: true, script: "ls -d ${backupDir}front-prod-* ").trim().split('\n')
// 构建备份目录选择参数
def backupDirChoices = backupDirs.collect { dir ->
def dirName = dir =~ /\/([^\/]+)$/
[
//name: dirName[0][1],
value: dir
]
}
// 在Jenkins控制台上输出备份文件夹列表供选择
def userInput = input(
id: 'backupDirInput',
message: 'Select a backup directory to restore:',
parameters: [
choice(name: 'BACKUP_DIR', choices: backupDirChoices, description: 'Backup Directory')
]
)
// 将所选备份目录传递给下一个阶段
env.BACKUP_DIR = userInput
}
}
}
stage('回滚') {
when {
expression { params.mode == 'rollback' }
}
steps {
script {
// 获取选择的备份目录
def selectedBackupDir = env.BACKUP_DIR
// 提取目录名称
def backupDirName = selectedBackupDir.split('/')[-1].split('}')[0]
// 正式进行回滚操作
def remote = [:]
remote.name = "${env.iname}"
remote.path = "${env.mod_path}"
remote.host = '172.16.0.19'
remote.allowAnyHosts = true
withCredentials([sshUserPrivateKey(credentialsId: '172.16.0.19', keyFileVariable: 'identity', passphraseVariable: '', usernameVariable: 'userName')]) {
remote.user = userName
remote.identityFile = identity
sshCommand remote: remote, command: "echo 'Selected Backup Directory: ${backupDirName}'"
sshCommand remote: remote, command: "ossutil64 cp -rf /data/docker-compose/jenkins/jenkins_home/biking-front/${backupDirName} oss://exchange-web-log/biking-index/ -c /root/.prodossutilconfig"
}
}
}
}
}
}
在jenkins控制台上验证效果
根据需求选择所需要还原的版本
点击Proceed进行还原或者点击Abort进行取消还原