繁体   English   中英

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

[英]How to pass paramaters to remote script in a Jenkins pipeline

我正在开发一个声明性 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}"
          }
      }
   }
}

输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM