Skip to content

Instantly share code, notes, and snippets.

@romanlv
Created March 24, 2023 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romanlv/941af6512bafa56282783abc53c559dc to your computer and use it in GitHub Desktop.
Save romanlv/941af6512bafa56282783abc53c559dc to your computer and use it in GitHub Desktop.
Renew AWS session key and update .env file
#!/usr/bin/env zx
const MFA_ARN = "...MFA_ARN..."
const baseFolder = "/Users/roman/dev/xyz"
const code = await question('What is MFA code? ')
// if using Yubikey
// const codeRes = await $`ykman oath accounts code ${MFA_ARN}`
// const code = codeRes.stdout.split(/\s+/)[1]
if (!code) {
throw "code not defined"
}
const sessionRes = await $`aws --profile main sts get-session-token --serial-number ${MFA_ARN} --token-code ${code}`
const credentials = JSON.parse(sessionRes.stdout).Credentials
console.log({ credentials })
await $`aws configure set aws_access_key_id ${credentials.AccessKeyId}`
await $`aws configure set aws_secret_access_key ${credentials.SecretAccessKey}`
await $`aws configure set aws_session_token ${credentials.SessionToken}`
const apps = [`${baseFolder}/web-graphql`];
async function replaceInFile(varName, value, file) {
await $`sed -i '' ${'/^' + varName + '=/s|=.*|=' + value + '|'} ${file}`
}
for(let folder of apps) {
cd(folder)
await replaceInFile("AWS_ACCESS_KEY_ID", credentials.AccessKeyId, ".env");
await replaceInFile("AWS_SECRET_ACCESS_KEY", credentials.SecretAccessKey, ".env");
await replaceInFile("AWS_SESSION_TOKEN", credentials.SessionToken, ".env");
}
@romanlv
Copy link
Author

romanlv commented Mar 24, 2023

requires zx to be installed

~/.aws/credentials

main profile is used only to generate session key that is saved as default

[main]
aws_access_key_id = ....
aws_secret_access_key = ...


[default]
aws_access_key_id = ....
aws_secret_access_key = ...
aws_session_token =  ....

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