Friday, January 7, 2022

[SOLVED] How do I insert a bash variable into the JSON body of a cURL request?

Issue

I am trying to run the following cURL command (taken from the ArgoCD documentation).

$ curl $ARGOCD_SERVER/api/v1/session -d $'{"username":"admin","password":"password"}'

With the proper credentials entered manually, it runs fine, but I have my password stored in an environment variable ($PASSWORD) and with the both the ' and " quotes it does not insert the password correctly.

$ curl $ARGOCD_SERVER/api/v1/session -d $'{"username":"admin","password":"$PASSWORD"}'

I suspect it uses the string literal $PASSWORD as the actual password, rather than the variable's content. How would I insert this variable correctly?


Solution

Like this:

curl $ARGOCD_SERVER/api/v1/session -d '{"username":"admin","password":"'$PASSWORD'"}'

or this:

curl $ARGOCD_SERVER/api/v1/session -d "{\"username\":\"admin\",\"password\":\"$PASSWORD\"}"

this'll probalby works too:

curl $ARGOCD_SERVER/api/v1/session -d "{'username':'admin','password':'$PASSWORD'}"

or:

printf -v data '{"username":"admin","password":"%s"}' "$PASSWORD"
curl $ARGOCD_SERVER/api/v1/session -d "$data"


Answered By - Ivan