【问题标题】:How to pass paramaters to remote script in a Jenkins pipeline如何将参数传递给 Jenkins 管道中的远程脚本
【发布时间】:2021-01-11 06:07:55
【问题描述】:

我正在开发一个声明式 jenkins 管道,我正在尝试登录到远程主机并执行 shell 脚本。下面是示例 sn-p。我想知道如何将参数传递给我的 script.sh 脚本。

#!/bin/bash
echo "argument $1"

下面是流水线脚本


hosts = [“x.x.x”, “x.x.x”]
pipeline {
  agent { node { label 'docker' } }

  parameters {
    choice(name: 'stageparam', choices: ['build', 'deploy'], description: ‘xyz’)
    string(name: 'Username', defaultValue: ‘abc’, description: 'enter username')
  }

  
  stages {
    stage('Setup') {
      steps {
        script {
          pom = getPom(effective: false)
        }
      }
    }
   
    stage('Deploy') {
      steps {
        script {

          def targetServers = null
          if (stageparam == "deploy") {
            targetServers = hosts
          } 

          targetServers.each { server ->
            echo "Server : ${server}"
            def remote = [:]
            remote.name = ‘server’
            remote.host = server
            remote.user = Username
            def pass = passwordParameter description: "Enter password for user ${remote.user} "
            remote.password = pass
            remote.allowAnyHosts = true
            stage('Remote SSH') {
                         sshPut remote: remote, from: ‘./script.sh', into: '.'
              sshScript remote: remote, script: "doc.sh ${Username}"
            }
          }
        }
      }
    }
  }
}

执行脚本时出现以下错误


/home/jenkins/workspace/script.sh Username does not exist.

【问题讨论】:

    标签: bash jenkins ssh jenkins-pipeline remote-server


    【解决方案1】:

    我写了一个简单的管道脚本来展示 bash 脚本中变量的用法。

    流水线脚本:

    pipeline {
       agent any
    parameters {
        choice(name: 'stageparam', choices: ['build', 'deploy'], description: 'enter stageparam')
        string(name: 'USERNAME', defaultValue: 'abc', description: 'enter username')
      }
       stages {
          
          stage('Git Pull')
          {
             steps {
                 checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'gitlab-test', url: 'http://localhost:8076/test-upgrade.git']]])
             } 
          }
          stage('Run the python script') {
              steps {
                  sh 'chmod 777 test.py'
                  sh "python test.py ${env.WORKSPACE}"
              }
          }
          stage('Run the bash script') {
              steps {
                  sh 'chmod 777 run.sh'
                  sh "./run.sh ${env.USERNAME}"
              }
          }
       }
    }
    

    输出:

    【讨论】:

    • 感谢您的回复。我的情况完全不同。我想使用 jenkins 在远程主机中执行我的脚本。
    猜你喜欢
    • 2016-07-03
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    相关资源
    最近更新 更多