Skip to content

Instantly share code, notes, and snippets.

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 qoomon/8141bbf7ed8e9ead170c78cda42a09c5 to your computer and use it in GitHub Desktop.
Save qoomon/8141bbf7ed8e9ead170c78cda42a09c5 to your computer and use it in GitHub Desktop.
AWSParametersAndSecretsLambdaExtension
/**
* @param secretId the ARN or name of the secret.
* @param version the version stage or version id
* @see https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets_lambda.html
* @see https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html
*/
export async function getSecretString(secretId: string, version?: SecretManagerSecretVersionStage | string) {
const extensionHttpPortPort = process.env["PARAMETERS_SECRETS_EXTENSION_HTTP_PORT"] ? parseInt(process.env["PARAMETERS_SECRETS_EXTENSION_HTTP_PORT"]) : 2773
const secretManagerRequestUrl = new URL(`http://localhost:${extensionHttpPortPort}/secretsmanager/get`)
secretManagerRequestUrl.searchParams.append('secretId', secretId)
// if version set and includes '-' it is a version id (a1b2c3d4-5678-90ab-cdef-EXAMPLE11111)
if (version?.includes('-')) secretManagerRequestUrl.searchParams.append('versionId', version)
// otherwise it is a version stage
else if (version) secretManagerRequestUrl.searchParams.append('versionStage', version)
return await fetch(secretManagerRequestUrl, {
headers: {
hostname: 'localhost',
'X-Aws-Parameters-Secrets-Token': process.env["AWS_SESSION_TOKEN"]!
}
}).then(response => {
if (!response.ok) throw new Error(`Could not get secret ${secretId}:${version || 'AWSCURRENT'}. ${secretManagerRequestUrl}`
+ `\n${response.status} (${response.statusText}) payload: ${response.text()}`);
return response;
}).then(response => response.json())
.then(data => data['SecretString'] as string)
}
export async function getSecretObject(secretId: string, version?: SecretManagerSecretVersionStage | string) {
return await getSecretString(secretId, version)
.then(secretString => JSON.parse(secretString) as SecretManagerSecretObject)
}
export type SecretManagerSecretVersionStage = 'AWSCURRENT' | 'AWSPREVIOUS' | 'AWSPENDING'
export type SecretManagerSecretObject = { [key: string]: string }
new lambda.Function(this, 'Lambda', {
// ...
paramsAndSecrets: ParamsAndSecretsLayerVersion.fromVersion(ParamsAndSecretsVersions.V1_0_103, {
cacheSize: 10,
secretsManagerTtl: Duration.seconds(300),
parameterStoreTtl: Duration.seconds(300),
}),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment