詹金斯管道sh中没有填充变量

时间:2019-07-14 15:10:11

标签: shell variables jenkins curl jenkins-pipeline

当我在sh脚本中执行curl时,我没有下面的代码,并且以前阶段的用户名,pwd和modulename都没有填充。

请让我知道我需要解决什么

def USERNAME
def PASSWORD
def MODULE_NAME
node {
    try {

        stage('userAuth') {
                    withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'ID-Creds',
                                  usernameVariable: 'user', passwordVariable: 'pwd']]) {
                        USERNAME="$user"
                        PASSWORD="$pwd"
                        echo "$USERNAME:$PASSWORD" //This is fine
                    }


        }

        stage('readPOM') {
            def pom = readMavenPom file: 'pom.xml'
            MODULE_NAME = pom.module
            echo "$MODULE_NAME"  //This is printing fine
        }

        stage('do curl') {
            def revision = sh(script: '''
                              AUTH="$USERNAME:$PASSWORD"; //Not getting populated getting empty
                              RespInfo=$(curl -u $AUTH  "https://host/apis/${MODULE_NAME}/deployments"); //Not getting populated getting empty for modulename
                              currntRev=$(jq -r .revision[0].name <<< "${RespInfo}"); 
                              echo $currntRev 
                              ''',returnStdout: true).split()
        }
    } 
    catch (e) {
        throw e
    } finally {
    }
}

2 个答案:

答案 0 :(得分:1)

您必须使用双引号(""")来应用字符串插值:

def revision = sh(script: """
    AUTH=\"$USERNAME:$PASSWORD\"; //Not getting populated getting empty

答案 1 :(得分:1)

一种更简单的方法是如下连接两个字符串:

def revision = sh(
  returnStdout: true,
  script: '''
    AUTH="$user:$pwd";
    RespInfo=$(curl -u "$AUTH"  "https://host/apis/''' + MODULE_NAME + '''/deployments");
    currntRev=$(jq -r .revision[0].name <<< "${RespInfo}"); 
    echo $currntRev 
  '''
).split()

注意:包裹在"""中的字符串将被扩展,但包裹在'''中的字符串则不会被扩展

USERNAMEPASSWORD是Groovy变量,当将它们包装在"""""中时,Groovy执行程序将在执行脚本之前对其进行扩展。

userpwd是Shell变量,使用'''

时应使用Shell变量