jenkins安装完成后,需要在jenkins安装插件
Publish Over SSH
SSH Agent Plugin
SSH Pipeline Steps
安装完成后,重新启动Jenkins
在被远程的服务器上执行命令
ssh-keygen -t rsa -b 4096
会生成2个文件 在目录 /root/.ssh
id_rsa id_rsa.pub
然后再执行命令
cat id_rsa.pub >> authorized_keys
当前目录下会多一个命令 authorized_keys文件
然后在Jenkins创建凭证
ID 不填会自动生成
username 就是服务器登录名
这里把id_rsa内容填在这个地方 保存即可
流水线远程测试代码
pipeline {
agent any
environment {
SSH_CREDENTIALS_ID = 'd06eb529-1326-6cfa-82eb-dc78e532f1b2'
SSH_REMOTE_PORT = 22
SSH_REMOTE_HOST = '192.168.0.100'
}
stages {
stage('部署') {
steps {
echo '部署中...'
script {
sh '''
cat > test.yaml << EOF
999999
EOF
'''
// 把「CODING 凭据管理」中的「凭据 ID」填入 credentialsId,而 id_rsa 无需修改
withCredentials([sshUserPrivateKey(
credentialsId: "${SSH_CREDENTIALS_ID}",
keyFileVariable: 'identity',
passphraseVariable: '',
usernameVariable: 'userName')]) {
// 声明服务器信息
def remote = [:]
remote.name = 'web-server'
remote.allowAnyHosts = true
remote.port = SSH_REMOTE_PORT.toInteger()
remote.host = "${SSH_REMOTE_HOST}"
remote.user = userName
remote.identityFile = identity
// SSH 上传文件到远端服务器
sshPut remote: remote, from: 'test.yaml', into: '/tmp/'
// 解压缩
sshCommand remote: remote, command: "ifconfig"
sshCommand remote: remote, sudo: true, command: "mkdir -p /opt/jenkins_abc"
}
}
echo '部署完成'
}
}
}
}
该示例执行完后,会生成 目录在 /tmp/test.yaml