簡體   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