Search code examples
gitlabcontinuous-integrationgitlab-ci

how to provide custom variables in gitlab api?


based on the gitlab docs, one can trigger a job in the ci/cd pipeline and pass some parameters in the POST request as well. sample below. how to correctly read/parse the variables.json in gitlab ci/cd job ? say, i want to trigger test-job1 in my pipeline via following curl command, how to read the parameters passed in @variables.json in .gitlab-ci?

curl --request POST "https://gitlab.example.com/api/v4/projects/project_id/trigger/pipeline" \
     --header "Content-Type: application/json" \
     --header "PRIVATE-TOKEN: <your_access_token>" \
     --data @variables.json

.gitlab-ci.yml

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

test-job1:
  stage: test
  script:
    - python3 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

  • Given a sample variables.json file like this:

    {
      "job_variables_attributes": [
        {
          "key": "MY_VAR_1",
          "value": "foo"
        },
        {
          "key": "MY_VAR_2",
          "value": "bar"
        }
      ]
    }
    

    Then on the job that's going to be executed then you can do something like the following:

    test-job1:
      stage: test
      script:
        - python3 mydumbscript.py $MY_VAR_1 $MY_VAR_2
    

    The --data @variables.json is essentially exporting the defined variables in your JSON to be available within the job, so you can use them the same way you'd if those were defined at the variables keyword.