Reputation: 961
I have a requirement where I want to access parameter store value and then use that later. This is how I am doing:
var options = {
Name: 'SecretAccessKey_temp',
WithDecryption: true
};
var secreretAccesKeyParam = ssm.getParameter(options).promise();
secreretAccesKeyParam.then(function (data, err) {
if (err) console.log(err, err.stack);
else {
const secretAccessKey = data.Parameter.Value
console.log(secretAccessKey)
}
});
This is giving me value but if I want to access secretAccessKey variable outside of this it's giving me 'undefined'. Can anyone please help me out to access this secretAccessKey variable outside of this function?
Upvotes: 2
Views: 3199
Reputation: 116
As your variable secreretAccesKeyParam
is a promise, you won't be able to access the context (e.g. secretAccessKey
) of your promise handler (e.g. function (data, err) {...}
). By definition of promise doing so :
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
var myRes = 'bar';
myPromise.then(dunction (data, err) {
myRes = data;
console.log(myRes); // executed asynchronously
});
console.log(data); // executed sychronously so printed first. myRes value is still 'bar'.
Would give you the output :
'bar'
'foo'
What you might want to do could be using an async function if you want to handle things as if they were synchronous.
var options = {
Name: 'SecretAccessKey_temp',
WithDecryption: true
};
var secreretAccesKeyParam = ssm.getParameter(options).promise();
(async () => {
try {
const data = await secreretAccesKeyParam;
} catch (err) {
console.log(err, err.stack);
}
const secretAccessKey = data.Parameter.Value;
console.log(secretAccessKey);
... // any action with your secret access key
})();
Or if you are already using handler function later :
let _secretAccessKey;
const getSecretAccessKey = async () => {
if (!_secretAccessKey) {
try {
const data = await secreretAccesKeyParam;
} catch (err) {
console.log(err, err.stack);
return null;
}
_secretAccessKey = data.Parameter.Value;
}
return Promise.resolve(_secretAccessKey);
}
...
async function mySuperHandler() {
const secretAccessKey = await getSecretAccessKey();
// do something with the secret
}
Upvotes: 1
Reputation: 41
How about set it as env ? Im currently use this method, but you have to make sure env is set before use it.
secreretAccesKeyParam.then(function (data, err) {
if (err) console.log(err, err.stack);
else {
process.env.secretAccessKey = data.Parameter.Value;
const secretAccessKey = process.env.secretAccessKey;
console.log(secretAccessKey);
}
});
Upvotes: 0