Sunday, February 27, 2022

[SOLVED] How to save curl output in gitlab variable?

Issue

For a project we would like to call an API and save the result of this curl in a variable.

The pipeline is built like this:

stages:
  - download

scan:
  stage: download
  image: ubuntu
  variables:
    TOKEN: 
  
  script:

    - apk add curl
    - apk add jq
    
    - TOKEN=$('curl -H "Content-Type: application/json" -d "{\"username\":\"$USER", \"password\":\"$PWD"}" https://example.org/api2/authenticate | jq .token ')
    #- echo $TOKEN

I got this error:

This GitLab CI configuration is invalid: jobs:scan:script config should be a string or a nested array of strings up to 10 levels deep.

The curl command (removed from the $(), but kept the single quotes to wrap the double quotes) works regularly and returns the string with the token inside. The only problem turns out to be encapsulating the result in a variable. What can be done?

Thank you.


Solution

Try instead of this

- TOKEN=$('curl -H "Content-Type: application/json" -d "{\"username\":\"$USER", \"password\":\"$PWD"}" https://example.org/api2/authenticate | jq .token ')

The following

- |
  TOKEN=$(curl -H "Content-Type: application/json" -d "{\"username\":\"$USER\", \"password\":\"$PWD\"}" https://example.org/api2/authenticate | jq .token)

P.S. I would suggest begin by running

- |
  curl -H "Content-Type: application/json" -d "{\"username\":\"$USER\", \"password\":\"$PWD\"}" https://example.org/api2/authenticate 

In order to debug the curl command output, before running jq



Answered By - Tolis Gerodimos
Answer Checked By - Mildred Charles (WPSolving Admin)