Jenkins通过python脚本实现远程触发gitlab流水线

用到的python库

python-gitlab

1.安装gitlab库

pip install python-gitlab

Jenkins通过python脚本实现远程触发gitlab流水线_第1张图片
2.编写python脚本

import gitlab
def process_pipeline(process_pipeline):
    if isinstance(process_pipeline,dict):
        git_url,git_access_token,project_id,git_ref,git_job_trigger = process_pipeline.values()
    else:
        raise Exception("传入的参数必须为字典")
    gl = gitlab.Gitlab(git_url,private_token=git_access_token)
    project = gl.projects.get(project_id)
    pipeline = project.trigger_pipeline(git_ref,git_job_trigger)
    pipeline_status = ""
    pipeline_ref = ""
    print("*" * 200)
    while pipeline.finished_at is None:
        pipeline.refresh()
        pipeline_status = pipeline.status
        pipeline_ref = pipeline.ref
    print("result:%s" %(pipeline))
    print("*" * 200)
    if pipeline_status == "success":
        print("当前gitlab pipeline状态为:%s,当前运行的分支为:%s" %(pipeline_status,pipeline_ref))
    elif pipeline_status == "failed":
        print("gitlab pipeline运行失败请检查,当前状态为:%s,当前运行的分支为:%s" %(pipeline_status,pipeline_ref))
    elif pipeline_status == "canceled":
        print("用户取消执行,当前状态为:%s,当前运行的分支为:%s" %(pipeline_status,pipeline_ref))
    else:
        print("非常见状态请检查,当前状态为 %s,当前运行的分支为:%s" %(pipeline_status,pipeline_ref))
process_pipeline(
    {
        'git_url': "https://gitlab.example.com",
        'git_access_token': "xxxx-xxxxxxxxxxx",
        'project_id': xxxxx,
        'git_ref': "test",
        'git_job_trigger': "xxxxxxxxxxx"
    }
)    

3.去到Jenkins中创建项目(需要在Jenkins服务器配置python环境及安装相关第三方库)
Jenkins通过python脚本实现远程触发gitlab流水线_第2张图片
4.查看运行效果
Jenkins通过python脚本实现远程触发gitlab流水线_第3张图片
5.本次试验是通过gitlab的cicd将镜像发布至阿里云ACK容器集群,可结合kubernetes接口获取pod更新镜像后的启动状态,确保pod完全启动后可通过apifox执行自动接口测试,从而实现 自动化发布及测试。

你可能感兴趣的:(CI/CD,jenkins,python,gitlab)