I what to get a system manager parameter store secret and add it in my lambda env variables at build time with aws cdk
Other aws deployment libraries can do it like serverless framework or even sst that is based on cdk
The only way I found to do this at build time is using a AwsCustomResource, but it creates a lambda just to do this that is not a viable option
import * as cr from 'aws-cdk-lib/custom-resources';
const ssmSecureString = new cr.AwsCustomResource(stack, 'SSMParameter', {
onUpdate: {
service: 'SSM',
action: 'getParameter',
parameters: {
Name: 'BIGQUERY_JSON_CRED',
WithDecryption: true,
},
physicalResourceId: cr.PhysicalResourceId.of('BIGQUERY_JSON_CRED'), // update physical ID to always fetch the latest value
},
policy: cr.AwsCustomResourcePolicy.fromSdkCalls({
resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE,
}),
});
Another way I've tryed
const bq = ssm.StringParameter.fromSecureStringParameterAttributes(stack, 'BIGQUERY_JSON_CRED', {
parameterName: 'BIGQUERY_JSON_CRED',
version: 1,
}).stringValue
const lambdaFunction = new NodejsFunction(stack, functionName, {
entry: path.resolve(__dirname, `../src/functions/hello/handler.ts`),
handler: 'handler',
runtime: lambda.Runtime.NODEJS_20_X,
environment: {
BIGQUERY_JSON_CRED: bq.stringValue,
},
});
When I try doing something simple like this I have an error
❌ Deployment failed: Error [ValidationError]: Parameters [BIGQUERY_JSON_CRED] referenced by template have types not supported by CloudFormation.
I want to avoid calling ssm at runtime in the lambda code
I recommend a different approach. Copying secrets to environment variables is not a secure practice. If it really is a secret, it should not be stored in a lambda environment variable. Instead, you can use the AWS Parameters and Secrets Lambda Extension to fetch secrets in your running code, and since this extension employs a caching mechanism it is very fast at runtime.
To use parameters from Parameter Store in AWS Lambda functions without using an SDK, you can use the AWS Parameters and Secrets Lambda Extension. This extension retrieves parameter values and caches them for future use. Using the Lambda extension can reduce your costs by reducing the number of API calls to Parameter Store. Using the extension can also improve latency because retrieving a cached parameter is faster than retrieving it from Parameter Store.
A Lambda extension is a companion process that augments the capabilities of a Lambda function. An extension is like a client that runs in parallel to a Lambda invocation.
See https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html for more details.
Also see