This is how to use curl
in GitLab CI YAML script with no hassle in 2021.
The following example CI pipeline uses curl
to trigger the remote application build and deploy on Digital Ocean App Platform for the real use case sake.
Here curl
uses URL arguments from GitLab variables and passes a JSON body with the request:
deploy:
stage: deploy
variables:
DEPLOY_CURL_COMMAND_BODY: "'{\"force_build\":true}'"
DEPLOY_CURL_COMMAND: 'curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $DO_APP_PLATFORM_API_TOKEN" --data $DEPLOY_CURL_COMMAND_BODY https://api.digitalocean.com/v2/apps/$DO_APP_PLATFORM_STAGE_FRONT_APP_ID/deployments'
script:
# The following echoes are just a debug output
- echo "Stage Deploy to DigitalOcean App Platform"
- echo "$DO_APP_PLATFORM_API_TOKEN"
- echo "$DO_APP_PLATFORM_STAGE_FRONT_APP_ID"
- echo $DEPLOY_CURL_COMMAND
# This line actually executes curl command saved within the variable.
- 'eval "$DEPLOY_CURL_COMMAND"'
The pipeline puts a command's argument into a variable. Then eval
the variable. Note the single quotes wrapping the variable value and eval
command. They are principal.
The variable uses as well the extrapolated repository level variables for secrets.
Note that GitLab YAML does not complain about a lone :
colon sign. It complains about :
- a colon followed by space sign. So the above example is universally applicable for both cases. But simpler implementation as per @Mavichow answer would serve well when there is no space after colon in the command line.
Note as well that you can use curl body
parameter that requires being wrapped in single quotas itself. Note there is no space after comma in body
variable content.
Some other ways to avoid :
(colon followed by space) issues:
after_script:
# Note how the single quotes eliminate colon+space issue
- 'MESSAGE="Tests finished with status: ${CI_JOB_STATUS}"'
# Here pipe operator allows using colon+space on the next line
- |
curl -X POST -H 'Content-type: application/json' --data "{\"text\":\"$MESSAGE\"}" "$SOME_URL"