pipeline语法之environment,dir(),deleteDir()方法,readJSON,writeJSON

一 environment指令指定一系列键值对,这些对值将被定义为所有步骤的环境变量或阶段特定步骤

environment{…}, 大括号里面写一些键值对,也就是定义一些变量并赋值,这些变量就是环境变量。环境变量的作用范围,取决你environment{…}所写的位置,你可以写在顶层环境变量,让所有的stage下的step共享这些变量,也可以单独定义在某一个stage下,只能供这个stage去调用变量,其他的stage不能共享这些变量。一般来说,我们基本上上定义全局环境变量,如果是局部环境变量,我们直接用def关键字声明就可以,没必要放environment{…}里面。

//全局
pipeline { agent any environment { unit_test
= true } stages { stage('Example') { steps { script{ if(unit_test == true){ println "变量为真 " } }} } } }

 二 dir ,deleteDir

dir()方法:就是改变当前的工作目录,在dir语句块里执行的其他路径或者相对路径

deleteDir()方法:默认递归删除WORKSPACE下的文件和文件夹,没有参数,使用这个方法会留下一个后遗症:

       执行这个job的时候,你之前已经在这个工作目录下面,你再建一个目录就会报错:mkdir: 无法创建目录"testdata": 没有那个文件或目录,这是个很矛盾的报错

       解决方法:使用cd重新切换到当前目录,再执行mkdir操作

举例如下:

pipeline{
    
    agent any
    stages{
        stage("deleteDir") {
            steps{
                script{
                    println env.WORKSPACE
                    dir("${env.WORKSPACE}/testdata"){   //切换到当前工作目录下的testdata目录
                       sh "pwd"                         //sh命令可以 sh "command..." 也可以 sh("command....")
                    }
                    sh("ls -al ${env.WORKSPACE}")
                    deleteDir()  // clean up current work directory   //清空目录
                    sh("ls -al ${env.WORKSPACE}")
                }
            }
        }
    }
}

执行结果

Started by user admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /root/.jenkins/workspace/pipe-example
[Pipeline] {
[Pipeline] stage
[Pipeline] { (deleteDir)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
/root/.jenkins/workspace/pipe-example     #println env.WORKSPACE
[Pipeline] dir Running in /root/.jenkins/workspace/pipe-example/testdata 
[Pipeline] { [Pipeline] sh
+ pwd /root/.jenkins/workspace/pipe-example/testdata [Pipeline] }
[Pipeline]
// dir
[Pipeline] sh
+ ls -al /root/.jenkins/workspace/pipe-example
总用量 4
drwxr-xr-x  4 root root   42 9月   4 11:33 .
drwxr-xr-x 28 root root 4096 9月   4 11:24 ..
drwxr-xr-x  2 root root   22 9月   4 11:28 testdata
drwxr-xr-x  2 root root    6 9月   4 11:33 testdata@tmp
[Pipeline] deleteDir
[Pipeline] sh
+ ls -al /root/.jenkins/workspace/pipe-example
总用量 4
drwxr-xr-x  2 root root    6 9月   4 11:33 .
drwxr-xr-x 28 root root 4096 9月   4 11:33 ..
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
 

 三 readJSON,writeJSON

要使用这两个方法,必须安装插件Pipeline Utility Steps,否则报错:java.lang.NoSuchMethodError: No such DSL method 'readJSON'

我们先来使用readJSON

1 先建一个json文件,路径在工作目录的testdata/test_json.json

{
"NAME":"xinxin",
"AGE":30,
"CITY":"Beijing",
"GENDER":"male"
}

2 重写方法,有两种,路径放在工作目录下面的module/pipeline-demo-module.groovy

import hudson.model.*;
 
 
def find_files(filetype) {
    
    def files = findFiles(glob:filetype)
    for (file in files) {
        println file.name
    }
}
 
def read_json_file(file_path) {               //读取文件的情况
    def propMap = readJSON file : file_path
    propMap.each {
        println ( it.key + " = " + it.value )
    }
}
 
def read_json_file2(json_string) {           //读取字符串的情况
    def propMap = readJSON text : json_string
    propMap.each {
        println ( it.key + " = " + it.value )
    }
}
return this;

最后设置pipeline stage文件内容

import hudson.model.*;
 
println env.JOB_NAME
println env.BUILD_NUMBER
 
pipeline{
    
    agent any
    stages{
        stage("init") {
            steps{
                script{
                    model_test = load env.WORKSPACE + "/module/pipeline-demo-module.groovy" //采用路径的拼接来读取
                }
            }
        }
        stage("Parse json") {   //分别调用两种方式读取
            steps{
                script{
                    json_file = env.WORKSPACE + "/testdata/test_json.json"
                    model_test.read_json_file(json_file)
                    println "================================"
                    json_string = '{"NAME":"xinxin","AGE":30,"CITY":"Beijing","GENDER":"male"}'
                    model_test.read_json_file2(json_string)
                }
            }
        }
    }
}

 结果:

Started by user admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] echo
pipe-example
[Pipeline] echo
58
[Pipeline] node
Running on Jenkins in /root/.jenkins/workspace/pipe-example
[Pipeline] {
[Pipeline] stage
[Pipeline] { (init)
[Pipeline] script
[Pipeline] {
[Pipeline] load
[Pipeline] { (/root/.jenkins/workspace/pipe-example/module/pipeline-demo-module.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Parse json)
[Pipeline] script
[Pipeline] {
[Pipeline] readJSON
[Pipeline] echo
NAME = xinxin
[Pipeline] echo
AGE = 30
[Pipeline] echo
CITY = Beijing
[Pipeline] echo
GENDER = male
[Pipeline] echo
================================
[Pipeline] readJSON
[Pipeline] echo
NAME = xinxin
[Pipeline] echo
AGE = 30
[Pipeline] echo
CITY = Beijing
[Pipeline] echo
GENDER = male
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
View Code

 下面看看writeJSON

看名称就知道是是将json格式的文件或者字符串写入文件

wirteJSON方法有两个必须的字段,分别是json和file,

json是一个json对象,是你需要把这个json写入到文件的内容,

第二个file字段是一个文件的路径,这个文件肯定在jenkins的workspace范围之内。

第三个字段pretty是可选,也就是可以选择把json对象插入到一个指定的位置。

1 修改module/pipeline-demo-module.groovy 

import hudson.model.*;
import groovy.json.*;  //这个省略,在使用JsonOutput类的时候必须导入
 
 
def find_files(filetype) {
    
    def files = findFiles(glob:filetype)
    for (file in files) {
        println file.name
    }
}
 
def read_json_file(file_path) {
    def propMap = readJSON file : file_path
    propMap.each {
        println ( it.key + " = " + it.value )
    }
}
 
def read_json_file2(json_string) {
    def propMap = readJSON text : json_string
    propMap.each {
        println ( it.key + " = " + it.value )
    }
}
def write_json_to_file(input_json, tofile_path) {   //增加的部分
    def input = ''
    if(input_json.toString().endsWith(".json")) {
        input = readJSON file : input_json
    }else {
        //def output = new JsonOutput()
                //def new_json_object = output.toJson(input_json)
        //input = new_json_object
                input = readJSON text : input_json
    }
    writeJSON file: tofile_path, json: input
}

return this;

2 修改pipeline stage文件内容

println env.JOB_NAME
println env.BUILD_NUMBER
 
pipeline{
    
    agent any
    stages{
        stage("init") {
            steps{
                script{
                    model_test = load env.WORKSPACE + "/module/pipeline-demo-module.groovy"
                }
            }
        }
        stage("write json") {
            steps{
                script{
                    json_file = env.WORKSPACE + "/testdata/test_json.json"
                    tojson_file = env.WORKSPACE + "/testdata/new_json.json"   //new_json.json文件可以事先不存在,它会自动创建
                    model_test.write_json_to_file(json_file,tojson_file)
                    println "================================"
                    json_string = '{"NAME":"xinxin","AGE":30,"CITY":"Beijing","GENDER":"male"}'
                    tojson_file = env.WORKSPACE + "/testdata/new_json1.json"
                    model_test.write_json_to_file(json_string,tojson_file)
                }
            }
        }
    }
}

执行结果

Started by user admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] echo
pipe-example
[Pipeline] echo
65
[Pipeline] node
Running on Jenkins in /root/.jenkins/workspace/pipe-example
[Pipeline] {
[Pipeline] stage
[Pipeline] { (init)
[Pipeline] script
[Pipeline] {
[Pipeline] load
[Pipeline] { (/root/.jenkins/workspace/pipe-example/module/pipeline-demo-module.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (write json)
[Pipeline] script
[Pipeline] {
[Pipeline] readJSON
[Pipeline] writeJSON
[Pipeline] echo
================================
[Pipeline] readJSON
[Pipeline] writeJSON
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
View Code

查看系统上面的文件

[root@localhost testdata]# ls
new_json1.json  new_json.json  test_json.json
[root@localhost testdata]# cat new_json.json 
{"NAME":"xinxin","AGE":30,"CITY":"Beijing","GENDER":"male"}[root@localhost testdata]# 
[root@localhost testdata]# cat new_json1.json 
{"NAME":"xinxin","AGE":30,"CITY":"Beijing","GENDER":"male"}[root@localhost testdata]# 
原文地址:https://www.cnblogs.com/mmyy-blog/p/11454893.html