jenkins pipeline 动态变量赋值写法

 environment {
        _version = createVersion()
       // COMMT= sh(  returnStdout: true, script: 'git log --oneline -2 | awk \'{print \$1}\'')
       // HTTPD= sh(  returnStdout: true, script: 'git rev-parse  HEAD')
        lastsha= sh(  returnStdout: true, script: 'git rev-parse HEAD~')
        nowsha=sh(  returnStdout: true, script: 'git rev-parse HEAD')
        modulename='11111111111222222222'
    }
  def foundFiles=[]
                 foundFiles = sh(script: 'ls -1 /var/lib/jenkins/workspace/xx-test-pom', 
            returnStdout: true).trim()
                 echo "foundFileslist==: ${foundFiles}"
                 def foundlist=foundFiles.split()
                                
                  echo "modulename-old=:${env.modulename}"     
                 for (int j = 0;j < foundlist.size();++j){
                     def t=foundlist[j]
                     withEnv(["modulename=${t}"]) { // it can override any env variable 
                       echo "modulename-2 = ${env.modulename}"  
 try {
                          sh(script: "sudo cp ${oldpath}/${env.modulename}/pom.xml ${prjpath}/${env.modulename}/pom.xml", returnStdout: false)
                        }finally {
                        	println "一定会执行到这里来error:cp ${oldpath}/${env.modulename}/pom.xml ${prjpath}/${env.modulename}/"
                        }           
}}
                       
                

主要有2点需要注意:

             1.使用 withEnv(["modulename=${t}"]) {} 方式,给变量动态赋值

             2.  sh(script: "sudo cp ${oldpath}/${env.modulename}/pom.xml ${prjpath}/${env.modulename}/pom.xml", returnStdout: false) 执行脚本 script 后面 的命令行使用双引号,单引号会报错,切记

 
                      

                  

你可能感兴趣的:(jenkins,运维)