AWS CDK(v2): Enabling Lambda to read SystemManager's parameter store

If you want to use key information from outside AWS in Lambda, there is a way to pass it via the SystemManager parameter store. You can also pass it as an environment variable, but if you want to make it a bit more secure, this way seems to be better. You can easily specify the permissions to Lambda in the CDK.

Version

  • node: 16.13.1
  • aws-cdk: 2.2.0
  • tsc: 4.5.4

HowTo

Stack side

On the Stack side, do grantRead() while passing the parameter name that you want to allow Lambda to read as an environment variable such as KEY_NAME.

/// lib/xyz-stack.ts

const KEY_NAME = '/awesome-app/external_key';

export class XyzStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
...

    const myLambda = new NodejsFunction(this, "MyAwesomeFunction", {
      entry: path.join(__dirname, './lambda/main.ts'),
      handler: "handler",
      environment: {
        KEY_NAME: KEY_NAME,
      },
    });

    const secureStringParameter = StringParameter.fromSecureStringParameterAttributes(this, 'AwesomeKey', {
      parameterName: KEY_NAME,
      version: 1,
    });
    secureStringParameter.grantRead(myLambda);

...

In the case of SecureString, the version number is required, such as version: 1. Version number is the number written below in the management console.

Parameter Version

Lambda side

Lambda will get the parameter name from env.KEY_NAME and read it using SSM. Since aws-sdk is used, you need to npm install aws-sdk.

/// lib/lambda/main.ts
import { env } from "process";
import { SSM } from "aws-sdk";

export const handler = async (event: any = {}): Promise<any> => {
  const awesomeKey = await getAwesomeKey();
  ...

}

async function getAwesomeKey(): Promise<string> {
    const ssm = new SSM({ region: 'ap-northeast-1' });
    const request = {
        Name: env.KEY_NAME!,
        WithDecryption: true,
    };
    const response = await ssm.getParameter(request).promise();
    return response.Parameter!.Value!;
}

Reference