Jenkins remotely triggers the gitlab pipeline through a python script

The python library used

python-gitlab

1. Install the gitlab library

pip install python-gitlab

insert image description here
2. Write python script

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. Go to Jenkins to create a project ( you need to configure the python environment on the Jenkins server and install relevant third-party libraries )
insert image description here
4. View the running effect
insert image description here
5. This test is to publish the image to the Alibaba Cloud ACK container cluster through gitlab's cicd, which can be combined with The kubernetes interface obtains the startup status of the pod after the image is updated to ensure that the automatic interface test can be performed through apifox after the pod is fully started, thereby realizing automatic release and testing.

Guess you like

Origin blog.csdn.net/Habo_/article/details/128019559