groovy
/**
* Auther: luojiaao
*/
/**
* run command.
*
* This function executes shell based on the operating system.
*
* @param m Map containing trace/returnStdout/returnStatus/sops_var.
* @return Output of the command.
*/
run_vars = [:]
def run(Map m) {
is_unix = isUnix()
// Run Param
if (is_unix) {
if(m.trace){
arg_x="-x"
}else{
arg_x=""
}
} else {
if(m.trace){
arg_x=""
}else{
arg_x="@echo off"
}
}
// Replace Var to CMD
try{
def pattern_in = /\$\{(\w+?)\}/
def matcher_in = (m.cmd =~ pattern_in)
def list_matcher_in = []
if (matcher_in.find()){
for(sub_in in matcher_in){
if(run_vars.get(sub_in[1], 'NoFind') != 'NoFind'){
list_matcher_in.add(sub_in[1])
}
}
for(i in list_matcher_in.toSet()){
m.cmd = m.cmd.replace('${'+i+'}', run_vars.get(i))
}
}
}catch(NotSerializableException ex){}
// Run
if (m.returnStdout){
// get std
if (is_unix) {
return sh(returnStdout: true, script: "#!/bin/sh ${arg_x}\n${m.cmd}")
} else {
return bat(returnStdout: true, script: "${arg_x}\n${m.cmd}")
}
}else if (m.returnStatus){
// get status
if (is_unix) {
return sh(returnStatus: true, script: "#!/bin/sh ${arg_x}\n${m.cmd}")
} else {
return bat(returnStatus: true, script: "${arg_x}\n${m.cmd}")
}
}else if (m.sops_var){
// get sops
def out = ""
if (is_unix) {
out = sh(returnStdout: true ,script: "#!/bin/sh ${arg_x}\n${m.cmd}")
} else {
out = bat(returnStdout: true ,script: "${arg_x}\n${m.cmd}")
}
println(out)
// save var to global from mark of SOPS_VAR
try{
def pattern_out = /<SOPS_VAR>(\w+?):(.+?)<\/SOPS_VAR>/
def matcher_out = (out =~ pattern_out)
if (matcher_out.find()){
for(sub_out in matcher_out){
run_vars[sub_out[1]] = sub_out[2]
}
}
}catch(NotSerializableException ex){}
}else{
if (is_unix) {
sh(script: "#!/bin/sh ${arg_x}\n${m.cmd}")
} else {
bat(script: "${arg_x}\n${m.cmd}")
}
}
}
pipeline{
agent any
options{
skipDefaultCheckout()
}
stages {
stage('SAVE') {
steps {
script {
// 保存VAR变量值为AAAAA
run(cmd: 'echo "<SOPS_VAR>VAR:AAAAA</SOPS_VAR>"', sops_var: true)
}
}
}
stage('PRINT') {
steps {
script {
// 执行之前会替换VAR的值
run(cmd: 'echo ${VAR}',trace: true)
}
}
}
}
}