【问题标题】:How to put value in variable in Jenkinsfile with sshcommand如何使用 sshcommand 将值放入 Jenkinsfile 中的变量
【发布时间】:2021-05-26 10:00:14
【问题描述】:

我想在 Jenkins 中创建一个管道,用于获取使用 sshCommand 执行的命令的值。 我在远程服务器上有一个这样的文件:

VALUE 11

这是我的管道:

pipeline {
agent any

stages {
    stage('Get Init') {
        steps {
            withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId:'xxxxxxx', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
                script {
                    def remote = [:]
                    remote.name = 'xxxxxx'
                    remote.host = 'xxxxxx'
                    remote.user = USERNAME
                    remote.port = 22
                    remote.password = PASSWORD
                    remote.allowAnyHosts = true
                    sshCommand remote: remote, command: "init=\$(cat /var/log/myFile |  grep VALUE | awk '{print \$2}')"
                }
            }
        }
    }
    stage("Test") {
        steps {
            script {
                    test = sh(script "echo $init")
                }
            }
        }
    }

    
}

}

我想在变量中获取“11”,以便稍后在我的 Jenkinsfile 中进行比较。如何做到这一点?

【问题讨论】:

    标签: jenkins jenkins-pipeline


    【解决方案1】:

    您可以通过以下方式使用:
    示例:
    def Result = sshCommand remote: remote, command: "<Your command>"

    # Declare variable init
    def init
    pipeline {
    agent any
    stages {
        stage('Get Init') {
            steps {
                withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId:'xxxxxxx', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
                    script {
                        def remote = [:]
                        remote.name = 'xxxxxx'
                        remote.host = 'xxxxxx'
                        remote.user = USERNAME
                        remote.port = 22
                        remote.password = PASSWORD
                        remote.allowAnyHosts = true
                        # Execute your command and take return value in the init variable
                        init= sshCommand remote: remote, command: "cat /var/log/myFile |  grep VALUE | awk '{print \$2}')"
                        echo "Initial Value: " + init
                    }
                }
            }
        }
        stage("Test") {
            steps {
                script {
                        test = sh(script "echo ${init}")
                    }
                }
            }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 2018-10-13
      • 1970-01-01
      • 2017-02-04
      • 2017-12-22
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多