1.准备工作
目标: 开发人员提交代码后触发GitlabCI ,如果有merge请求则触发Jenkins对源分支在开发环境构建测试。
2.GItlab配置
开启仅允许pipeline成功后才能merge选项
项目注册runner
项目添加.gitlab-ci.yaml文件
tags: gitlab-runner 的标签
scripts: 调用runner运行的脚本 这里讲脚本做了软连接为gitlabci 后面两个参数分别是 gitlab项目的id jenkins项目名称
3.Python脚本
这个脚本需要软连接到/usr/bin/gitlabci,主要采用gitlab库和jenkins完成。
# _*_ coding: utf-8 _*_ import gitlab import jenkins import time import sys import datetime import os #获取分支 def GetBranch(projectId): startTime = datetime.datetime.now().minute while True: project = gl.projects.get(projectId) lastMerge = project.mergerequests.list()[0] nowTime = datetime.datetime.now().minute useTime = nowTime - startTime #print(useTime) timeout = 5 if useTime > timeout : #raise Exception("获取分支超时!") os.system("echo ‘获取分支超时!‘") #print("获取分支超时!") return ‘‘ time.sleep(5) mergeStatus = lastMerge.changes()[‘state‘].encode(‘utf-8‘) if mergeStatus == ‘opened‘: sourceBranch = lastMerge.changes()[‘source_branch‘].encode(‘utf-8‘) print("SourceBranch -->>>" + sourceBranch) os.system("echo ") return sourceBranch else: #raise Exception("No merge request is opened!") os.system("echo ‘No merge request is opened!‘") #print(‘No merge request is opened!‘) #触发构建 def JenkinsBuild(projectName,branchName): nextBuildNumber = server.get_job_info(projectName)[‘nextBuildNumber‘] server.build_job(projectName,{‘gitlabCI‘ : branchName}) os.system("echo ‘触发成功!‘") print("触发成功! " + "BuildNumber is " + "-->" + str(nextBuildNumber)) time.sleep(10) startTime = datetime.datetime.now().minute while True: nowTime = datetime.datetime.now().minute useTime = nowTime - startTime if useTime > timeout : raise Exception("构建超时!") #print("构建超时!") #exit() buildInfo = server.get_build_info(projectName, nextBuildNumber) if buildInfo[‘building‘] == True: print(projectName + "--> Building") time.sleep(30) elif buildInfo[‘building‘] == False: result = buildInfo[‘result‘].encode(‘utf-8‘) if result == ‘SUCCESS‘: os.system("echo ‘构建成功!‘") print("构建成功!-->" + result) return True else: raise Exception("触发成功 构建失败!--> 请检查项目参数") #print("触发成功 构建失败!--> 请检查项目参数") #return False if __name__ == ‘__main__‘: gitUrl=‘xxxxx‘ gitToken=‘xxxxx‘ jenkinsUrl=‘http://0.0.0.0:8080‘ jenkinsUser=‘xxxxxx‘ jenkinsToken=‘xxxxxxxx‘ timeout=5 projectId=sys.argv[1] projectName=sys.argv[2] #run gl = gitlab.Gitlab(gitUrl,gitToken) branchName = GetBranch(projectId) #branchName = ‘v1.11.0_release‘ if branchName != ‘‘: server = jenkins.Jenkins(jenkinsUrl,jenkinsUser,jenkinsToken) JenkinsBuild(projectName,branchName)
效果
原文地址:https://www.cnblogs.com/mascot1/p/9963984.html
时间: 2024-11-05 17:28:01