Created
January 30, 2024 00:46
-
-
Save josefaidt/a3b4e80939a2c3576b9d2ee2cc536222 to your computer and use it in GitHub Desktop.
fetch-aws-credentials.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AssumeRoleCommand, STSClient } from '@aws-sdk/client-sts' | |
export type fetchAwsCredentialsOptions = { | |
/** | |
* AWS Region to use | |
* @default {process.env.AWS_REGION} | |
*/ | |
region: string | |
} | |
/** | |
* Fetch temporary AWS credentials | |
* @param roleToAssume full ARN of the role to assume | |
* @returns AWS credentials | |
*/ | |
export async function fetchAwsCredentials( | |
roleToAssume: string, | |
{ region }: fetchAwsCredentialsOptions | |
) { | |
const REGION = region || process.env.AWS_REGION | |
const client = new STSClient({ region: REGION }) | |
const command = new AssumeRoleCommand({ | |
RoleArn: roleToAssume, | |
RoleSessionName: 'HeyAmplifyDiscordBot', | |
}) | |
const response = await client.send(command) | |
const { Credentials } = response | |
if ( | |
!Credentials?.AccessKeyId || | |
!Credentials.SecretAccessKey || | |
!Credentials.SessionToken || | |
!Credentials.Expiration | |
) { | |
throw new Error('Failed to retrieve credentials') | |
} | |
return { | |
accessKeyId: Credentials.AccessKeyId, | |
secretAccessKey: Credentials.SecretAccessKey, | |
sessionToken: Credentials.SessionToken, | |
expiration: Credentials.Expiration, | |
} | |
} | |
export type AwsCredentials = Awaited<ReturnType<typeof fetchAwsCredentials>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment