groovy Jenkins Pipeline Form JSON工作负载for CURL

myzjeezk  于 7个月前  发布在  Jenkins
关注(0)|答案(2)|浏览(65)

我正在尝试cURL内Jenkins管道沿着与数据。CURL命令如下所示

sh(script:'curl -H "Content-Type: application/json" -d '{ "token":"swqkm7f55v39g9kkdggkzs","duration":10, "platform":"android", "available_now":"true"}' https://device.pcloudy.com/api/devices'

这里的问题是在数据令牌字段,我想通过环境变量。比如说,我有可变的(env.authtoken),我在那里存储了我的令牌。这个令牌需要在curl中传递

sh(script:'curl -H "Content-Type: application/json" -d '{ "token":"${env.authtoken}","duration":10, "platform":"android", "available_now":"true"}' https://device.pcloudy.com/api/devices',returnStdout: true)

但是,这是一个意想不到的字符错误。实际上,我想执行如下语句

sh(script:"curl -H "Content-Type: application/json" -d '{ "token":"swqkm7f55v39g9kkdggkzs","duration":10, "platform":"android", "available_now":"true"}' https://device.pcloudy.com/api/devices"

而不是硬编码的值在令牌字段中,我想通过我的变量。感谢您的帮助!

5sxhfpxr

5sxhfpxr1#

我猜引号有问题。尝试以这种方式使用多行sh命令:

sh """
    curl -H "Content-Type: application/json" -d '{ "token":"${env.authtoken}","duration":10, "platform":"android", "available_now":"true"}' https://device.pcloudy.com/api/devices
"""

看看curl命令是否通过。如果是这样,那么您可以返回到原始命令,尝试修改它,以便引号不会过早终止命令。我猜问题在于您以'启动命令,并在-d之后再次使用它。这将中断curl命令。

vuv7lop3

vuv7lop32#

如果使用''将命令构造为字符串,那么如果要在内部使用它,必须对'的其余部分进行转义。
如果你使用""来构造字符串,也会发生同样的情况,那么就需要escap de "
在这两种情况下,都要用反斜杠将其转义:\'\"
例如,在您的第一个案例中:

sh(script:'curl -H "Content-Type: application/json" -d \'{ "token":"swqkm7f55v39g9kkdggkzs","duration":10, "platform":"android", "available_now":"true"}\' https://device.pcloudy.com/api/devices')

或者,如果你还想计算一些变量"""yourmultilinestring and ${somevariable}""",你可以尝试使用Groovy多行字符串'''yourmultilinestring'''或多行gstring,因为在这些情况下没有必要转义单引号或双引号。
为您的案例提供完整的工作样本:

pipeline {
    agent any
    
    environment {
        authtoken = 'swqkm7f55v39g9kkdggkzs'
    }

    stages {
        stage('Stage - Test curl') {
            steps {
                script {
                    sh(
                    script:"""
                    curl -H "Content-Type: application/json" -d '{ "token":"${env.authtoken}","duration":10, "platform":"android", "available_now":"true"}' https://device.pcloudy.com/api/devices
                    """)
                }
            }   
        }
    }
}

相关问题