Jenkins 声明式管道 ssh 代理插件

时间:2021-06-23 01:23:18

标签: jenkins ssh jenkins-pipeline jenkins-plugins sudo

我正在尝试使用 sshagent 插件部署到远程服务器。

当使用以下语法时,我得到

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                sshagent(['nginx-ec2']) {
                    // some block
                    sh "ssh -o StrictHostKeyChecking=no ubuntu@<host_ip>"
                    sh "whoami"
                }
            }
        }
    }
}

获取输出:

[Pipeline] sh (hide)
+ whoami
jenkins

虽然我希望使用提供的凭据在远程服务器上运行脚本!!

所以,我不得不以这种方式运行它

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                sshagent(['nginx-ec2']) {
                    // some block
                    sh "ssh -o StrictHostKeyChecking=no -l ubuntu <host_ip> 'whoami && \
                    sudo apt update  && sudo apt install -y docker.io && \
                    sudo usermod -aG docker ubuntu && \
                    source .bashrc && \
                    docker run -d nginx'"
                }
            }
        }
    }
}

是否有任何“干净”的方法可以使用 ubuntu 而不是 jenkins 用户在远程服务器上运行脚本?

编辑:

我知道我需要在 ssh 命令下运行它,而不是作为单独的 sh 脚本运行它,否则它将作为 jenkins 运行,我可以按照下面的脚本方式运行它。

这就是为什么我要问是否有更好的方法来以声明方式编写它。

node {
   stage('Deploy'){
     def dockerRun = "whoami && \
            sudo apt update  && sudo apt install -y docker.io && \
            sudo usermod -aG docker ubuntu && \
            source .bashrc && \
            docker run -d nginx "
            
     sshagent(['nginx-ec2']) {
       sh "ssh -o StrictHostKeyChecking=no ubuntu@<host_ip> '${dockerRun}' "
     }
   }
}

谢谢,

2 个答案:

答案 0 :(得分:1)

如前所述,您应该选择引用正确远程用户名的凭据,如 SSH Agent Jenkins plugin 中所示:

https://cdn.jsdelivr.net/gh/jenkinsci/ssh-agent-plugin@master/docs/images/Screen_Shot_2012-10-26_at_12.25.04.png

node {
  sshagent (credentials: ['deploy-dev']) {
    sh 'ssh -o StrictHostKeyChecking=no -l cloudbees 192.168.1.106 uname -a'
  }
}

另外,我只会执行一个脚本,其中包含您要远程执行的所有命令序列。

答案 1 :(得分:0)

嗯,到目前为止,这是最好的方法,尽管有重复!

pipeline {
  agent any

  stages {
      stage('Deploy') {
          steps {

             sshagent(['nginx-ec2']) {
                 // some block
                 sh "ssh -o StrictHostKeyChecking=no -l ubuntu <remote_ip> 'whoami'"
                 sh "ssh -o StrictHostKeyChecking=no -l ubuntu <remote_ip> 'sudo apt update  && sudo apt install -y docker.io'"
                 sh "ssh -o StrictHostKeyChecking=no -l ubuntu <remote_ip> 'sudo usermod -aG docker ubuntu'"
                 sh "ssh -o StrictHostKeyChecking=no -l ubuntu <remote_ip> 'source .bashrc'"
                 sh "ssh -o StrictHostKeyChecking=no -l ubuntu <remote_ip> 'docker run -d -nginx'"
             }
         }
      }
   }
}