From a29d4f45744c4b69c783deece425350b7772e31b Mon Sep 17 00:00:00 2001 From: dxin <1554389441@qq.com> Date: Sun, 30 Nov 2025 23:40:49 +0800 Subject: [PATCH] !!! --- SCM/构建镜像/1 | 181 ++++++++++ SCM/构建镜像/build_image_flymoon_email.groovy | 5 - .../build_image_flymoon_email_v2.groovy | 324 ++++++++++++++++++ SCM/部署镜像/s1/DM_s1_flymoon_email_v2.groovy | 214 ++++++++++++ 4 files changed, 719 insertions(+), 5 deletions(-) create mode 100644 SCM/构建镜像/1 create mode 100644 SCM/构建镜像/build_image_flymoon_email_v2.groovy create mode 100644 SCM/部署镜像/s1/DM_s1_flymoon_email_v2.groovy diff --git a/SCM/构建镜像/1 b/SCM/构建镜像/1 new file mode 100644 index 0000000..a4fe710 --- /dev/null +++ b/SCM/构建镜像/1 @@ -0,0 +1,181 @@ +// ========= 使用 properties 定义参数 (Scripted Pipeline 部分) ========= +properties([ + parameters([ + // --- 1. 动态下拉框 (移除 filterable) --- + [$class: 'org.biouno.unochoice.DynamicReferenceParameter', + name: 'IMAGE_TAG_WITH_LABELS', // 参数名,用于被其他参数引用 + description: '选择镜像 (tag - Labels)', + choiceType: 'PT_SINGLE_SELECT', // 单选 + // filterable: true, // ❌ 移除:2.8.8 可能不支持 + script: [ + $class: 'org.biouno.unochoice.model.GroovyScript', + // ✅ 修复:使用 GroovyScriptSource + script: [ + $class: 'org.biouno.unochoice.model.GroovyScriptSource', + script: ''' + import groovy.json.JsonSlurper + + def choices = [] + def metadataDir = '/var/lib/jenkins/metadata' + // 注意:这里的文件名需要与构建 Job 存储的文件名一致 + // 假设你的命名空间是 lessiesit + def metadataFileRelativePath = "lessiesit-flymoon-email.json" // <--- 修正:根据实际命名空间和镜像名调整 + def fullMetadataPath = "${metadataDir}/${metadataFileRelativePath}" + + try { + // 使用 readFile 步骤读取文件内容(作为字符串) + def existingDataString = readFile file: fullMetadataPath, encoding: 'UTF-8' + if (existingDataString) { + def jsonSlurper = new groovy.json.JsonSlurper() + def existingDataList = jsonSlurper.parseText(existingDataString) + + if (existingDataList instanceof List) { + existingDataList.each { imageData -> + def tag = imageData.image_tag + def labels = imageData.labels + def branch = labels?.get('git-branch') ?: 'N/A' + def commit = labels?.get('git-commit') ?: 'N/A' + def author = labels?.get('git-author') ?: 'N/A' + def message = labels?.get('git-message') ?: 'N/A' + def time = labels?.get('build-time') ?: 'N/A' + + // 格式化显示文本: "tag - commit: message (time) - branch" + def displayText = "${tag} - ${commit}: ${message} (${time}) - ${branch}" + // 将 image_tag 作为选项的值 + def value = tag + + // Active Choices 期望返回 ["displayText [value]", ...] 格式的 List + choices << "${displayText} [${value}]" + } + } else { + choices = ["(元数据文件格式错误: 非 List 类型)"] + } + } else { + choices = ["(元数据文件为空)"] + } + } catch (java.io.FileNotFoundException e) { + // 文件不存在 + choices = ["(未找到元数据文件: ${fullMetadataPath})"] + } catch (Exception e) { + choices = ["❌ 加载镜像列表失败: ${e.message}"] + } + + return choices + ''' + ], + fallbackScript: [ + $class: 'org.biouno.unochoice.model.GroovyScriptSource', + script: ''' + return ['⚠️ 脚本执行异常'] + ''' + ] + ], + omitValueField: true // 不显示输入框,只显示下拉 + ], + + // --- 2. 监听下拉框变化,显示 Labels --- + [$class: 'org.biouno.unochoice.ReactiveReferenceParameter', + name: 'IMAGE_LABELS_PREVIEW', // 参数名,用于显示 + description: '镜像 Labels 预览', // 页面上会显示这个描述 + script: [ + $class: 'org.biouno.unochoice.model.GroovyScript', + // ✅ 修复:使用 GroovyScriptSource + script: [ + $class: 'org.biouno.unochoice.model.GroovyScriptSource', + script: ''' + import groovy.json.JsonSlurper + + // 获取被引用的参数值 + def selectedTag = params.IMAGE_TAG_WITH_LABELS ?: '' // 使用下拉框的参数名 + + if (!selectedTag) { + return '
(请选择镜像)
' + } + + def metadataDir = '/var/lib/jenkins/metadata' + // 注意:这里的文件名需要与构建 Job 存储的文件名一致 + // 假设你的命名空间是 lessiesit + def metadataFileRelativePath = "lessiesit-flymoon-email.json" // <--- 修正:根据实际命名空间和镜像名调整 + def fullMetadataPath = "${metadataDir}/${metadataFileRelativePath}" + + try { + def existingDataString = readFile file: fullMetadataPath, encoding: 'UTF-8' + if (existingDataString) { + def jsonSlurper = new groovy.json.JsonSlurper() + def existingDataList = jsonSlurper.parseText(existingDataString) + + if (existingDataList instanceof List) { + // 查找匹配的镜像数据 + def imageData = existingDataList.find { it.image_tag == selectedTag } + + if (imageData) { + def labels = imageData.labels + def branch = labels?.get('git-branch') ?: 'N/A' + def commit = labels?.get('git-commit') ?: 'N/A' + def author = labels?.get('git-author') ?: 'N/A' + def message = labels?.get('git-message') ?: 'N/A' + def time = labels?.get('build-time') ?: 'N/A' + + // 格式化输出 + def output = "
🏷️ Labels for ${selectedTag}:
" + output += "git-branch: ${branch}
" + output += "git-commit: ${commit}
" + output += "git-author: ${author}
" + output += "git-message: ${message}
" + output += "build-time: ${time}
" + output += "
" + + return output + } else { + return "
⚠️ 未找到标签为 '${selectedTag}' 的镜像信息
" + } + } else { + return "
❌ 元数据文件格式错误: 非 List 类型
" + } + } else { + return "
❌ 元数据文件为空
" + } + } catch (java.io.FileNotFoundException e) { + return "
❌ 未找到元数据文件: ${fullMetadataPath}
" + } catch (Exception e) { + return "
❌ 查询镜像信息失败: ${e.message}
" + } + ''' + ], + fallbackScript: [ + $class: 'org.biouno.unochoice.model.GroovyScriptSource', + script: ''' + return '
⚠️ 查询脚本执行异常
' + ''' + ] + ], + choiceType: 'ET_FORMATTED_HTML', // 返回 HTML + omitValueField: true, // 不显示输入框,只显示返回的 HTML + referencedParameters: 'IMAGE_TAG_WITH_LABELS' // 监听的参数 + ] + // --- 结束添加 --- + ]) +]) + +// ========= Declarative Pipeline 主体 ========= +pipeline { + agent any + // 注意:parameters 块已移至 properties 中 + stages { + stage('部署') { + steps { + script { + // --- ✅ 修正:构建完整镜像名 --- + // 从参数 IMAGE_TAG_WITH_LABELS 获取 tag + def tag = params.IMAGE_TAG_WITH_LABELS // 使用下拉框的参数名 + // 拼接完整镜像名 + def fullImageName = "uswccr.ccs.tencentyun.com/lessiesit/flymoon-email:${tag}" // 修正:命名空间 + + echo "开始部署镜像: ${fullImageName}" + // 部署命令(如kubectl、docker run等) + // sh "kubectl set image deployment/your-app app=${fullImageName}" + } + } + } + } +} \ No newline at end of file diff --git a/SCM/构建镜像/build_image_flymoon_email.groovy b/SCM/构建镜像/build_image_flymoon_email.groovy index 2dc0f62..ab392ae 100644 --- a/SCM/构建镜像/build_image_flymoon_email.groovy +++ b/SCM/构建镜像/build_image_flymoon_email.groovy @@ -29,11 +29,6 @@ pipeline { defaultValue: '', description: '可选:自定义镜像 Tag (字母、数字、点、下划线、短横线), 如 v0.0.1, 留空则自动生成 “ v+构建次数_分支名_短哈希_构建时间 ”' ) - booleanParam( - name: 'DEPLOY_AFTER_BUILD', - defaultValue: false, - description: '是否构建完镜像后部署?' - ) } environment { REGISTRY = "uswccr.ccs.tencentyun.com" // 镜像仓库地址 diff --git a/SCM/构建镜像/build_image_flymoon_email_v2.groovy b/SCM/构建镜像/build_image_flymoon_email_v2.groovy new file mode 100644 index 0000000..76ba523 --- /dev/null +++ b/SCM/构建镜像/build_image_flymoon_email_v2.groovy @@ -0,0 +1,324 @@ + +// --- 辅助函数:深拷贝对象以确保可序列化 --- +def deepCopyForSerialization(obj) { + if (obj instanceof Map) { + // 创建新的 LinkedHashMap,递归拷贝值 + return obj.collectEntries { k, v -> [(k): deepCopyForSerialization(v)] } + } else if (obj instanceof List) { + // 创建新的 ArrayList,递归拷贝元素 + return obj.collect { item -> deepCopyForSerialization(item) } + } else if (obj instanceof String || obj instanceof Number || obj instanceof Boolean || obj == null) { + return obj + } else { + return obj.toString() + } +} +// --- 结束辅助函数 --- + +pipeline { + agent any + + parameters { + gitParameter( + branchFilter: 'origin/(.*)', + defaultValue: 'dxin', + name: 'Code_branch', + type: 'PT_BRANCH_TAG', + selectedValue: 'DEFAULT', + sortMode: 'NONE', + description: '选择代码分支: ', + quickFilterEnabled: true, + tagFilter: '*', + listSize: "1" + ) + choice( + name: 'NAME_SPACES', + choices: ['sit', 'test', 'prod'], + description: '选择存放镜像的仓库命名空间:' + ) + choice( + name: 'MAVEN_BUILD_PROFILE', + choices: ['us', 'cn'], + description: '选择MAVEN构建的配置文件, 默认为 us' + ) + string( + name: 'CUSTOM_TAG', + defaultValue: '', + description: '可选:自定义镜像 Tag (字母、数字、点、下划线、短横线), 如 v0.0.1, 留空则自动生成 “ v+构建次数_分支名_短哈希_构建时间 ”' + ) + } + environment { + REGISTRY = "uswccr.ccs.tencentyun.com" // 镜像仓库地址 + NAMESPACE = "lessie${params.NAME_SPACES}" // 命名空间根据choices的选择拼接 + IMAGE_NAME = "flymoon-email" // 镜像名(固定前缀) + CREDENTIALS_ID = "dxin_img_hub_auth" // 容器仓库凭证ID + } + stages { + stage('拉取代码') { + steps { + git branch: "${params.Code_branch}", + credentialsId: 'fly_gitlab_auth', + url: 'http://172.24.16.20/root/fly_moon_email.git' + } + } + stage('获取信息') { + steps { + script { + // 获取分支名 + env.Code_branch = "${params.Code_branch}" + // 获取最近一次提交的哈希值(短格式,前8位) + env.GIT_COMMIT_SHORT = sh(script: 'git rev-parse --short HEAD',returnStdout: true).trim() + // 获取最近一次提交的哈希值(全格式) + env.GIT_COMMIT_LONG = sh(script: 'git rev-parse HEAD', returnStdout: true).trim() + // 获取最近一次提交的作者 + env.GIT_AUTHOR = sh(script: 'git log -1 --pretty=format:%an',returnStdout: true).trim() + // 获取最近一次提交的时间(格式化) + env.GIT_COMMIT_TIME = sh( + script: 'git log -1 --pretty=format:%ct | xargs -I {} date -d @{} +%Y%m%d-%H%M%S', + returnStdout: true + ).trim() + // 获取最近一次提交的备注信息(转义特殊字符,避免构建失败) + env.GIT_COMMIT_MSG = sh(script: 'git log -1 --pretty=format:%s | sed -e \'s/"/\\"/g\'', returnStdout: true).trim() + + // Jenkins构建次数 + def buildNumber = env.BUILD_NUMBER // Jenkins内置变量,直接获取当前Job的构建序号 + // 当前分支名(处理/为-,如feature/docker_1015 → feature-docker_1015) + def branchName = sh(script: 'git rev-parse --abbrev-ref HEAD', returnStdout: true).trim() + def formattedBranch = branchName.replace('/', '-').replace('_', '-') // 替换分支名中的/和_为- + // 构建时间(格式:202510181215,年-月-日-时-分,无分隔符) + def buildTime = sh(script: 'date +%Y%m%d%H%M', returnStdout: true).trim() + def defaultTag = "v${buildNumber}_${formattedBranch}_${GIT_COMMIT_SHORT}_${buildTime}" + + def customTag = params.CUSTOM_TAG?.trim() + def tagPattern = ~/^[a-zA-Z0-9._-]+$/ + + // 判断最终Tag + if (customTag && customTag ==~ tagPattern) { + echo "✅ 使用自定义镜像 Tag: ${customTag}" + env.IMAGE_TAG = customTag + } else if (customTag) { + echo "⚠️ 自定义 Tag '${customTag}' 不符合规范,将使用默认生成的 Tag: ${defaultTag}" + + def confirmed = true + timeout(time: 1, unit: 'MINUTES') { + try { + input( + message: """⚠️ Tag 命名不规范: + ${customTag} + + 将使用自动生成的 Tag: + ${defaultTag} + + 是否继续构建?""", + ok: '确认' + ) + } catch (err) { + // 用户点击“取消”或中断 + echo "🚫 用户取消构建" + confirmed = false + } + } + if (confirmed) { + echo "✅ 用户确认使用自动生成的 Tag:${defaultTag}" + env.IMAGE_TAG = defaultTag + } else { + error("流水线已终止。") + } + } else { + env.IMAGE_TAG = defaultTag + echo "未输入自定义 Tag, 使用自动生成规则: ${env.IMAGE_TAG}" + } + } + } + } + stage('登录容器仓库') { + steps { + withCredentials([usernamePassword( + credentialsId: env.CREDENTIALS_ID, + usernameVariable: 'REGISTRY_USER', + passwordVariable: 'REGISTRY_PWD' + )]) { + sh ''' + echo "$REGISTRY_PWD" | docker login ${REGISTRY} -u ${REGISTRY_USER} --password-stdin + ''' + } + } + } + stage('构建容器镜像') { + steps { + script { + // 构建镜像,添加标签信息 + sh """ + docker build \ + --build-arg MAVEN_BUILD_PROFILE=${params.MAVEN_BUILD_PROFILE} \ + -t ${REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} \ + --label "git-branch='${Code_branch}'" \ + --label "git-commit='${GIT_COMMIT_LONG}'" \ + --label "git-author='${GIT_AUTHOR}'" \ + --label "git-message='${GIT_COMMIT_MSG}'" \ + --label "build-time='${GIT_COMMIT_TIME}'" \ + . + """ + } + } + } + stage('推送镜像到仓库') { + steps { + script { + sh "docker push ${REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}" + echo "推送镜像成功:${REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}" + } + } + } + } + + post { + always { + script { + def keepCount = 2 + echo "开始清理本地旧镜像,仅保留最近 ${keepCount} 个构建版本" + def imagePrefix = "${REGISTRY}/${NAMESPACE}/${IMAGE_NAME}" + + // 获取所有镜像(按创建时间排序,越新的越前) + // 格式:Repository:Tag ImageID CreatedAt + def allImagesRaw = sh(script: "docker images ${imagePrefix} --format '{{.Repository}}:{{.Tag}} {{.ID}} {{.CreatedAt}}' | sort -rk3", returnStdout: true).trim() + if (!allImagesRaw) { + echo "未找到任何镜像,无需清理" + return + } + + def allImages = allImagesRaw.split('\n') + if (allImages.size() <= keepCount) { + echo "当前镜像数未超过 ${keepCount} 个,无需清理" + return + } + + def oldImages = allImages.drop(keepCount) + echo "发现 ${oldImages.size()} 个旧镜像需要清理" + oldImages.each { line -> + echo " ${line}" + } + + oldImages.each { line -> + def parts = line.split(' ') + def imageTag = parts[0] + def imageId = parts.size() > 1 ? parts[1] : "" + + // 对于标签为的无效镜像,使用镜像ID删除 + if (imageTag.contains("") && imageId) { + echo "删除无效镜像: ${imageId}" + sh(returnStatus: true, script: "docker rmi -f ${imageId} || true") + } else if (imageId) { + // 对于有标签的有效镜像,优先使用镜像ID删除 + echo "删除旧镜像: ${imageTag} (${imageId})" + sh(returnStatus: true, script: "docker rmi -f ${imageId} || true") + } else { + // 兜底方案,使用标签删除 + echo "删除旧镜像: ${imageTag}" + sh(returnStatus: true, script: "docker rmi -f ${imageTag} || true") + } + } + + echo "清理完成,当前镜像状态:" + sh """ + docker images ${imagePrefix} --format 'table {{.Repository}}\\t{{.Tag}}\\t{{.CreatedAt}}\\t{{.Size}}' + """ + + sh "docker logout ${REGISTRY}" + echo "容器仓库已登出,本地凭证已清理" + } + } + success { + script { + // 1. 准备元数据 (转换所有环境变量为 String) + def metadataDir = '/var/lib/jenkins/metadata' + def metadataFileRelativePath = "${env.NAMESPACE}-${env.IMAGE_NAME}.json" // 相对于 metadataDir 的文件名 + def fullMetadataPath = "${metadataDir}/${metadataFileRelativePath}" + + // --- 转换为 String --- + def registry = env.REGISTRY as String + def namespace = env.NAMESPACE as String + def imageName = env.IMAGE_NAME as String + def imageTag = env.IMAGE_TAG as String + def codeBranch = params.Code_branch as String // 使用 params,因为 Code_branch 是参数 + def gitCommit = env.GIT_COMMIT_LONG as String + def gitAuthor = env.GIT_AUTHOR as String + def gitCommitMsg = env.GIT_COMMIT_MSG as String + def gitCommitTime = env.GIT_COMMIT_TIME as String + def buildNumber = env.BUILD_NUMBER as String + // --- 转换为 String --- + + // 2. 准备新数据 + def newImageData = [ + image_tag: imageTag, // 使用转换后的变量 + full_image_name: "${registry}/${namespace}/${imageName}:${imageTag}", // 使用转换后的变量 + labels: [ + "git-branch": codeBranch, + "git-commit": gitCommit, + "git-author": gitAuthor, + "git-message": gitCommitMsg, + "build-time": gitCommitTime + ], + build_job_number: buildNumber, + build_time: new Date().format('yyyy-MM-dd HH:mm:ss') // Jenkins 构建完成时间 + ] + + // 2. 读取现有数据(如果文件存在) + def existingDataList = [] + try { + // 使用 readJSON 步骤读取文件内容 (readJSON 会自动处理 LazyMap 问题) + def rawExistingData = readJSON file: fullMetadataPath, default: [] // 如果文件不存在,则返回空列表 [] + + // --- ✅ 修复:深拷贝 rawExistingData (修正内联代码) --- + if (rawExistingData instanceof List) { + existingDataList = rawExistingData.collect { item -> + if (item instanceof Map) { + // 递归深拷贝 Map (使用辅助函数) + return deepCopyForSerialization(item) + } else { + return item + } + } + } else { + echo "警告: 元数据文件 ${fullMetadataPath} 格式不正确(非 List 类型),将被覆盖。" + existingDataList = [] + } + // --- 结束修复 --- + + } catch (Exception e) { + // readJSON 在文件不存在时通常会返回 default 值,但如果文件存在但格式错误,会抛出异常 + echo "警告: 读取元数据文件 ${fullMetadataPath} 失败或格式错误: ${e.getMessage()},将被覆盖。" + // 确保目录存在 + sh "mkdir -p ${metadataDir}" + existingDataList = [] // 重置为新列表 + } + + // 3. 将新数据添加到列表开头(最新的在前) + existingDataList.add(0, newImageData) + + // 4. 限制列表大小为 20 + if (existingDataList.size() > 20) { + existingDataList = existingDataList.take(20) + } + + // 5. 使用 writeJSON 步骤写入文件 (writeJSON 会自动处理 Map 的序列化) + writeJSON file: fullMetadataPath, json: existingDataList, pretty: 2 // pretty: 2 表示格式化 JSON (2 个空格缩进) + + echo "镜像元数据已存储到: ${fullMetadataPath}" + + // 输出构建结果 + echo """ + 镜像地址:${registry}/${namespace}/${imageName}:${imageTag} + 对应代码提交哈希:${gitCommit} + 对应代码分支:${codeBranch} + 代码提交者:${gitAuthor} + 提交备注:${gitCommitMsg} + """.stripIndent() + } + } + failure { + // 输出构建结果 + echo "构建失败,请检查!" + } + } +} diff --git a/SCM/部署镜像/s1/DM_s1_flymoon_email_v2.groovy b/SCM/部署镜像/s1/DM_s1_flymoon_email_v2.groovy new file mode 100644 index 0000000..1f232ea --- /dev/null +++ b/SCM/部署镜像/s1/DM_s1_flymoon_email_v2.groovy @@ -0,0 +1,214 @@ +pipeline { + agent any + + parameters { + booleanParam( + name: 'DEPLOY_AFTER_BUILD', + defaultValue: false, + description: '是否快速回滚上一个版本?' + ) + choice( + name: 'BRANCH_NAME', + choices: ['dxin', 'opt'], + description: '选择资源清单Yaml的分支' + ) + imageTag( + name: 'IMAGE_NAME', + description: '此处是 sit 镜像仓库内的 flymoon-email 镜像', + registry: 'https://uswccr.ccs.tencentyun.com', + image: 'lessiesit/flymoon-email', + credentialId: 'dxin_img_hub_auth', + filter: '.*', + defaultTag: '', + verifySsl: true + ) + } + environment { + KUBECONFIG = credentials('k8s-test-config-admin') // k8s 凭证 ID, Jenkins 中配置的凭证名称 + IMAGE_FULL_NAME = "uswccr.ccs.tencentyun.com/${IMAGE_NAME}" + Deployment_yaml = "${WORKSPACE}/lessie-ai/sit/s1/flymoon-email.yaml" + Deployment_name = "s1-flymoon-email" + K8s_namespace = "sit" + Pod_container_name = "flymoon-email" + } + stages { + stage('快速回滚上一版本') { + when { + expression { return params.DEPLOY_AFTER_BUILD == true } + } + steps { + script { + sh """ + echo "=== 开始回滚到上一个版本 ===" + kubectl rollout undo deployment/${Deployment_name} -n ${K8s_namespace} + echo "=== 回滚中... ===" + kubectl rollout status deployment/${Deployment_name} -n ${K8s_namespace} --timeout=180s + echo "=== 查看所使用的镜像 ===" + kubectl get deployment ${Deployment_name} -n ${K8s_namespace} -o=jsonpath='{.spec.template.spec.containers[*].image}' + echo "=== 回滚完成 ===" + """ + } + } + } + stage('拉取yaml') { + when { + expression { return params.DEPLOY_AFTER_BUILD == false } + } + steps { + git branch: "${params.BRANCH_NAME}", + credentialsId: 'fly_gitlab_auth', + url: 'http://172.24.16.20/opt/opt-config.git' + } + } + stage('修改YAML镜像') { + when { + expression { return params.DEPLOY_AFTER_BUILD == false } + } + steps { + script { + echo "=== 所选择新的镜像: ${params.IMAGE_NAME} ===" + OLD_IMAGE_NAME = sh ( + script: "kubectl get deployment ${Deployment_name} -n ${K8s_namespace} -o=jsonpath='{.spec.template.spec.containers[*].image}'", + returnStdout: true + ).trim() + echo "--- 旧镜像: ${OLD_IMAGE_NAME} ---" + sh """ + echo "=== 修改 Deployment YAML 中的镜像版本 ===" + sed -i 's#image:.*#image: ${IMAGE_FULL_NAME}#' ${Deployment_yaml} + """ + } + } + } + stage('部署到k8s') { + when { + expression { return params.DEPLOY_AFTER_BUILD == false } + } + steps { + script { + def ANNOTATION = "更新 image 为 ${params.IMAGE_NAME}" + sh """ + echo "===Apply Deployment YAML ===" + kubectl apply -f ${Deployment_yaml} -n ${K8s_namespace} + + echo "=== 查看当前新使用的镜像 ===" + kubectl get deployment ${Deployment_name} -n ${K8s_namespace} -o=jsonpath='{.spec.template.spec.containers[*].image}' + + echo "=== 添加注解 ===" + kubectl annotate deployment/${Deployment_name} kubernetes.io/change-cause="${ANNOTATION}" --overwrite -n ${K8s_namespace} + + echo "=== 查看历史版本 ===" + kubectl rollout history deployment/${Deployment_name} -n ${K8s_namespace} + """ + } + } + } + stage('检查部署情况') { + when { + expression { return params.DEPLOY_AFTER_BUILD == false } + } + steps { + script { + echo "=== 检测部署状态并验证新版本运行情况 ===" + echo "--- 检查 Deployment 更新状态 ---" + def rolloutStatus = sh( + script: "kubectl rollout status deployment/${Deployment_name} -n ${K8s_namespace} --timeout=60s", + returnStatus: true + ) + + if (rolloutStatus != 0){ + echo "Deployment ${Deployment_name} 发布 **超时或失败**,开始排查..." + sh """ + echo "--- Deployment 状态 ---" + kubectl describe deployment ${Deployment_name} -n ${K8s_namespace} || true + + echo '--- Pod 列表 ---' + kubectl get pods -n ${K8s_namespace} -l app=${Pod_container_name} -o wide || true + + echo "--- Pod 描述 (describe) ---" + for pod in \$(kubectl get pods -n ${K8s_namespace} -l app=${Pod_container_name} -o jsonpath='{.items[*].metadata.name}'); do + echo "-- Pod 描述 \$pod --" + kubectl describe pod \$pod -n ${K8s_namespace} || true + done + + echo "--- 最近 200 行 Pod 日志 ---" + for pod in \$(kubectl get pods -n ${K8s_namespace} -l app=${Pod_container_name} -o jsonpath='{.items[*].metadata.name}'); do + echo "-- logs \$pod --" + kubectl logs \$pod -n ${K8s_namespace} --tail=200 || true + done + """ + error("=== Deployment 发布失败,请检查以上输出定位问题 ===") + } + + echo "=== 检查 Pods 是否全部 Ready ===" + sh "kubectl get pods -l app=${Pod_container_name} -n ${K8s_namespace} -o wide" + + echo "=== 获取最新 Pod 名称 ===" + NEW_POD = sh ( + script: "kubectl get pods -l app=${Pod_container_name} -n ${K8s_namespace} --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1].metadata.name}'", + returnStdout: true + ).trim() + + echo "=== 新 Pod 启动日志(最近20行) ===" + sh "kubectl logs ${NEW_POD} -n ${K8s_namespace} --tail=20 || true" + + echo "部署成功:${NEW_POD} 已正常运行" + } + } + } + stage('生成变更说明') { + when { + expression { return params.DEPLOY_AFTER_BUILD == false } + } + steps { + script { + def user = currentBuild.getBuildCauses()[0].userName ?: "SYSTEM" + def now = sh(script: "date '+%Y-%m-%d %H:%M:%S'", returnStdout: true).trim() + env.CHANGE_MSG = """ + jenkins执行人: ${user} + 修改时间: ${now} + 旧镜像: ${OLD_IMAGE_NAME} + 新镜像: ${IMAGE_FULL_NAME} + 部署对象: ${Deployment_name} + """.stripIndent() + echo "=== 本次部署变更说明 ===" + echo env.CHANGE_MSG + } + } + } + stage('提交变更记录到 GitLab') { + when { + expression { return params.DEPLOY_AFTER_BUILD == false } + } + steps { + script { + withCredentials([usernamePassword(credentialsId: 'fly_gitlab_auth', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PASS')]) { + sh """ + cd ${WORKSPACE} + git config user.name "jenkins" + git config user.email "jenkins@local" + + git add ${Deployment_yaml} + git commit -m "更新镜像 ${CHANGE_MSG}" + + # 生成临时 .netrc 文件 + echo "machine 172.24.16.20 login \$GIT_USER password \$GIT_PASS" > ~/.netrc + chmod 600 ~/.netrc + + git push http://172.24.16.20/opt/opt-config.git ${params.BRANCH_NAME} + """ + } + } + } + } + } + + post { + success { + echo "成功!" + echo "=== 所选择镜像: ${params.IMAGE_NAME} ===" + } + failure { + echo "有步骤失败,请检查!" + } + } +} \ No newline at end of file