Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GitLab CI get predefined variable with API?

I am using predefined variables like $CI_COMMIT_REF_SLUG in my gitlab ci pipeline and it would be very useful to access those variables via the gitlab api.

I have read through the documentation and went through all gitlab-ci related GET routes (branches/, jobs/, pipelines/) but could only find the original branch names/tags for each job and pipeline.

Is there any to access this variable?

edit: Use-case would be I'd like to query the urls after a successful pipeline. During the pipeline a url like this is generated example.com/$_CI_COMMIT_REF_SLUG/.

I need a response like this coming from the API:

{
    "ref_slug":"foo-12",
    "ref":"-/foo_12-"
}
like image 879
Theo Avatar asked Sep 16 '25 10:09

Theo


2 Answers

I don't think that such API exists.

However you can use in parallel your own local variable calculated based on their function: https://gitlab.com/gitlab-org/gitlab-runner/-/blob/main/Makefile.build.mk#L25

BRANCH=$(git branch --show-current)
CI_COMMIT_REF_SLUG=$(echo $BRANCH | cut -c -63 | sed -E 's/[^a-z0-9-]+/-/g' | sed -E 's/^-*([a-z0-9-]+[a-z0-9])-*$$/\1/g')

I don't think that their implementation will change anytime soon(because of backward compatibility implications) to require sync on your side. If you don't want to be exposed to side effects caused by changes in their implementation you can use your calculated value everywhere.

like image 91
tiberiuemilian Avatar answered Sep 19 '25 07:09

tiberiuemilian


I have similiar requirement and googling brought me here. Unfortuately the accepted answer said no. Then I found something useful in gitlab ci document and I think this is what I want.

GET /projects/:id/pipelines/:pipeline_id/variables

[
  {
    "key": "RUN_NIGHTLY_BUILD",
    "variable_type": "env_var",
    "value": "true"
  },
  {
    "key": "foo",
    "value": "bar"
  }
]

Update

/projects/:id/variables gets the predefined variables in ci/ci variable settings, while /projects/:id/pipelines/:pipeline_id/variables gets the variables you manually input when triggering the pipeline.

like image 43
Lei Yang Avatar answered Sep 19 '25 08:09

Lei Yang