pythongitlabgitlab-cigitlab-api

how to trigger and pass parameters to a job in a gitlab ci/cd via gitlab api?


can i pass parameters to a job via REST api call to a gitlab api, to trigger a specific job? I have a python script that runs as a part of the job and i would like to pass parameters to that script. I would like to invoke that job via gitlab api. how would the request look like?

for example, based on the documentation , a curl command to trigger the pipeline looks like this

curl --request POST \ 
  "https://gitlab.example.com/api/v4/projects/project_id/trigger/pipeline?token=**************&ref=main"

Question : so in my example below, i have a test-job1, which runs a python script, called mydumbscript.py and i pass in few parameters , $arg1 ... . can i pass this parameter via gitlab api and trigger this particular job?

I have set up a project in gitlab , say myproject and here is a sample .gitlab-ci.yml file

build-job:
  stage: build
  script:
    - echo "Hello, $GITLAB_USER_LOGIN!"

test-job1:
  stage: test
  script:
    - python3 myproject/script/mydumbscript.py $arg1 $arg2 $arg3

test-job2:
  stage: test
  script:
    - echo "This job tests something, but takes more time than test-job1."
    - echo "After the echo commands complete, it runs the sleep command for 20 seconds"
    - echo "which simulates a test that runs 20 seconds longer than test-job1"
    - sleep 20

deploy-prod:
  stage: deploy
  script:
    - echo "This job deploys something from the $CI_COMMIT_BRANCH branch."
  environment: production

Solution

  • From the gitlab documentation:

    You can pass any number of CI/CD variables in the trigger API call. These variables have the highest precedence, and override all variables with the same name. The parameter is of the form variables[key]=value, for example:

    curl --request POST \
         --form token=TOKEN \
         --form ref=main \
         --form variables[UPLOAD_TO_S3]="true" \
         "https://gitlab.example.com/api/v4/projects/123456/trigger/pipeline"
    

    CI/CD variables in triggered pipelines display on each job’s page, but only users with the Owner and Maintainer role can view the values.

    The key in example is the variable you will have defined in your pipeline when it starts running. you can add multiple lines like the --form variables line.

    fyi, this information and more can be found here: https://docs.gitlab.com/ee/ci/triggers/#pass-cicd-variables-in-the-api-call