How can I efficiently extract variables from JSON with xonsh?

126 Views Asked by At

Given a variable AWS_ASSUMED_ROLE that contains the output of the aws sts assume-role (a JSON string), I can write the following in bash.

export AWS_ACCESS_KEY_ID=$( jq -r '.Credentials.AccessKeyId' <<<$AWS_ASSUMED_ROLE )
export AWS_SECRET_ACCESS_KEY=$( jq -r '.Credentials.SecretAccessKey' <<<$AWS_ASSUMED_ROLE )
export AWS_SESSION_TOKEN=$( jq -r '.Credentials.SessionToken' <<<$AWS_ASSUMED_ROLE )

aws sts get-caller-identity

However, in order to get the same functionality in xonsh, I need two echo commands.

$AWS_ACCESS_KEY_ID     = $( echo -n @$( echo @(AWS_ASSUMED_ROLE) | jq -r '.Credentials.AccessKeyId') )
$AWS_SECRET_ACCESS_KEY = $( echo -n @$( echo @(AWS_ASSUMED_ROLE) | jq -r '.Credentials.SecretAccessKey' ) )
$AWS_SESSION_TOKEN     = $( echo -n @$( echo @(AWS_ASSUMED_ROLE) | jq -r '.Credentials.SessionToken' ) )

aws sts get-caller-identity

The inner one to provide jq with the input data. The outer one to be able to set the corresponding environment variable with a string value without a new line.

Okay, a little awkward but not too bad. However, is there a better way to do it?

1

There are 1 best solutions below

1
On

jq is a great tool -- for this particular case with xonsh, I'd lean on the json module instead, though. Assuming that AWS_ASSUMED_ROLE is some stringified json blob:

import json

blob = json.loads(AWS_ASSUMED_ROLE)
$AWS_ACCESS_KEY_ID = blob["Credentials"]["AccessKeyId"]
...