jenkins动态节点添加配置和使用方式为docker in docker

2023-05-16

jenkins动态节点添加配置和使用

  1. 安装docker模块
  2. 配置
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    mounts内容解释:
type=bind,source=/etc/jenkins/users.yaml,target=/etc/jenkins/users.yaml  #控制user权限
type=bind,source=/usr/bin/check.py,target=/usr/bin/check.py     #控制user权限脚本
type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock #docker in docker 
type=bind,source=/usr/bin/docker,target=/usr/bin/docker       #docker in docker 
type=bind,source=/usr/lib64/libltdl.so.7,target=/usr/lib/x86_64-linux-gnu/libltdl.so.7  #docker in docker 
type=bind,source=/data/jenkins_build_cache/.cache,target=/data/jenkins_build_cache/.cache  #容器node启动参数
type=bind,source=/data/lib/composer,target=/data/lib/composer         #容器node启动参数
type=bind,source=/home/jenkins/repo,target=/home/jenkins/repo         #dockerfile文件路径
type=bind,source=/root/.docker/config.json,target=/root/.docker/config.json #docker login 文件上传,下载
type=bind,source=/bin/kubectl,target=/bin/kubectl         #k8s操作命令
type=bind,source=/root/.kube/,target=/root/.kube/          #k8s config文件

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
pipline文件解释


#!/usr/bin/env groovy
import groovy.json.JsonOutput

String gitRepositryURL = 'https://gitlab.ssm/dtkgroup/dtk-chrome-plugin.git' #代码路径
String dockerRegistry = 'registry.bce.com'      #harbor仓库地址
String dockerRegistryURL = 'https://registry.bce.com'   #harbor url仓库地址
String dockerRegistryNameSpace = 'datae-test'          #harbor仓库名字

String kubeManifestsRepo = '/home/jenkins/repo/dtkst/app'  #dockerfile文件路径
Map dockerImages = [:]
boolean notify = false

String jobBaseName = env.JOB_NAME[4..-1]
String jobK8sName = jobBaseName.replaceAll('_', "-") 

Map commitInfo = [:]
Map buildInfo = [:]

commitInfo.projectName = gitRepositryURL.replaceFirst(/^.*\/([^\/]+?).git$/, '$1') 
commitInfo.gitRepositryURL = gitRepositryURL
buildInfo.buildId = currentBuild.id

@NonCPS
def newSh(String cmd) {
	def script = '#!/bin/sh +x\n' << cmd
	result = sh(returnStdout: true, script: script.toString())
	return result
}

pipeline {
		agent  
		{
	    node { 
	      label 'dockercloud'          #指定jnlp节点
	    } 
	    }


	options {                   #设置jenkins显示配置
		buildDiscarder logRotator(
			artifactDaysToKeepStr: '', 
			artifactNumToKeepStr: '', 
			daysToKeepStr: '10', 
			numToKeepStr: '10'
			)
	}

	parameters {         #参数设置
        choice( 
        	name: 'PENV',
        	choices: [
        		'dev1',
        		'dev2',
        		'test1',
        		'test2', 
        		'test3', 
        		'test4',
        		'test5',
                        'test6',
                        'test7',
        		'huise',
'huise4',
                        'huise3'
        	], 
        	description: '选择发布环境,默认发布至dev1测试环境'
        	)

        gitParameter(         #分支获取
        	name: 'GIT_BRANCH', 
            type: 'PT_BRANCH_TAG',
            branchFilter: 'origin/(.*)',
            defaultValue: 'master',
            selectedValue: 'DEFAULT',
            sortMode: 'DESCENDING_SMART',
            quickFilterEnabled: true, 
            description: 'Select your branch or tag.'
        	)
        booleanParam(name: 'force', defaultValue: false, description: '代码重复强制发版')
    }

	stages {

		stage('预处理') {
			steps {
				script {
					def now = new Date()
					buildInfo.buildDate = now.format("yy-MM-dd HH:mm", TimeZone.getTimeZone('UTC'))

					def causes = currentBuild.getBuildCauses()
					buildInfo.buildUser = causes[0]['userName']
					userList = readYaml(file:'/etc/jenkins/users.yaml')
					if (!(PENV in userList.env.dev ) && !(buildInfo.buildUser in userList.user.allow)) {
						error(message: "开发只能发布环境到${userList.env.dev.join(',')}")			
					}
					if (PENV in userList.env.huise ) {
						ACTIVE = 'prod'
					}
					buildInfo.gitBranch = GIT_BRANCH
					buildInfo.publishEnv = PENV
					currentBuild.description = "k8s环境: ${PENV} 构建人:${buildInfo.buildUser} 分支: ${GIT_BRANCH}"
				// 	newSh("check.py -u ${buildInfo.buildUser} -e ${PENV}")
				}
			}
		}

		stage('同步代码仓库') {
			steps {
				script {
					def scmVars = checkout([
								$class: 'GitSCM', 
								branches: [[name: "${GIT_BRANCH}"]], 
								extensions: [[$class: 'CheckoutOption', timeout: 20], [$class: 'CloneOption', depth: 1]], 
								userRemoteConfigs: [[credentialsId: "541146d-3606-485-ab9c-2e44cd2880", url: "${gitRepositryURL}"]]
								])
					commitInfo.gitCommit = scmVars.GIT_COMMIT
					commitInfo.gitBranch = GIT_BRANCH
					commitInfo.xiangmu_name = env.JOB_BASE_NAME
					commitInfo.commitDate = newSh('git log --pretty=format:"%ci" -1')
					commitInfo.cmmitMessage = newSh('git log --pretty=format:"%s" -1')

					String gitDiff = newSh('git diff HEAD^ HEAD')
					def committer = [:]
					committer.name = newSh('git log --pretty=format:"%cn" -1')
					committer.email =  newSh('git log --pretty=format:"%ce" -1')
					commitInfo.committer = committer
					
					String consoleStdout = "\n\n---------SYNCHRONIZE GIT REPOSITORY---------\nGit repo sync successfully.\n\n" + JsonOutput.prettyPrint(JsonOutput.toJson(commitInfo))
					println(consoleStdout)

					consoleStdout = "\n\n---------CHANGE LOGS---------\nGit diff:\n\n" + gitDiff
					println(consoleStdout)
					getDatabaseConnection(type: 'GLOBAL') {
						def sqlString="select commit_seccec from jenkins_commit.jenkins_jilu where xm_name = ? and env = ?"
                        def params=[commitInfo.xiangmu_name,PENV]
                        def rest_null = sql sql:sqlString,parameters:params
						if (rest_null.size() == 0){
						  def sqlString2="insert  into  jenkins_commit.jenkins_jilu(xm_name,env,commit_seccec)   values(?,?,?)"
                          def params2=[commitInfo.xiangmu_name,PENV,commitInfo.gitCommit]
						  sql sql:sqlString2,parameters:params2
						  println("mysql插入数据")
						}
						if (rest_null.size() >= 1) {
							   def Map rest = rest_null.get(0)
							    if (rest.get("commit_seccec") == commitInfo.gitCommit && force == "false"){
                        currentBuild.description = "k8s环境: ${PENV} 构建人:${buildInfo.buildUser} 分支: ${GIT_BRANCH} 构建失败: 代码重复不发版"
							   println("代码没有变化不做发版")
                               error "上一个版本和现在正在发的版本一致,不做发版"
							   }
							 //  if (rest.get("commit_seccec") == commitInfo.gitCommit){
							 //  println("代码没有变化不做发版")
        //                       error "上一个版本和现在正在发的版本一致,不做发版"
							 //  }
						}
				
					}
				}
			}
		}

		stage('构建') {		
			agent {
          		docker { 
              		image 'registrye.com/dt/node:14.19.3-alpine3.15'
                    args '--user root -v /data/jenkins_build_cache/.cache:${HOME}/.cache'
                    args '--user root -v /data/lib/composer:/root/.composer'
                    // reuseNode true
          		}	
      		}

        	steps {
            	script {
            		sh """
                    npm config set puppeteer_download_host=https://npm.taobao.org/mirrors
                    npm i --registry=https://registry.npm.taobao.org
                    npm run build:${ACTIVE}
                    """
					stash name: 'build-output', includes: '**'        #打包后的文件传给下一级使用
					
            // 		consoleStdout = "\n\n---------BUILD RESULTS---------\nBuild info generated successfully.\n\n" + JsonOutput.prettyPrint(JsonOutput.toJson(buildInfo))
            // 		println(consoleStdout)
        		}	
			}
		}
		

		stage('Docker') {
			steps {
				script {
				    unstash 'build-output'   #使用上级文件路径
				//	docker.withRegistry(dockerRegistryURL, '8f1a40fa-8-4717-f87299916d') {
					docker.withRegistry(dockerRegistryURL) {
						
						String dockerFile = kubeManifestsRepo + '/' + jobBaseName + '/' + 'Dockerfile.test'
						    
						if (!fileExists(dockerFile)) {
							dockerFile = kubeManifestsRepo + '/' + jobK8sName + '/' + 'Dockerfile.test'
						}

						String dockerRepository = dockerRegistry + '/' + dockerRegistryNameSpace + '/' + jobK8sName
						def customImage = docker.build(dockerRepository, "-f ${dockerFile} .")
							customImage.push(commitInfo.gitCommit)
							customImage.push('latest')

						dockerImages.nginx = dockerRepository + ':' + commitInfo.gitCommit

					}
				}
			}
		}

		stage('部署') {
			steps {
				script {
					dockerImages.each { k, v -> 
						newSh("kubectl -n ${PENV} set image deployment/${jobK8sName} ${k}=${v}")
						newSh("kubectl -n ${PENV} rollout status deployment/${jobK8sName} --timeout=2m")
					}
					String content = "![screenshot](https://comquent.de/wp-content/uploads/CQ-Pipeline-Kurs.png)\n\n### Jenkins Pipeline\n>**构建信息**:\n>- 构建项目: ${jobBaseName}\n>- 构建id: ${currentBuild.number}\n>- 构建人: ${buildInfo.buildUser}\n>- 构建分支: ${GIT_BRANCH}\n>- 发布环境: ${PENV}\n>**版本信息**:\n>- commit_hash: ${commitInfo.gitCommit}\n>- commit_date: ${commitInfo.commitDate}\n>- commit_message: ${commitInfo.cmmitMessage}\n>- committer: ${commitInfo.committer.name}"	
					def workflowMessage = [
						"msgtype": "actionCard",
						"actionCard":[
							"title":"构建信息",
							"text":content,
							"btnOrientation": "0",
							"btns": [
								[
									"title": "详细信息",
									"actionURL": "https://k8sje.qu.com/blue/organizations/jenkins/pp_api/detail/k8s_o_app_api/${currentBuild.number}/pipeline"
								],
								[
									"title": "日志监控",
									"actionURL": "http://k8skna.ojequ.com/app/kibana#/discover?_g=()&_a=(columns:!(_source),index:'18d519283c86fa1d0',interval:auto,query:(language:kuery,query:''),sort:!(!('@timestamp',desc)))"
								],
							]
						]
					]	

					String workflowMessageJSON = JsonOutput.toJson(workflowMessage)
					timeout(unit: 'SECONDS', time: 30) {
						newSh("curl 'https://oapi.dingtalk.com/robot/send?access_token=9e88df7a79749c' -s -H 'Content-Type: application/json' -d '${workflowMessageJSON}'")
					}
				}
			}
		}
		stage("commit入库"){
             steps {
                  script{
                        getDatabaseConnection(type: 'GLOBAL') {
				        def sqlString3="update jenkins_commit.jenkins_jilu set commit_seccec=?    where xm_name=? and env=?;"
                        def params3=[commitInfo.gitCommit,commitInfo.xiangmu_name,PENV]
                        sql sql:sqlString3,parameters:params3
				  }
				  }
			 }
		}
	}
}



在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jenkins动态节点添加配置和使用方式为docker in docker 的相关文章

  • secure CRT + Xmanager 实现图形化界面的查看

    1 准备 安装xmanager 可以去网上找 有很多破解版Linux主机关闭selinux和防火墙 2 Linux主机安装必要的软件包 root 64 localhost yum install y xorg x11 server util
  • STM32【H7】理论——综述、HAL库简述

    文章目录 1 STM32H7芯片简介1 1 STM32H7与STM32F1 F4系列芯片的区别1 2 硬件框图1 3 STM32H7各型号对比1 4 总线框图和时钟1 5 AXI总线1 5 1 AXI总线简介1 5 2 AXI总线优先级编程
  • STM32理论 —— FreeRTOS(内核控制、时钟、队列)

    文章目录 1 系统内核控制1 1 相关API函数1 1 1 函数 96 taskYIELD 96 1 1 2 函数 96 taskENTER CRITICAL 96 1 1 3 函数 96 taskEXIT CRITICAL 96 1 1
  • vscode基本插件安装与配置

    插件安装 xff1a Auto Rename Tag 重命名标签时 xff0c 自动更新结尾配对的标签 Chinese 汉化 ESLint 规范化代码 xff0c 对应的setting配置 xff08 全局所有项目都有效 xff09 xff
  • Ubuntu20.04(Noetic)版本中关于“使用rospack命令工具来查看这些一级依赖包“报错解决方法

    ROS Noetic版本中关于 使用rospack命令工具来查看这些一级依赖包 报错解决方法 问题描述 xff1a 在跟随ROS初级教程 创建ROS软件包这一步骤 xff0c 可能会遇见下面问题 xff1a smw 64 smw Lenov
  • 最详细的Ubuntu18配置px4_ros_gazebo仿真

    本教程将在Ubuntu18安装ros px4工具链 以及gazebo仿真环境 参考此教程可以在Ubuntu16的环境安装ros px4工具链 以及gazebo仿真环境 首先 xff0c 我们来看下Ubuntu各版本对应的gazebo关系 x
  • 百度获取toke

    https aip baidubce com oauth 2 0 token grant type 61 client credentials amp client id 61 官网获取的AK amp client secret 61 官网
  • 详细的EVE-NG部署方法+EVE各种镜像与模板,附带SCRT+WINSCP等工具提供(VM部署)

    自己写的一份较详细的EVE NG在虚拟机VM上部署的教程 xff0c 喜欢的可以关注一下 xff0c 谢谢 首先我在百度云附上了EVE NG社区版2 0 3 110版本的OVF文件 xff0c 此次用这个版本来演示 xff0c 并且还提供了
  • node.js环境一键部署

    61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
  • Golang Interface小结

    1 概述 1 1 简介 接口是一种规范 xff0c 描述了类的行为和功能 xff0c 而不做具体实现 C 43 43 定义接口的方式称为 侵入式 xff0c 而Go采用的是 非侵入式 xff0c 不需要显式声明 xff0c 只需要实现了接口
  • UART 简介

    1 引脚 UART 是一种异步全双工通信方式 xff0c 所以除了电源引脚之外 xff0c UART 常有引脚有 TXD xff0c RXD xff1b 除此之外还有硬件流控引脚 RTS 和 CTS TXD 是发送引脚 xff0c RXD
  • 无人机飞控三大算法:捷联式惯性导航系统、卡尔曼滤波算法、飞行控制PID算法

    无人机飞控三大算法 xff1a 捷联式惯性导航系统 卡尔曼滤波算法 飞行控制PID算法 一 捷联式惯性导航系统 说到导航 xff0c 不得不说GPS xff0c 他是接受卫星发送的信号计算出自身位置的 xff0c 但是当GPS设备上方被遮挡
  • [学习笔记-01]关于单片机的中断处理机制(一)

    单片机的中断处理机制 1 什么是中断 xff1f 1 1 为什么要使用中断 中断的特点 1 2 什么是中断源 xff1f 1 2 1中断源有哪些 2 中断机制的流程3 中断优先级3 1 多个中断同时发生3 2 中断嵌套 1 什么是中断 xf
  • 黑苹果突然某一天无法上网?可能设置了BIOS,这样可以有网了!

    如图所示 xff0c 本人是微星迫击炮B450 xff08 非MAX xff09 xff0c 进入BIOS设置网卡 xff0c 可以解决这样的没网的问题 如果各位的BIOS不是微星 xff0c 也没有关系 xff0c 可以找到类似的功能就可
  • LSTM模型、双向LSTM模型以及模型输入输出的理解

    循环神经网路 xff08 RNN xff09 在工作时一个重要的优点在于 xff0c 其能够在输入和输出序列之间的映射过程中利用上下文相关信息 然而不幸的是 xff0c 标准的循环神经网络 xff08 RNN xff09 能够存取的上下文信
  • 无人机中的PID控制代码略解

    无人机中的PID控制代码略解 PID的控制规律 xff1a 参考 xff1a Amov实验室 PX4中级课程 PID基础 频域函数 xff1a u s
  • 如何用Python在图片上绘制BoundingBox

    参考资料 xff1a https blog csdn net weixin 41735859 article details 106599903 在目标检测等CV领域的任务里 xff0c 经常会涉及到在图片上绘制BBox xff0c 也就是
  • uart

    1 关于UART的基本特性 xff1a xff08 1 xff09 异步串行通信 xff0c 可为全双工 半双工 单发送TX或单接收RX模式 xff1b xff08 2 xff09 支持5 xff5e 8位数据位的配置 xff0c 波特率几
  • STM32--数码管显示使用

    STM32 数码管显示 简介 1 硬件部分 STM32F103C8T6 最小系统板 一位共阴数码管 2 软件部分 Keil软件编程 数码管码表 硬件部分 数码管 简介 数码管 xff0c 也称作辉光管 xff0c 是一种可以显示数字和其他信
  • LXC 和 LXD 容器总结

    1 概述 1 1 LXC LXC是Linux Containers的缩写 它是一种虚拟化技术 xff0c 通过一个Linux内核在一个受控主机上虚拟地运行多个Linux系统 LXC使用内核的Cgroups功能 xff0c 来提供进程和网络空

随机推荐