首页 > 编程语言 >Jenkins2+python构建devops流水线demo分享

Jenkins2+python构建devops流水线demo分享

时间:2023-02-06 13:33:29浏览次数:43  
标签:Jenkins2 python demo send environment token env ip ###

#Jenkins2 demo
@Library('global-shared-library') _
pipeline {
agent { label 'master' }
options{
disableConcurrentBuilds()
// ansiColor('xterm')
}
parameters {
gitParameter branchFilter: 'origin/(.*)' , defaultValue: 'master' ,name: 'BRANCH', type: 'PT_BRANCH_TAG', listSize: '15', useRepository: 'http://IP+端口/xxx.git' //选择将要构建的分支
string(name:'WEICHAT_RECEIVERS',defaultValue: ' ',description: 'wx接收消息,多人接收xxx|xxxx')
extendedChoice description: '部署环境: ', multiSelectDelimiter: ',', name: 'environments', quoteValue: true, saveJSONParameterToFile: false, type: 'PT_CHECKBOX', value: 'ip,ip', visibleItemCount: 10
}
environment {
//部署包名称
testWarName='包名字' //备份脚本
//部署脚本 backup stop and start
apiDeployShellName='启动脚本'
//WEICHAT_RECEIVERS='联系人'
GIT_URL="http://IP+端口/xxx.git"
}
stages {
stage("获取发布环境"){
steps{
//定义环境:
script{
def tempName=params.environments
tempName=tempName.replaceAll("\"","")
echo "\033[7m environments:${tempName} \033[0m"
env.environment=tempName
echo "${env.environment}"
}
}
}
stage('选择分支并输出最后一次 commit 信息'){
steps {
script{
echo "${WORKSPACE}"
gitBranchCommitMsg_python(params.BRANCH,env.GIT_URL)
}
}
}
stage('编译'){
steps{

script{
if( "${env.environment}"=="ip" ){
echo "\033[7m 本部署服务器只进行包传递 \033[0m"
sh "zip -r ${testWarName} *"
sh "ansible ip -u 用户 -m copy -a '命令'"
}
if( "${env.environment}"=="ip" ){
sh "zip -r ${testWarName} *"
sh "ansible ip -u www -m copy -a '命令'"
sh "ansible ip -u www -m shell -a '命令'"
}
if( "${env.environment}"=="ip" ){
pwebRelease("${env.environment}")

}
if( "${env.environment}"=="ip" ){
pwebRelease("${env.environment}")
}
if( "${env.environment}"=="ip" ){
pwebRelease("${env.environment}")
}
if( "${env.environment}"=="ip" ){
pwebRelease("${env.environment}")

}
echo "\033[7m copy package complete \033[0m"
}
}

}
}
post {
success {
script{
wrap([$class: 'BuildUser']) {
echo "serviceNames:${params.serviceNames}"
// 执行python脚本,发送编译结果给企业wx
sh "cd 路径;python weixin.py \'${WEICHAT_RECEIVERS}\' 'jenkins:${JOB_NAME}:${BUILD_NUMBER} is success' '###build-user:${BUILD_USER} \n ###build-url:${BUILD_URL} \n ###serviceNames:${params.serviceNames} \n ###loadBalanceServer:${params.loadBalanceServer} ' "
}
}
}
failure {
script{
wrap([$class: 'BuildUser']) {
// 执行python脚本,发送编译结果给企业wx
if(env.deployEnv == 'rollback'){
message='failure,the deploy is rollback'
}else{
message='failure'
}
sh "cd 路径;python wx.py \'${WEICHAT_RECEIVERS}\' 'jenkins:${JOB_NAME}:${BUILD_NUMBER} is ${message}' '###build-user:${BUILD_USER} \n ###build-url:${BUILD_URL} \n ###serviceNames:${params.serviceNames} \n ###loadBalanceServer:${params.loadBalanceServer} ' "
}
}
}
aborted{
script{
wrap([$class: 'BuildUser']) {
// 执行python脚本,发送编译结果给企业wx
sh "cd 路径;python wx.py \'${WEICHAT_RECEIVERS}\' 'jenkins:${JOB_NAME}:${BUILD_NUMBER} is aborted ,please check the job' '###build-user:${BUILD_USER} \n ###build-url:${BUILD_URL} \n ###serviceNames:${params.serviceNames} \n ###loadBalanceServer:${params.loadBalanceServer} ' "
}
}
}
}
}
#企业wx py demo
#!/usr/bin/python
#_*_coding:utf-8 _*_


import urllib,urllib2
import json
import sys
import simplejson

reload(sys)
sys.setdefaultencoding('utf-8')


def gettoken(corpid,corpsecret):
gettoken_url = 'https://qyapi.wx.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
print gettoken_url
try:
token_file = urllib2.urlopen(gettoken_url)
except urllib2.HTTPError as e:
print e.code
print e.read().decode("utf8")
sys.exit()
token_data = token_file.read().decode('utf-8')
token_json = json.loads(token_data)
token_json.keys()
token = token_json['access_token']
return token

def senddata(access_token,user,subject,content):

send_url = 'https://qyapi.w.qq.com/cgi-bin/message/send?access_token=' + access_token
send_values = {
"touser":"用户, #企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
"toparty":"1", #企业号中的部门id。
"msgtype":"text", #消息类型。
"agentid":"xxx", #企业号中的应用id。
"text":{
"content":subject + '\n' + content
},
"safe":"0"
}
# send_data = json.dumps(send_values, ensure_ascii=False)
send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
send_request = urllib2.Request(send_url, send_data)
response = json.loads(urllib2.urlopen(send_request).read())
print str(response)


if __name__ == '__main__':
user = str(sys.argv[1]) #zabbix传过来的第一个参数
subject = str(sys.argv[2]) #zabbix传过来的第二个参数
content = str(sys.argv[3]) #zabbix传过来的第三个参数

corpid = 'xxx' #企业号的标识(上文中提到获取位置)
corpsecret = 'xxx' #管理组凭证密钥(上文中提到获取位置)
accesstoken = gettoken(corpid,corpsecret)
senddata(accesstoken,user,subject,content)

标签:Jenkins2,python,demo,send,environment,token,env,ip,###
From: https://blog.51cto.com/renzhiyuan/6038988

相关文章

  • AngularJS - 入门小Demo
    AngularJS四大特效MVC模式、模块化设计、自动化双向数据绑定、依赖注入如果了解了后端开发知识,想必对这些词汇不会陌生,AngularJS融合了后端开发的一些思想,虽然身为前端框架,......
  • 跟着廖雪峰学python004
    ​ ​编辑循环Python有两种循环:①for...in循环②while循环dict字典set集合for...in循环依次把list或tuple中的每个元素迭代出来names=['Michael'......
  • 一、python——变量和简单数据类型
    message="helloworld"print(message)message="Let'sgo"print(message)#title()以首字母大写显示每个单词name="zhouyuting"print(name.title())name......
  • 二、python——列表
    bicycles=["trek","cannondale","redline"]print(bicycles[0])print(bicycles[0].title())#索引为-1,返回最后一个元素print(bicycles[-1])print(bicycles[-1].......
  • 三、python——if语句
    cars=['audi','bmw','aubaru','toyota']forcarincars:ifcar=='bmw':print(car.upper())else:print(car.title())#andorage......
  • 四、python——字典
    alien_0={'color':'green','points':5}print(alien_0['color'])print(alien_0['points'])print(alien_0)alien_0['x_position']=0alien_0['y_position']=25......
  • 五、python——用户输入和while循环
    #函数input()让程序暂停运行,等待用户输入一些文本。#获取用户输入后,Python将其存储在一个变量中,以方便你使用message=input("Tellmesomething,andIwillrepea......
  • 六、python——函数
    pizza.pydefmake_pizzas(size,*toppings):"""概述要制作的比萨"""print('size:'+size)print(toppings)deftest_one():print('one')deft......
  • 七、python——类
    类名应采用驼峰命名法,即将类名中的每个单词的首字母都大写,而不使用下划线。实例名和模块名都采用小写格式,并在单词之间加上下划线。对于每个类,都应紧跟在类定义后面包含一......
  • python 的爬虫技巧是什么?
    以前写毕设是关于网络爬虫这一块的。大学期间做的项目都是关于Java应用程序开发这一块的,这次不想再写那些烂大街的管理系统了,不如试试别的。正逢导师给出参考题目,于是选了......