Using gitlab CI yaml with multiline bash command (e.g curl with a json header)

119 views Asked by At

Sometimes I struggle at the most stupid places.. But how can I issue a multiline curl from gitlab ci's yaml file? I tried the following:

curl --request POST \
    --header 'Content-Type: application/json' \
    --header "JOB-TOKEN: $CI_JOB_TOKEN" \
    --data "{ \
      \"name\": \"$CI_PROJECT_NAME\", \
    }" \
    "$CI_API_V4_URL/projects/$CI_PROJECT_ID/releases"

Which yields:

An error has occurred and reported in the system's low-level error handler.

Now I think this is more bash specific, so I tried to use single quotes:

  curl --request POST \
    --header 'Content-Type: application/json' \
    --header 'JOB-TOKEN: $CI_JOB_TOKEN' \
    --data '{
      "name": "$CI_PROJECT_NAME"
    }' \
    "$CI_API_V4_URL/projects/$CI_PROJECT_ID/releases"

That works (well it gives me a server response that is) but bash will now take the variables literally, so $CI_JOB_TOKEN is not replaced, also not $CI_PROJECT_NAME.

How can I get this to work?

2

There are 2 answers

1
Philipp Parzer On

try following

  script:
    - >
      curl --fail -X "POST"
      "$CI_API_V4_URL/projects/$CI_PROJECT_ID/releases"
      -H "Content-Type: application/json"
      -H "JOB-TOKEN: $CI_JOB_TOKEN"
      --data '{
        "name": "$CI_PROJECT_NAME"
      }'    

0
glades On

Found quite a nice workaround using envsubst:

  script:
    - >
      echo '{
          "name": "will be replaced -> ${CI_COMMIT_SHORT_SHA}",
          "tag_name": "v0.6",
          "description": "Super nice release",
          "ref": "master",
          "assets": {
            "links": [{
              "name": "hoge",
              "url": "https://google.com",
              "direct_asset_path": "/binaries/linux-amd64",
              "link_type":"other"
            }]
          }
        }' > payload.json
    - |
      curl \
        --header 'Content-Type: application/json' \
        --header "JOB-TOKEN: $CI_JOB_TOKEN" \
        --data "$(cat payload.json | envsubst)" \
        --request POST "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/releases"

Just add apk add gettext to your alpine image