Skip to content

Instantly share code, notes, and snippets.

@andreineculau
Created December 22, 2017 10:55
Show Gist options
  • Save andreineculau/a186c2181a3099a422abc293c8e79fef to your computer and use it in GitHub Desktop.
Save andreineculau/a186c2181a3099a422abc293c8e79fef to your computer and use it in GitHub Desktop.
fucking get aws-sdk-js to read your aws-cli assumed role
import aws from 'aws-sdk';
import fs from 'fs';
import ini from 'ini';
import path from 'path';
// compatibility with aws-cli
let cliCacheFolder = path.join(process.env.HOME, '.aws', 'cli', 'cache');
let awsProfile = process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE;
if (awsProfile) {
try {
let configIni = ini.parse(fs.readFileSync(
`${process.env.HOME}/.aws/config`,
'utf-8'
));
let awsProfileConfig = configIni[`profile ${awsProfile}`];
if (awsProfileConfig && awsProfileConfig.role_arn) {
let stsAssumeRoleArnPrefix = awsProfileConfig.role_arn.replace('iam', 'sts').replace(':role/', ':assumed-role/');
let filenames = fs.readdirSync(cliCacheFolder);
let files = filenames.map(function(filename) {
filename = path.join(cliCacheFolder, filename);
let stat = fs.statSync(filename);
return {
filename,
mtime: new Date(stat.mtime)
};
}).sort(function(a, b) {
if (a.mtime < b.mtime) {
return 1;
}
if (a.mtime > b.mtime) {
return -1;
}
return 0;
});
let awsCliCache;
files.find(function(file) {
try {
let cache = JSON.parse(fs.readFileSync(file.filename));
if (cache && cache.AssumedRoleUser && cache.AssumedRoleUser.Arn.indexOf(stsAssumeRoleArnPrefix) === 0) {
awsCliCache = cache;
return true;
}
} catch (_err) {
}
return false;
});
if (awsCliCache) {
let sts = new aws.STS();
aws.config.credentials = sts.credentialsFrom(awsCliCache);
}
}
} catch (_err) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment