使用Python API触发GitLab流水线时私有令牌报400错误排查
GitLab流水线触发400错误(私有令牌)问题排查
我用Python写了个函数,通过tag和release变量触发GitLab流水线。用流水线触发令牌时运行正常,但换成私有令牌后,出现400错误:
Response Status Code: 400
Response Body: {"error":"variables is invalid"}
我的Python代码如下:
import requests import json # Function to trigger GitLab pipeline def trigger_gitlab_pipeline(project_id, tag, release, branch, private_token): url = f"https://gitlab.com/api/v4/projects/{project_id}/pipeline" headers = { 'PRIVATE-TOKEN': private_token, 'Content-Type': 'application/json' } # Data payload, ensuring release is a string data = { 'ref': branch, 'variables': { 'TAG_NAME': tag, 'RELEASE_NUM': release } } print("Request Data:", json.dumps(data, indent=4)) # Send the request response = requests.post(url, headers=headers, json=data) # Output the result print("Response Status Code:", response.status_code) print("Response Body:", response.text) # Example usage project_id = <project_id> tag = "AGT_v1.2.0-b25_and_AWB_v1.2.0-b08" release = 88 # This will be converted to string branch = "pipe_modi" private_token = <token> trigger_gitlab_pipeline(project_id, tag, release, branch, private_token)
请问我是不是漏了什么,或者调用方式错了?
问题原因
用私有令牌(个人访问令牌)调用GitLab流水线触发API时,variables参数的格式要求和流水线触发令牌不同:
- 流水线令牌接受键值对字典格式的
variables - 私有令牌调用必须使用数组格式,每个变量是包含
key和value的对象
另外原代码中未实际将release转为字符串,GitLab变量值仅支持字符串类型,这也是潜在问题。
修改后的代码
调整variables结构为数组格式,同时完成release的字符串转换:
import requests import json # Function to trigger GitLab pipeline def trigger_gitlab_pipeline(project_id, tag, release, branch, private_token): url = f"https://gitlab.com/api/v4/projects/{project_id}/pipeline" headers = { 'PRIVATE-TOKEN': private_token, 'Content-Type': 'application/json' } # 修正variables为数组格式,同时将release转为字符串 data = { 'ref': branch, 'variables': [ {'key': 'TAG_NAME', 'value': tag}, {'key': 'RELEASE_NUM', 'value': str(release)} ] } print("Request Data:", json.dumps(data, indent=4)) # Send the request response = requests.post(url, headers=headers, json=data) # Output the result print("Response Status Code:", response.status_code) print("Response Body:", response.text) # Example usage project_id = <project_id> tag = "AGT_v1.2.0-b25_and_AWB_v1.2.0-b08" release = 88 branch = "pipe_modi" private_token = <token> trigger_gitlab_pipeline(project_id, tag, release, branch, private_token)
修改后,请求参数将符合GitLab API对私有令牌调用的格式要求,可解决400错误。
内容的提问来源于stack exchange,提问作者sandesh b nataraj
相关产品推荐
相关产品推荐

