pipeline中读取文件内容

avatar 2023年12月1日18:01:04 评论 160 次浏览

前面已经说过,在每次发布服务时,需要选择一下分支,还要选择服务名称,只所以这样选择是因为避免构建的时候发布了没必要的服务,但是我们又需要明白服务名称,这里就尝试是否可以在pipeline中能够读取文件内容,只要读取到文件内容,我们直接发布根据读取到文件内容发布服务即可,看下面的示例。

 pipeline {
     agent any
     options {
         timeout(time: 60, unit: 'MINUTES') //SECONDS, MINUTES, HOURS
         timestamps () 
     }
     environment {
         fileContent = readFile '/apps/works/data/deploy'
     }
     stages {
         stage('Docker build') {
             steps {
                 script {
                     //def file = readFile '/apps/works/data/deploy'
                     //def lines = file.readLines().findAll { it.trim() != '' }
                     //def lines = file.readLines()
                     def lines = fileContent.readLines()
                     echo "$lines"
                     for (line in lines){
                         def items = line.split(',').findAll { it.trim() != '' }
                         for (item in items) {
                             echo "Processing line: ${item}"
                         }
                        
                         
                     }
                 }
             }
         }
         stage('k8s deploy') {
             steps {
                 sh 'echo "k8s yml"'
                 script {
                     def lines = fileContent.readLines()
                     for (line in lines){
                         //portserver(item)
                         def items = line.split(',').findAll { it.trim() != '' }
                         for (item in items) {
                             echo "Processing line: ${item}"
                         }
                         
                     }
                 }
             }
         }
     }
 }

为了方便所有的stage可以读取文件内容,所以我们需要把读取文件内容的这个变量放到全局中,方便stage可以复用。然后通过fileContent.readLines()读取文件所有内容,然后进行取行或者分隔符在循环,这样做的目的是为了方便名字别写错了。而且针对全局变量可以多次使用,看一下输出结果。

这个是我的部分循环,因为篇幅的问题就没有过多截图,这里确实把文件的内容都读取出来了,而且进行了循环,只要把文件内容缓存自己的服务即可。好了,没有了,先写到这吧

avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: