I am trying to parse the response from aws secretsmanager
The output looks like:
{
"ARN": "arn:aws:secretsmanager:us-west-2:0000:secret:token-0000",
"Name": "token",
"VersionId": "0000-0000-0000-0000-0000",
"SecretString": "{\"TOKEN\":\"000000000000\"}",
"VersionStages": ["AWSCURRENT"],
"CreatedDate": "0000"
}
When attempting to parse this string with JSON.parse(), it attempts to parse the string value in SecretString which has escaped quotes.
I would have expected to need to JSON.parse the response in two steps however this does not work.
#!/bin/bash
TOKEN=$(node -e "\
const result = JSON.parse('$(aws secretsmanager get-secret-value --secret-id $ARN)'); \
const token = JSON.parse(result.SecretString); \
console.log(token); \
")
echo $TOKEN
How can I prevent the JSON.parse function from attempting to parse the string value of the SecretString - Alternatively, is there a better way to obtain the value?
JSON.parse does not attempt to parse JSON-encoded strings contained within the parsed object, so I don't think this is what's causing your problem. It's more likely to do with the shell's handling of the quotes.
I think a better way to do this would be to have your Node script call the aws CLI using child_process.execFile, rather than having the shell call aws and pass the result into Node.
If you need to access the ARN variable from Node you can do it using process.env.ARN.
Here's some code that should do the trick:
async function main()
{
const child_process = require('child_process');
const util = require('util');
const execFile = util.promisify(child_process.execFile);
const json = (await execFile('aws', ['secretsmanager', 'get-secret-value', '--secret-id', process.env.ARN])).stdout;
const result = JSON.parse(json);
const token = result.SecretString;
console.log(token);
}
main();
If you're going to be needing to do more of this kind of stuff, it might be worth looking at the AWS SDK for NodeJS. Even with execFile, there are still some pitfalls with using CLI tools programmatically in this way, especially if you need to pass JSON into the CLI tool.
You can do:
const json = {
"ARN": "arn:aws:secretsmanager:us-west-2:0000:secret:token-0000",
"Name": "token",
"VersionId": "0000-0000-0000-0000-0000",
"SecretString": "{\"TOKEN\":\"000000000000\"}",
"VersionStages": ["AWSCURRENT"],
"CreatedDate": "0000"
}
json.SecretString = JSON.parse(json.SecretString)
const { SecretString: { TOKEN: token } } = json
console.log('Token:', token)
try with single quotes instead of double quotes for the string value of the JSON
{
"ARN": 'arn:aws:secretsmanager:us-west-2:0000:secret:token-0000',
"Name": 'token',
"VersionId": '0000-0000-0000-0000-0000',
"SecretString": '{\"TOKEN\":\"000000000000\"}',
"VersionStages": ['AWSCURRENT'],
"CreatedDate": '0000'
}