Logo
1 mins
单机服务JenkinsCiCD通用实践

该文章介绍了一个基于Jenkins的 CICD部署剧本,包含构建、部署和 归档三个阶段,支持Git代码拉取 、npm打包、远程服务器部署及生 产环境确认流程。

单机服务JenkinsCiCD通用实践

整理一个自己写的基于Jenkins CICD通用的单体服务的部署剧本

node {
def commitId
def outputFile
git changelog: true,
branch: "${params.GIT_BRANCH}",
url: "https://gitlab.com/demo/oadmin.git"
commitId = sh(script: "git rev-parse --short HEAD", returnStdout: true).trim()
def currentTimestamp = new Date().format('yyyy-MM-dd_HH-mm-ss', TimeZone.getTimeZone('Asia/Shanghai'))
outputFile = "${params.DEPLOY_SERVER}-${BUILD_NUMBER}-${commitId}-${currentTimestamp}"
stage('Build') {
// 打包命令
sh 'export PATH=/var/lib/jenkins/node-v12.14.0/bin:$PATH && npm install && npm run build'
// 保存输出
sh "mv dist /${outputFile}"
// 部署产出脚本
sh "echo 'ln -snf /www/release/${outputFile} /www/web/latest' > deploy.sh;chmod +x deploy.sh"
}
stage('Deploy') {
//远程服务器部署ssh密钥
withCredentials([sshUserPrivateKey(credentialsId: 'jenkins_id_rsa', keyFileVariable: 'SSH_KEY_FILE', passphraseVariable: '', usernameVariable: 'SSH_USER')]) {
// 上传zip文件
def remote = [:]
remote.name = 'remote_server'
remote.host = "${params.DEPLOY_SERVER}"
remote.user = SSH_USER
remote.identityFile = SSH_KEY_FILE
remote.allowAnyHosts = true
// 把outputFile产出文件上传到服务器部署目录下
sshPut remote: remote, from: "${outputFile}", into: '/www/release'
// 生成环境配置二次check
if ("${params.DEPLOY_SERVER}" == 'prod') {
input 'Are you sure you want to deploy to production?'
}
// 执行部署脚本,传入zip文件名作为参数
sshScript remote: remote, script: "deploy.sh"
}
}
stage('Archive') {
// 归档outputFile文件
archiveArtifacts artifacts: "${outputFile}", fingerprint: true
}
}
image.png