Created
November 30, 2022 06:07
-
-
Save mangosmoothie/ad2f843361d51f61ca9d7771e716cea5 to your computer and use it in GitHub Desktop.
TypeScript / Node utilize credential_process in for AWS profile to access S3
This file contains 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 * as https from 'https'; | |
import * as AWS from 'aws-sdk'; | |
import { execFileSync } from 'child_process'; | |
import * as process from 'process'; | |
const REGION = process.env.AWS_REGION || 'us-east-1'; | |
const { CREDENTIALS_PROCESS } = process.env; | |
export const createDefaultConfiguration = async (): Promise<AWS.S3.ClientConfiguration> => { | |
const config = { | |
REGION, | |
httpOptions: { | |
agent: new https.Agent({ | |
rejectUnauthorized: false, | |
}), | |
}, | |
}; | |
// extract from 'credentials_process' that returns a json object to std out | |
if (CREDENTIALS_PROCESS) { | |
const credentialChain = new AWS.CredentialProviderChain(); | |
const creds = JSON.parse(execFileSync(CREDENTIALS_PROCESS).toString()); | |
credentialChain.providers.unshift( | |
new AWS.Credentials({ | |
accessKeyId: creds.AccessKeyId, | |
secretAccessKey: creds.SecretAccessKey, | |
sessionToken: creds.SessionToken, | |
}) | |
); | |
return { | |
...config, | |
credentials: await credentialChain.resolvePromise(), | |
}; | |
} | |
return config; | |
}; | |
const getS3 = async () => { | |
return new AWS.S3({ | |
...(await createDefaultConfiguration()), | |
apiVersion: '2006-03-01', | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment