主旨
實踐 Jenkins 流水線使用SSH方式操作 Git 倉庫,包含基於 SSH 私鑰認證的服務器
准備
需要提前安裝 SSH Agent Plugin,可以通過 Manage Jenkins-> Manage Plugins-> Installed 使用 filter 搜索查看是否安裝,如沒有則通過 Available處搜索安裝
使用
本地生成ssh key或使用已有
生成ssh key,默認會生成在用戶目錄下 .ssh 中
ssh-keygen -o

其中,id_rsa是私鑰,id_rsa.pub是公鑰,known_hosts是訪問過的服務器公鑰
GitLab設置訪問SSH key
一圖勝多言

Jenkins設置憑據
在Jenkins主頁面依次點擊 憑據-> 系統-> 全局憑據

點擊 Add Credentials 添加密鑰

- Kind選
SSH Username with private key - ID 為后續在流水線腳本中引用的值,舉例是 hellxz-ssh-key
- Private Key點擊
Enter directly->Add,在出現的輸入框中粘貼你的私鑰id_rsa中的值 - 最后點 OK,添加密鑰
流水線腳本中使用密鑰
pipeline {
agent any
stages{
stage('clone private repo') {
steps{
sshagent (credentials: ["hellxz-test-ssh"]) {
sh 'git clone ssh://xxxxx/config.git' //這里以一個私服倉庫config舉例,就不貼地址了
}
}
}
}
}
測試結果

