一、系统环境

组件版本
Ubuntu20.04
Jenkins2.319.1
Bitbucket
Jenkins插件作用
ssh-steps-pluginSSH远程

二、相关资料

官方文档-Jenkins用户手册

三、添加凭证

在Jenkins中添加要远程服务器的用户名和密码,如:ID命名为"192.168.12.12"
在这里插入图片描述
在这里插入图片描述

四、简单示例

pipeline {
    //代理,通常是一个机器或容器
    agent any
     
    //环境变量,类似全局变量
    environment {
        //构建执行者
        BUILD_USER = ""
    }
     
    //构建触发器,Jenkins自动构建条件
    triggers{
        //每3分钟判断一次代码是否有变化
        pollSCM('H/3 * * * *')
    }
 
    stages {
        //构建阶段
        stage('Build') {
            //使用build user vars插件,获取构建执行者
            steps {
                wrap([$class: 'BuildUser']) {
                    script {
                        //将构建执行者注入到环境变量中,方便最后通知使用
                        BUILD_USER = "${env.BUILD_USER}"
                    }
                }
                /* 从Bitbucket上拉取分支
                * @url git地址
                * @branch 分支名称
                * @credentialsId Jenkins凭证Id,用于远程访问
                */
                git(url: 'https://demo@bitbucket.org/demo/demo.git', branch: 'master', credentialsId: 'Bitbucket')
                //执行maven打包
                //-B --batch-mode 在非交互(批处理)模式下运行(该模式下,当Mven需要输入时,它不会停下来接受用户的输入,而是使用合理的默认值);
                //打包时跳过JUnit测试用例,
                //-DskipTests 不执行测试用例,但编译测试用例类生成相应的class文件至target/test-classes下
                //-Dmaven.test.skip=true,不执行测试用例,也不编译测试用例类
                sh 'npm install && npm run build'
            }
        }
         
        //部署阶段
        stage('Deliver') {
            steps {
                //执行脚本
                    sh '''
                        cd /var/lib/jenkins/workspace/demo/
                        tar -cvf dist.tar.gz ./dist
                        '''
            }
        }
        stage('SSH') {
            steps {
                script {                 
  	                def remote = [:]
  	                remote.name = 'test'
  	                remote.host = '192.168.12.12'
                    remote.allowAnyHosts = true
                    withCredentials([usernamePassword(credentialsId: '192.168.12.12', passwordVariable: 'password', usernameVariable: 'username')]) {
                        remote.user = "${username}"
                        remote.password = "${password}"
                    }
                    sshCommand remote: remote, command: "pwd"
                    sshRemove remote: remote, path: '/usr/share/nginx/html/demo/dist'
                    sshPut remote: remote, from: '/var/lib/jenkins/workspace/demo/dist.tar.gz', into: '/usr/share/nginx/html/test-monitor/'
                    sshCommand remote: remote, command: "cd /usr/share/nginx/html/demo/ && tar -xvf ./dist.tar.gz"
                }
            }
        }
    }
}

五、参考鸣谢

jenkins pipelines 使用ssh 例子
Jenkins Pipeline SSH 鉴权

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐