一. jenkins pipeline 脚本模板,里面添加了一些 groovy 语言方法,这个模板目前是编译 dotnet 使用,支持linux 和windows 机器。
#!groovy // dotnet 可以使用模板 sourcefile='aaa' SCM_TYPE ='git' SCM_URL = 'url://' SCM_AUTH_PASS ='da77d2e8-' SCM_AUTH_USER='tess-dsd' SCM_BRANCH = 'dev' BUILD_SCRIPTS='''''' COMPILE_LABEL = 'dotNetCMs' LFS_NODE_LABEL = '192.168.1.1' RESOURCE_NODE_LABEL = '192.168.1.2' set_env='''nouse ''' unzip_path ='nouse' config_path = 'nouse' target_path = '' stop_script='''''' start_script='''cd $WORKSPACE; unzip -oq $zipfile; for i in aaa bbb do rm -rf \\$basedir/\\$i/upload/* mv \\$i/* \\$basedir/\\$i/upload/ /bin/cp \\$basedir/\\$i/a.json \\$basedir/\\$i/upload/ done rm -rf ./*; ## restart systemctl restart aaa.service systemctl restart bbb.service ''' // Not need often change zipfile="${sourcefile}.zip" last_outfile = 'last_outfile.log' childproject="baaa" envName="测试环境" tolist="xxx@xdf.cn" codedir = 'code_dir' def oper_checkout(SCM_TYPE='',SCM_URL='',SCM_BRANCH='',SCM_AUTH_PASS='',SCM_AUTH_USER=''){ if (SCM_TYPE =='git') { return checkout([$class: "GitSCM", branches: [[name: "${SCM_BRANCH}"]],doGenerateSubmoduleConfigurations: false, extensions: [],submoduleCfg: [], userRemoteConfigs: [[credentialsId: "${SCM_AUTH_PASS}", url: "${SCM_URL}"]]]) } else if (SCM_TYPE == 'tfs' ) { // need SCM_AUTH_USER args return checkout(scm: [$class: 'TeamFoundationServerScm',password: new hudson.util.Secret("${SCM_AUTH_PASS}"), projectPath: "${SCM_BRANCH}",serverUrl: "${SCM_URL}", useOverwrite: true, userName: "$SCM_AUTH_USER",workspaceName: 'Hudson-${JOB_NAME}']) } else if (SCM_TYPE == 'svn' ){ return checkout([$class: 'SubversionSCM', additionalCredentials: [], excludedCommitMessages: '', excludedRegions: '',excludedRevprop: '', excludedUsers: '', filterChangelog: false, ignoreDirPropChanges: false, includedRegions: '',locations: [[cancelProcessOnExternalsFail: true, credentialsId: "${SCM_AUTH_PASS}",depthOption: 'infinity', ignoreExternalsOption: true, local: '.',remote: "${SCM_URL}" ]],quietOperation: true, workspaceUpdater: [$class: 'CheckoutUpdater']]) } } def check_resource_label(){ if (RESOURCE_NODE_LABEL == ''){ RESOURCE_NODE_LABEL = COMPILE_LABEL } } check_resource_label() pipeline { agent { label COMPILE_LABEL } options { disableConcurrentBuilds() buildDiscarder logRotator(artifactNumToKeepStr: '', numToKeepStr: '30') } stages{ stage('checkout'){ steps{ script { if (codedir != '' ){ if (COMPILE_LABEL_TYPE == 'posix' ){ dirstr = sh(returnStdout: true, script:"ls -m").trim() }else { dir_temp = bat(returnStdout: true, script:"dir /B/L").trim().split('\n').toList() if (dir_temp.size() < 2 ){ dirstr = '' }else { dirstr = dir_temp[1..-1].join(',') } } if ( dirstr != '' && ! dirstr.contains(codedir) ){ if (COMPILE_LABEL_TYPE == 'posix' ){ sh 'rm -rf ./*' }else { bat 'del * /Q/S' dd_temp = bat(returnStdout: true, script:"dir /AD /B").trim().split('\n').tolist() if (dd_temp.size() < 2){ dd = [] }else { dd = dd_temp[1..-1] } if (dd != []){ dd.each { k -> bat "rd $k /Q /S" } } } } dir(codedir){ oper_checkout(SCM_TYPE,SCM_URL,SCM_BRANCH,SCM_AUTH_PASS,SCM_AUTH_USER) } }else { oper_checkout(SCM_TYPE,SCM_URL,SCM_BRANCH,SCM_AUTH_PASS,SCM_AUTH_USER) } } } } stage('build'){ steps{ script { if (COMPILE_LABEL_TYPE == 'posix') { sub_build_path= WORKSPACE + '/build' }else { sub_build_path= WORKSPACE + '\\build' } // BUILD_Server CHECK if (RESOURCE_NODE_LABEL == ''){ RESOURCE_NODE_LABEL = COMPILE_LABEL } // BUILD_server END println 'Dest Directory is: ' + sub_build_path if ( BUILD_SCRIPTS.trim() != ''){ buld_scripts_new = '' build_temp = BUILD_SCRIPTS.split(';|\n').toList() print build_temp sub_module_names = '' if (COMPILE_LABEL_TYPE == 'posix'){ sh """ if test ! -d build;then mkdir build;else rm -rf ./build/*;fi; if test -f ${zipfile} ;then rm -f ./${zipfile};fi; """ }else { bat """ if exist ${zipfile} ( del $zipfile /Q echo "delete $zipfile" ) if exist build ( rd build /Q /S echo "delete build output dirs" ) """ } build_temp.each { k -> print k subname = '' if (k.contains('publish')){ k_list = k.split('\\\\').toList() sk = k_list[-1] if (sk.endsWith('.csproj')){ subname = sk.replace('.csproj','') }else if (sk.endsWith('.sln')){ subname = sk.replace('.sln','') } dir(codedir){ if (COMPILE_LABEL_TYPE == 'posix') { k_n = k + ' -o ' + sub_build_path + '/' + subname sh "$k_n" }else { k_n = k + ' -o ' + sub_build_path + '\\' + subname print 'k_n =' + k_n bat "$k_n" } } }else { dir(codedir){ if (COMPILE_LABEL_TYPE == 'posix') { sh "$k" }else { bat "$k" } } } } if (COMPILE_LABEL_TYPE == 'posix'){ sh """ zip -qry $zipfile ${sub_build_path}/* """ }else { bat """ 7z a $zipfile ${sub_build_path}\\* """ } stash includes: "$zipfile", name: "$zipfile" rvfind = '' } } } } stage('service oper'){ agent { label RESOURCE_NODE_LABEL } steps{ script{ if ( RESOURCE_NODE_LABEL == COMPILE_LABEL ){ print 'deploy host not set!!' }else{ // SET ENV if (set_env.trim() != ''){ envs = set_env.split(';|\n').toList() envs.each { ka -> if ( ka.contains('=')){ envstr = 'env.' + ka.trim() //evaluate('def '+ka) evaluate(envstr) } } } if (unzip_path.startsWith('$')){ unzip_path = evaluate(unzip_path.replace('$','').replace('{','').replace('}','')) } if (config_path.startsWith('$')){ config_path = evaluate(config_path.replace('$','').replace('{','').replace('}','')) } // SET END unstash "$zipfile" if (WORKSPACE.startsWith('/')){ RESOURCE_LABEL_TYPE = 'posix' }else { RESOURCE_LABEL_TYPE = 'nt' } if ( RESOURCE_LABEL_TYPE == 'posix' ){ if (unzip_path != '' && unzip_path.startsWith('/') ) { def rvconfig = '' config_path = config_path.trim() env.unzip_path = unzip_path opuser = sh returnStdout: true,script:''' if test $(getfacl $unzip_path| wc -l) -gt 0 ;then rv=$(getfacl $unzip_path 2>/dev/null | egrep '^# owner'| awk -F: -v ORS=" " '{print $2}'); echo $rv; else echo 'You need check acl.x86_64 package or Check directory ${unzip_path} !!!' fi ''' if ( opuser.split(' ').size() >1 ){ println opuser opuser = '' }else{ println "Directory ${unzip_path} owner user is :" + opuser opuser = opuser.trim() } if (config_path != ''){ if (!config_path.endsWith('/')){ config_path += '/' } rvconfig = sh(returnStdout: true, script: "ls -m $config_path 2> /dev/null|| echo 'nouse'").trim() } if ( stop_script != '' ){ rvstop = sh returnStatus: true,script: """ sudo su -c "${stop_script}" """ echo 'RVSTOP=' + rvstop } if (! unzip_path.endsWith('/')){ unzip_path += '/' } sh """ sudo su - -c "cd ${unzip_path};rm -rf ./*" """ sh """ sudo su - ${opuser} -c "cd ${unzip_path};unzip -oq ${workspace}/$zipfile;mv ${sourcefile}/* .;rm -rf ./${sourcefile}" """ if (rvconfig != '' && rvconfig != 'nouse') { for (config in rvconfig.split(',')){ config = config.trim() if (config != ''){ config_absolute = config_path + config if (opuser != '' && opuser != 'root') { sh """ sudo su -c "cd ${unzip_path};cp -rf $config_absolute .;chown -R ${opuser}:${opuser} $config" """ } else { sh """ sudo su -c "cd ${unzip_path};cp -rf $config_absolute .;" """ } } } } }else { env.zipfile = zipfile env.sourcefile = sourcefile } sh """ sudo su -c "${start_script}" """ }else { // Run windows Resoure if (unzip_path != '' && !unzip_path.startsWith('nouse') ) { def rvconfig = '' config_path = config_path.trim() env.unzip_path = unzip_path if ( stop_script != '' ){ rvstop = bat returnStatus: true,script: """ ${stop_script} """ echo 'RVSTOP=' + rvstop } bat """ del $unzip_path\\* /Q /S 7z x "$zipfile" -y -o"$unzip_path" xcopy $unzip_path\\$sourcefile\\* $unzip_path /E /Y\r\n rd $unzip_path\\$sourcefile /Q /S pause """ if ( config_path != '' && !config_path.startsWith('nouse') ){ print "Copy configfile to " bat """ xcopy $config_path\\* $unzip_path /E /Y\r\n pause """ } }else { env.zipfile = zipfile env.sourcefile = sourcefile } bat """ ${start_script} pause """ } } } } } stage('up-file'){ agent { label LFS_NODE_LABEL } steps { script { if ( rvfind != 'path_err' ) { unstash "$zipfile" envStr=pack_dir_in_lfs.split('/')[-1].trim() if ( envStr != 'env_test_nouse') { println 'env: ' + envName + ', package name : ' + zipfile + ' lfs put file' sh """ if test ! -d ${pack_dir_on_server}/${pack_lfs_project};then sudo su -c " cd ${pack_dir_on_server}; git clone ${pack_lfs_remote}/${pack_lfs_project}.git; " fi """ sh """ sudo su -c "set -e;cd ${pack_dir_on_server}/${pack_lfs_project}; if test ! -d ${pack_dir_in_lfs};then mkdir -p ${pack_dir_in_lfs};fi; cd ${pack_dir_in_lfs}; if test ! -d ${BUILD_NUMBER};then mkdir ${BUILD_NUMBER};fi; cd $BUILD_NUMBER; cp ${workspace}/$zipfile .; git add -f *; git commit -m ' cis code OutFile build: $BUILD_NUMBER'; git push;" """ } else { println 'env: ' + envStr + ', package name : ' + zipfile + ' not need put file' } }else{ print 'Not have zipfile!!' } } } } } post{ always{ script { def codel = '' def code = [] change_html='${CHANGES,showPaths=true,showDependencies=true,format="<pre><ul><li>提交ID: %r</li><li>提交人:%a</li><li>提交时间:%d</li><li>提交信息:%m</li><li>提交文件:<br />%p</li></ul></pre>",pathFormat=" %p <br />"}' result = currentBuild.currentResult status = '${BUILD_STATUS}' extcode = '' if (result == 'SUCCESS'){ color = 'green' result_cn = '构建成功' }else if (result == 'FAILURE'){ color = 'red' result_cn = '构建失败' extcode = ''' <tr> <td><b><font color="#0B610B">构建日志 :</font></b> <hr size="2" width="100%" align="center" /></td> </tr> <tr> <td><textarea cols="150" rows="30" readonly="readonly" style="font-family: Courier New">${BUILD_LOG}</textarea> </td> </tr> ''' }else { color = 'blue' result_cn = '构建异常' } if ( RESOURCE_NODE_LABEL == COMPILE_LABEL ){ result_cn = result_cn + '(无程序部署)' } emailext(body: """ <html> <body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0"> <table width="95%" cellpadding="0" cellspacing="0" style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif"> <tr> <td><br /> <b><font color="#0B610B">构建信息</font></b> <hr size="2" width="100%" align="center" /></td> </tr> <tr> <td> <ul> <li>构建名称:${childproject}-${envName}</li> <li>构建结果:<span style="color:${color}"> ${status}</span></li> <li>构建编号:${BUILD_NUMBER} </li> <li>变更记录:${change_html}</li> </ul> </td> </tr> ${extcode} </table> </body> </html>""",subject: "${childproject}-${envName}-${result_cn}",to: "${tolist}",recipientProviders: [[$class: 'DevelopersRecipientProvider']]) } } } }