如何在Jenkins管道中将参数传递给远程脚本

问题描述

我正在声明性的jenkins管道上尝试登录远程主机并执行shell脚本。以下是示例代码段。我想知道如何将参数传递给我的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脚本中变量的用法。

管道脚本:

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}"
          }
      }
   }
}

输出:

enter image description here