Search code examples
bashcurlrackspace-cloud

Using JSON output in curl bash script


I want to upload a file automatically to rackspace files which requires an auth-token that is updated daily, so I want to create a script which gets the auth token and then uses that in the script to upload the file.

This is the command to get the auth token which outputs the key perfectly:

curl -s -X POST https://auth.api.rackspacecloud.com/v2.0/tokens\
     -d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"USER", "apiKey":"KEY" } } }'\
     -H "Content-type: application/json" | python -mjson.tool |\
python -c 'import sys, json;\
           print json.load(sys.stdin)[sys.argv[1]][sys.argv[2]][sys.argv[3]]'\
access token id

This is the command to upload the file:

curl -X PUT -T file.xml -D - \
-H "Content-Type: text/xml" \
-H "X-Auth-Token: TOKENGOESHERE" \
URL

I need to get the token from the first command into the TOKENGOESHERE place in the second command.

What I have tried so far is:

token = curl -s -X POST https://auth.api.rackspacecloud.com/v2.0/tokens -d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"USER", "apiKey":"KEY" } } }' -H "Content-type: application/json" | python -mjson.tool | python -c 'import sys, json; print json.load(sys.stdin)[sys.argv[1]][sys.argv[2]][sys.argv[3]]' access token id

curl -X PUT -T file.xml -D - \
-H "Content-Type: text/xml" \
-H "X-Auth-Token: $token" \
URL

but it didn't work and I am guessing it has something to do with the quotes but I don't know enough about bash to know what the problem is.

Thanks!


Solution

  • This should work:

    token=$(curl -s -X POST https://auth.api.rackspacecloud.com/v2.0/tokens \
        -d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"USER", "apiKey":"KEY" } } }' \
        -H "Content-type: application/json" \
        | python -mjson.tool \
        | python -c 'import sys, json; print json.load(sys.stdin)["access"]["token"]["id"]')
    
    curl -X PUT -T file.xml -D - \
        -H "Content-Type: text/xml" \
        -H "X-Auth-Token: $token" \
        URL