Michi-2142
Michi-2142

Reputation: 1312

Use CURL response in GitLab CI Script

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?

Upvotes: 8

Views: 11199

Answers (1)

slauth
slauth

Reputation: 3178

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

Upvotes: 11

Related Questions