简体   繁体   中英

Trigger GitLab Build with Python Requests

I'm trying to trigger a GitLab build using Python Requests. Normally one can kick off a build with a curl command.

Example curl command:

curl -X POST \
  -F token=TOKEN \
  -F ref=master \
  -F "variables[UPLOAD_TO_S3]=true" \
  https://gitlab.example.com/api/v4/projects/9/trigger/pipeline

I can get this working using the sh module but I'd prefer using requests . I've tried variations with the following:

data = {
    'token': token,
    'ref': master,
    'variables[UPLOAD_TO_S3]': str(uploadS3),
}

headers = {'Content-Type': 'application/json'}
result = requests.post(_trigger_url, headers=headers, json=data)

I tried with and without the headers param. I've also tried passing the data dict using params , json , files , and data . All keep coming back with 400 or 404 errors. Any suggestions?

The above answer is incomplete as it does not deal with the part that makes this complex that is passing trough variables.

To pass variables around with requests using json data one needs to pass the data in the following structure

data = {
    'token': token,
    'ref': master,
    'variables': [{"key": "UPLOAD_TO_S3", "value": True}, {"key": "S3_SERVER", "value": "https://mys3.example.com"}],
}

result = requests.post(_trigger_url, json=data)

You shouldn't send the Content-Type: "application/json" header as part of your request, and you should only need form encoding, so just pass your data dict as the data argument.

Here's a request to my Gitlab instance that succeeds and triggers a build of my project's master branch.

rsp = requests.post('https://gitlab.instance/api/v4/projects/PROJECT_ID/trigger/pipeline',
          data={'token': '125fdsfdf1ab3631d2423434347643', 'ref': 'master'})

Here's the output if I inspect my rsp object in `ipython:

In [3]: rsp
Out[3]: <Response [201]>

You should also be able to trigger the pipeline by sending a POST and including the token and ref in the URL itself.

rsp = requests.post('https://gitlab.instance/api/v4/projects/PROJECT_ID/trigger/pipeline?token=TOKEN&ref=master')

If I pass the Content-Type: "application/json" header, Gitlab responds with an HTTP/400 error.

The first answer doesn't address the "variables" part. The second answer didn't work for me. Here's what I ended up with working:

variables = {
    "UPLOAD_TO_S3": True,
    "S3_SERVER": "https://mys3.example.com"
}

data = {
    "token": token,
    "ref": ref_name,
    "variables": variables
}

res = requests.post(pipeline_trigger, json=data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM