简体   繁体   中英

Set environment variables from string of key/value pairs

I'm using AWS Secrets Manager to pull some environment variables during the deployment process for a React CloudFront Web App. I have not written a ton of javascript - and I'm trying to figure out the best way to extract values from my string of 'secrets' and set them as environment variables.

For some context, I'm able to hook into the AWS-SDK just fine and retrieve my secrets - they look like this:

console.log(secret)
> {"JOE":"https://joe.com","MIKE":"http://mike.com"}

The first surprise came when I decided to check the type of my secret and came to find out javascript is evaluating it as a string:

console.log(typeof secret);
> string

Since I now know I'm working with a string, I'm attempting to find the most efficient way to parse this 'string' (though it looks like a dictionary to my python eyes) and set each key/pair value within the string as environment variables.

The first I tried was the 'modules.export' method - I did something like:

module.exports = secret;

if(process.env.JOE) {
    console.log('It is set!');
}
else {
    console.log('No set!');
}

Of course, this was too good to be true - and did not appear to work as I'd hoped.

The next thing I tried was simply to try and index the string and see what it might return:

console.log(secret["JOE"]);
> undefined

No luck there.

I have tried a variety of other simple builtin javascript methods but I'm not seeming to make any progress. Am I think correctly that I should first load this into a dictionary, then possibly use modules.export to set each key/pair in the dict as environment variables ?

That looks like a JSON string. Just call JSON.parse(secret) and it should give you the object you expected.

Data from web servers always will return as a string, regardless of its format. Refer to this link: https://www.w3schools.com/js/js_json_parse.asp This should convert the data to JSON which you can then treat as a regular JavaScript object.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM