6

I try to get all badges of a certain GitLab project in .gitlab-ci.yaml and find out the id of a certain badge by name. I have the following script where I try to call the badges api with a curl and store the json result in a variable named BADGES:

build-backend:
  stage: build
  script:
    - BADGES='curl --header "PRIVATE-TOKEN:$GITLAB_API_TOKEN" "https://gitlab.example.com/api/v4/projects/${CI_PROJECT_ID}/badges"'
    - echo ${BADGES}

Of course now the echo ${BADGES} will output the curl because I stored it in the as string to the variable but I have no clue how to do this.

In JavaScript I would do this:

const badges = ...CURL_RESPONSE...;
const versionBadge = badges.find(b => b.name === 'vBadge');

Is this possible at all?

Michi-2142
  • 1,170
  • 3
  • 18
  • 39
  • Gitlab-ci uses whatever default shell defined in the image its using for the job. You can trivially replace the image putting whatever tools you want into it. What you've got right now is either `bash` or `ash` - you can read on their respective capabilities elsewhere. – oakad Aug 12 '21 at 15:30

1 Answers1

8

To capture the result of the call to curl you could use the $(…) construct:

BADGES="$(curl …)"

To select a specific badge ID in the response you could use jq.

Full example:

get_badge_id:
  image: alpine
  before_script:
    - apk add --no-cache curl jq
  script:
    - 'BADGE_ID="$(curl -s -H "PRIVATE-TOKEN: $GITLAB_API_TOKEN" $CI_API_V4_URL/projects/${CI_PROJECT_ID}/badges | jq ".[] | select(.name == \"vBadge\") | .id")"'
    - echo BADGE_ID is $BADGE_ID
slauth
  • 2,667
  • 1
  • 10
  • 18