Jenkinsfile Pipeline 使用 SSH 连接

Jenkinsfile Pipeline 使用 SSH 连接

为了在 Jenkinsfile 的命令中使用 SSH,我们不得不通过一些设置…

前提

首先你需要将用到的 SSH 私钥保存到 Jenkins 的凭据中,这样你会获得一个 credentialId。这不是本文主要的内容,故不在此展开赘述,详情可参考官方文档:https://www.jenkins.io/doc/book/using/using-credentials/

只用一个 SSH Key

假若我们的 Jenkinsfile 里只用到了一个 SSH key,那么直接使用 Jenkins 的 SSH Agent 这个插件就好,在 Jenkinsfile 中具体写法为:

pipeline {
    agent any

    stages {
        stage('doing') {
            steps {
                // 启动 ssh-agent 并将你的的 SSH 私钥凭据添加到其中
                sshagent(credentials: ["你在Jenkins中保存SSH密钥后获得的凭据ID"]) {
                    // 在这里就可以正常进行需要 SSH 连接才能做的操作了...

                }
            }
        }
    }
}

多个 SSH Key

pipeline {
  agent any

  stages {
    stage('doing') {
      steps {
        // credentialsId 值为Jenkins凭据管理中的相应凭据
        withCredentials([
            // credentialsId1 和 credentialsId2 是在Jenkins中保存SSH密钥后获得的凭据ID
            // ssh_key_file_1 和 ssh_key_file_2 是自己取的变量名,在函数内部,Jenkins会把相应凭据ID对应的SSH密钥文件存到这个变量名中
            sshUserPrivateKey(credentialsId: "credentialsId1", keyFileVariable: "ssh_key_file_1"),
            sshUserPrivateKey(credentialsId: "credentialsId2", keyFileVariable: "ssh_key_file_2")
        ]) {
          // 读取的凭据将以环境变量的形式获取
          // 变量 ssh_key_file_1 和 ssh_key_file_2 分别为各自的凭据ID对应的ssh私钥文件
          // 然后就可以使用这两个SSH私钥文件来进行操作了...

        }

      // ...

      }
    }
  }
}

参考

Jenkinsfile Pipeline 使用 SSH 连接

文完撒花🎉!感谢观看👏!

Original: https://www.cnblogs.com/astrofeyx/p/jenkins-ssh-key-dockerfile.html
Author: 徐风吟
Title: Jenkinsfile Pipeline 使用 SSH 连接

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/684254/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球