如何将外壳变量值访问到Groovy管道脚本中 [英] How to access Shell variable value into Groovy pipeline script

查看:12
本文介绍了如何将外壳变量值访问到Groovy管道脚本中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我是Shell、Jenkins、Groovy管道的新手。我的要求是将文件文本读入到外壳脚本下的变量中,并且需要将该变量值传递出外壳脚本并在Groovy脚本中使用。

以下是我的代码:

stages
    {
        stage('example')
        
        {
            steps
            {
                script
                {
                    
                sh'''
                    #!/bin/bash
                    set +x                  
                    readVal=$(<$WORKSPACE/test.json)
                    echo "$readVal"        //this is priting my entire json successfully                  
                    
                  echo 'closing shell script'
                    
                ''' 
                    
                    
                    println WORKSPACE    /// this is printing my workspace value successfully 
                    
                    println readVal     // not working 
                    println env.readVal     // not working 
                    println $readVal     // not working 

                
                }
            }
        }
    }

如何从外壳中获取readVal的值以进行访问?

推荐答案

参见Jenkins, Pipeline Best Practices

A.解决方案:使用外壳步骤并返回标准输出,而不是使用[复杂函数]。该外壳如下所示:

def JsonReturn = sh label: '', returnStdout: true, script: 'echo "$LOCAL_FILE"| jq "$PARSING_QUERY"'

示例

pipeline {
    agent any

    stages {
        stage('example') {
            steps {
                script {
                    def readVal = sh script: 'echo "READ_VAL_VALUE"', returnStdout: true
                    echo readVal
                    println readVal
                }
            }
        }
    }
}

控制台输出

[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in C:UsersjenkinsAppDataLocalJenkins.jenkinsworkspacePipeline project
[Pipeline] {
[Pipeline] stage
[Pipeline] { (example)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ echo READ_VAL_VALUE
[Pipeline] echo
READ_VAL_VALUE

[Pipeline] echo
READ_VAL_VALUE

[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

这篇关于如何将外壳变量值访问到Groovy管道脚本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆