0

I am curling Azure Log Analytics for some info, but first I need to grab an OAuth token from 1 command and pass it into the next. I have the following Curl commands which I have tested fine on their own (copying pasting the output for the next input), however I want to pass the OAuth token output as a variable for an automation task, but for some reason it is not able to read the variable into the next command.

token=$(curl -X POST \
  https://login.microsoftonline.com/{{subscriptionID}}/oauth2/token \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials&client_id={{clientID}}&client_secret={{clientSECRET}}&resource=https%3A%2F%2Fapi.loganalytics.io' \
  | jq .access_token)


curl -X POST \
  https://api.loganalytics.io/v1/workspaces/{{workspaceID}}/query \
  -H 'Authorization: Bearer $token' \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -d '{ "query": "AzureActivity | summarize count() by Category" }'

Unfortunately when I run this command it responds back that a token is needed.

{"error":{"message":"Valid authentication was not provided","code":"AuthorizationRequiredError"}}

However, if I were to echo the $token variable it shows that it was saved

beefcake@ubuntu:~$ echo $token
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1...."

As I said, the commands work fine if I remove the token=$(..) and just copy/paste the output into the next input. Any ideas why this won't work for automation?

Beefcake
  • 733
  • 2
  • 12
  • 37

1 Answers1

1

@Aserre had the right mindset. Turns out that jq copies the inverted commas " " from the string, whereas the bearer token requires none. Thus my first command should have looked like this:

token=$(curl -X POST \
  https://login.microsoftonline.com/{{subscriptionID}}/oauth2/token \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials&client_id={{clientID}}&client_secret={{clientSECRET}}&resource=https%3A%2F%2Fapi.loganalytics.io' \
  | jq -r .access_token)

Note the last line that has the -r command for removing the double quotes. Which showed an echo of:

beefcake@ubuntu:~$ echo $token
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs....

Note the " " removed from the echo. In addition to that, I had to alter the next command where I replaced 'Authorization: Bearer $token' with "Authorization: Bearer $token":

curl -X POST \
  https://api.loganalytics.io/v1/workspaces/{{workspaceID}}/query \
  -H "Authorization: Bearer $token" \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -d '{ "query": "AzureActivity | summarize count() by Category" }'
Beefcake
  • 733
  • 2
  • 12
  • 37