Home > Enterprise >  How do I insert a bash variable into the JSON body of a cURL request?
How do I insert a bash variable into the JSON body of a cURL request?

Time:10-28

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?

CodePudding user response:

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"

CodePudding user response:

You can use to create the JSON:

json=$(jq -c -n --arg username admin --arg password "$password" '$ARGS.named')

curl $ARGOCD_SERVER/api/v1/session -d "$json"

Using jq ensures that the JSON is properly formulated, no matter the contents of the variable:

$ password=$'with\'both"quotes'
$ declare -p password
declare -- password="with'both\"quotes"
$ jq -cn --arg username admin --arg password "$password" '$ARGS.named'
{"username":"admin","password":"with'both\"quotes"}
  • Related