簡體   English   中英

如何在 Jenkins 腳本管道中將參數傳遞給 bash 腳本並將憑據設置為遠程主機登錄

[英]How to pass paramaters to bash script in a Jenkins scripted pipeline and set the credentials to remote host login

我是 Jenkins 腳本化管道的新手。 下面是我試圖在遠程主機上執行的代碼。 我想知道兩件事:

1)如何在不進行硬編碼的情況下傳遞憑據。 不像我在下面的腳本中所做的那樣。

2)如何將參數傳遞給我的 test.sh 腳本。 意思是我想把它作為

sshScript remote: remote, script: "myscript.sh {version} "

更新:

下面是我得到的腳本:

node {
        properties([
        parameters([
            string(name: 'version', defaultValue: '', description: 'Enter the version in x.y.z format')
        ])
    ]) 
         version = params.version.trim()
         def remote = [:]
         remote.name = 'Filetransfer'
         remote.host = 'X.X.XX.XXXX'
         remote.allowAnyHosts = true

     withCredentials([usernamePassword(credentialsId: 'saltmaster', passwordVariable: 'password', usernameVariable: 'ops')]) {
        remote.user = ops
        remote.password = password    
            stage('Filetransfer') {
                  sshCommand remote: remote, command: "hostname" 
                //sshCommand remote: remote, command: "whoami"
                  sshGet remote: remote, from: '/srv/salt/tm-server/files/docker-compose.yaml', into: '/home/jenkins/jenkins-data/docker-compose.yaml', override: true
                 //sshScript remote: remote, script: '/home/jenkins/jenkins-data/rebuilt_dockercompose.sh "${version}"'

            }

                sh 'echo "Executing the script now ..."'
                sh "echo Current version: ${version}"
                sh "/home/jenkins/jenkins-data/rebuilt_dockercompose.sh //"${version}//""   

    }
}


這是您可以執行的操作:

無需硬編碼即可傳遞憑據

  1. 在您的 Jenkins 實例中, 添加類型為SSH Username 和 private key的全局憑證。
  2. 在您的管道中,使用憑據綁定插件中的withCredentials([sshUserPrivateKey...])指令來傳遞憑據。 這也將屏蔽控制台 output 中的憑據。

傳遞用戶定義的參數

  1. 由於您的管道是腳本化管道,因此請使用包裹在properties([])塊中的parameters([string...]) ) 塊以允許用戶將版本作為字符串參數輸入。
  2. 將參數作為參數傳遞給您的 shell 腳本。

修改后的流水線腳本

node {
    properties([
        parameters([
            string(name: 'version', defaultValue: '', description: 'Enter the version in x.y.z format')
        ])
    ]) 
    def remote = [:]
    remote.name = 'testPlugin'
    remote.host = 'x.x.x.x'
    remote.allowAnyHosts = true

    withCredentials([
        sshUserPrivateKey(credentialsId: 'ssh-credentials', usernameVariable: 'ssh-user', passphraseVariable: 'ssh-pass')
    ]) {
        remote.user = ssh-user
        remote.password = ssh-pass

        stage('testPlugin') {
            sshPut remote: remote, from: 'myscript.sh', into: '.'
            sshScript remote: remote, script: "myscript.sh ${version}"               
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM