实验架构: 192.168.0.96 gitlab 192.168.0.97 jenkins 192.168.0.98 harbor、docker集群 说明:下面代码编译镜像那一步的代码必须靠左,目的是不要有空格,否则报错,deploy那一步也必须是那种格式,否则报错 安装完jenkins后首先生成pipeline可以用的git链接地址 pipeline { agent any stages { stage('git checkout'){ steps { echo 'git clone' checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'c32a3a24-2c9d-4c8d-b456-9d6d0badf3a2', url: 'http://192.168.0.96:8081/zihao/test.git']]]) } } stage('maven build'){ steps { echo 'maven build' sh ''' export JAVA_HOME=/usr/local/jdk1.8.0_171/ /usr/local/apache-maven-3.5.4/bin/mvn clean package -Dmaven.test.skip=true ''' } } stage('docker build and push images'){ steps { echo 'docker build and push images' sh ''' REPOSITORY=192.168.0.98:5000/library/solo/solo:${Tag} cat >Dockerfile<<EOF FROM 192.168.0.98:5000/library/tomcat-85:latest RUN rm -rf /usr/local/tomcat/webapps/ROOT/ COPY target/*.war /usr/local/tomcat/webapps/ROOT.war WORKDIR /usr/local/tomcat EXPOSE 8080 CMD ["./bin/catalina.sh", "run"] EOF docker build -t $REPOSITORY . docker login -u admin -p Harbor12345 192.168.0.98:5000 docker push $REPOSITORY ''' } } stage('deploy'){ steps { echo 'deploy' sh ''' REPOSITORY=192.168.0.98:5000/library/solo/solo:${Tag} cat >deployment.yaml<<EOF apiVersion: extensions/v1beta1 kind: Deployment metadata: name: http-test-dm spec: replicas: 1 template: metadata: labels: name: http-test-dm spec: containers: - name: http-test-con image: $REPOSITORY imagePullPolicy: IfNotPresent ports: - containerPort: 80 EOF ''' } } } } 把上面的$REPOSITORY镜像替换成真实的镜像,执行完查看结果如下: [root@bogon ~]# ls /root/.jenkins/workspace/pipline-test/ CHANGE_LOGS.html deployment.yaml Dockerfile package.json PULL_REQUEST_TEMPLATE.md scripts 说明.htm CODE_OF_CONDUCT.md deploy.sh gulpfile.js package-lock.json README.md src CONTRIBUTING.md docker-compose.yml LICENSE pom.xml read.txt target [root@bogon ~]# cat /root/.jenkins/workspace/pipline-test/deployment.yaml apiVersion: extensions/v1beta1 kind: Deployment metadata: name: http-test-dm spec: replicas: 1 template: metadata: labels: name: http-test-dm spec: containers: - name: http-test-con image: 192.168.0.98:5000/library/solo/solo:1.0.2 imagePullPolicy: IfNotPresent ports: - containerPort: 80 说明:远程执行命令前提需要安装ssh agent插件, 现在ssh agent的认证,已不支持明文用户密码,而只能用加密方式实现。 所以先在jenknis和docker集群之间实现ssh免密码rsa证书登陆。 私钥放jenkins,公钥放在docker集群,然后,将私钥拿出来,写入到jenkins凭据 参照:https://blog.csdn.net/weixin_34067980/article/details/86444168 脚本参照: https://blog.csdn.net/jackyzhousales/article/details/81713004 https://blog.csdn.net/a1010256340/article/details/83989059 生成pipeline可以用的git链接地址参照: https://www.cnblogs.com/FRESHMANS/p/8184874.html