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

k97glaaz  于 2023-10-20  发布在  Jenkins
关注(0)|答案(1)|浏览(190)

我正在一个声明性的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.
e5nszbig

e5nszbig1#

我已经编写了一个简单的管道脚本来显示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}"
          }
      }
   }
}

输出量:

相关问题