Skip to content

Instantly share code, notes, and snippets.

@josefaidt
Created January 30, 2024 00:46
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 josefaidt/a3b4e80939a2c3576b9d2ee2cc536222 to your computer and use it in GitHub Desktop.
Save josefaidt/a3b4e80939a2c3576b9d2ee2cc536222 to your computer and use it in GitHub Desktop.
fetch-aws-credentials.ts
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