1. 程式人生 > >Jenkins高階篇之Pipeline方法篇-Pipeline Utility Steps-3-方法readProperties

Jenkins高階篇之Pipeline方法篇-Pipeline Utility Steps-3-方法readProperties

這篇繼續來學習檔案相關操作的方法,前面學習了JSON格式檔案的讀和寫,這麼介紹一個讀取properties檔案,這個方法特別是適合Java專案,一個Java專案很多配置檔案可能是採用properties型別來寫入鍵值對資料。

1.方法readProperties

就是從一個xxx.properties檔案去讀取內容出來,得到是一個map物件。下面我現在/testdata資料夾下建立一個test.properties檔案,裡面寫入這些內容。

Name = Anthony
Aget = 18
City = Beijing
Agend = male

module 裡面解析讀取properties的方法如下。

def read_properties(properties_file) {
	 def props = readProperties interpolate: true, file: properties_file
	 props.each {
		println ( it.key + " = " + it.value )
	 }
}

pipeline 讀取properties的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 + "/pipeline/module/pipeline-demo-module.groovy"
				}
			}
		}
		stage("read properties") {
			steps{
				script{
					properties_file = env.WORKSPACE + "/testdata/test.properties"
					model_test.read_properties(properties_file)
					println "================================"
				}
			}
		}
	}
}


我的jenkins 測試job地址:http://65.49.216.200:8080/job/pipeline-project-demo/47/console

你通過日誌可以看到具體測試結果,程式碼可以看replay下指令碼,或者github專案。

2.方法touch

這個touch就是linux下的touch的作用,建立一個檔案(如果不存在),併產生時間戳。

下面來舉例,執行一個stage來測試下。

stage("touch file") {
			steps{
				script{
					touch_file = env.WORKSPACE + "/testdata/"+ env.BUILD_NUMBER +".log"
					touch touch_file
				}
			}
		}

把這個加到原來的pipeline stage檔案,執行,然後去自己jenkins 節點機器下找到剛剛touch的檔案

[[email protected] ~]# cd /var/lib/jenkins/workspace/pipeline-project-demo/testdata/
[[email protected] testdata]# ls
123.txt  abc.log  new_json.json   test.properties
48.log   a.log    test_json.json
[[email protected] testdata]# cat 48.log
[[email protected] testdata]# ls -l 48.log
-rw-r--r-- 1 jenkins jenkins 0 Nov  8 10:08 48.log
[[email protected] testdata]#

我的測試jenkins job:http://65.49.216.200:8080/job/pipeline-project-demo/48/

這裡需要提醒的哈,touch的檔案在jenkins 節點機器不是在程式碼庫,也不是在你eclipse專案裡。