3

I am trying to write a script that will setup a Rackspace cloud server and i'm having trouble with one aspect of it. When the script runs it will ask the user a couple questions to get the username and api key. I then use those values in a curl command. The output of the curl command needs to get assigned to a variable as well. This is what i have - i'm thinking there is just a syntax error i am missing. This isn't the whole script, it's just the only part i am having trouble with.

#!/bin/bash

# Ask questions to get login creds
read -p "Rackspace Username? " username
read -p "Rackspace API Key? " apikey

# Get Rackspace token
echo "Getting token..."
token=$(curl -s -X POST https://auth.api.rackspacecloud.com/v2.0/tokens \
    -d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"$username", "apiKey":"$apikey" } } }' \
    -H "Content-type: application/json" \
    | python -mjson.tool \
    | python -c 'import sys, json; print json.load(sys.stdin)["access"]["token"]["id"]')
echo "...done!"

.....

1 Answer 1

4

The problem with the below line is that $username and $apikey are inside single-quotes and bash variables are not evaluated inside single-quotes:

-d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"$username", "apiKey":"$apikey" } } }' \

To fix it, end the single-quote string before the bash variable and start it again afterwards:

-d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":'"$username"', "apiKey":'"$apikey"' } } }' \

If you need the literal double-quotes in the string for it to work, then we have to add them in inside the single-quoted portion of the string:

-d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"'"$username"'", "apiKey":"'"$apikey"'" } } }' \
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I did make one small tweak to get it to work. Had to change '"$username"' to "'$username'" and the same for the apikey.
@ryanpitts1 Glad it worked. For greatest safety, it should be "'"$username"'". This provides literal double-quotes that curl sees. It also causes bash to evaluate the variables inside double-quoted strings which is important if whitespace should appear in the variable's value. As your were commenting, I was adding a final version which incorporates this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.