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

一 environment指令指定一系列鍵值對,這些對值將被定義爲全部步驟的環境變量或階段特定步驟java

environment{…}, 大括號裏面寫一些鍵值對,也就是定義一些變量並賦值,這些變量就是環境變量。環境變量的做用範圍,取決你environment{…}所寫的位置,你能夠寫在頂層環境變量,讓全部的stage下的step共享這些變量,也能夠單獨定義在某一個stage下,只能供這個stage去調用變量,其餘的stage不能共享這些變量。通常來講,咱們基本上上定義全局環境變量,若是是局部環境變量,咱們直接用def關鍵字聲明就能夠,不必放environment{…}裏面。node

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

 二 dir ,deleteDirjson

dir()方法:就是改變當前的工做目錄,在dir語句塊裏執行的其餘路徑或者相對路徑ide

deleteDir()方法:默認遞歸刪除WORKSPACE下的文件和文件夾,沒有參數,使用這個方法會留下一個後遺症:this

       執行這個job的時候,你以前已經在這個工做目錄下面,你再建一個目錄就會報錯:mkdir: 沒法建立目錄"testdata": 沒有那個文件或目錄,這是個很矛盾的報錯spa

       解決方法:使用cd從新切換到當前目錄,再執行mkdir操做插件

舉例以下:code

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,writeJSONblog

要使用這兩個方法,必須安裝插件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]# 
相關文章
相關標籤/搜索