Skip to content

Instantly share code, notes, and snippets.

@tetsupanda
Last active August 25, 2020 14:51
Show Gist options
  • Save tetsupanda/c888d18b365af3eafad44be2bd440240 to your computer and use it in GitHub Desktop.
Save tetsupanda/c888d18b365af3eafad44be2bd440240 to your computer and use it in GitHub Desktop.
Node script that updates the credentials file, in the case you are using the AWS SDK and AWS CLI behind AWS SSO.
//Using encode, parse from 'ini' lib, probably not needed *shrugs*
async function setAWSCredentials () {
const userProfilePath = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']
const awsCacheFile = '/.aws/cli/cache'
const awsCredentialFile = '/.aws/credentials'
const cachefullPath = userProfilePath + awsCacheFile
const credsFullPath = userProfilePath + awsCredentialFile
const fileDirectory = await fs.promises.opendir(cachefullPath)
const filesToCompare = []
for await (const dirFile of fileDirectory) {
const wholeFilePath = cachefullPath + '/' + dirFile.name
const stats = await fs.promises.stat(wholeFilePath)
const fileObj = {
pathToFile: wholeFilePath,
lastModified: stats.mtime
}
filesToCompare.push(fileObj)
}
let fileToParse = filesToCompare[0].pathToFile
if(filesToCompare.length > 0) {
fileToParse = filesToCompare.sort((a, b) => b.lastModified - a.lastModified)[0].pathToFile
}
const { Credentials: creds } = JSON.parse(await fs.promises.readFile(fileToParse, 'utf-8'))
const AwsConfig = {
aws_access_key_id: creds.AccessKeyId,
aws_secret_access_key: creds.SecretAccessKey,
aws_session_token: creds.SessionToken,
region: 'us-east-1'
}
const config = parse(await fs.promises.readFile(credsFullPath, 'utf-8'))
config['default'] = AwsConfig
await fs.promises.writeFile(credsFullPath, encode(config), { encoding: 'utf-8', flag: 'w' })
AWS.config.update({
credentials: new AWS.Credentials(AwsConfig.aws_access_key_id, AwsConfig.aws_secret_access_key, AwsConfig.aws_session_token),
region: AwsConfig.region
})
}
@tetsupanda
Copy link
Author

Reference to the issues this works around:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment