AWS Compute Blog
Retrieving parameters and secrets with Powertools for AWS Lambda (TypeScript)
This post is written by Andrea Amorosi, Senior Solutions Architect and Pascal Vogel, Solutions Architect.
When building serverless applications using AWS Lambda, you often need to retrieve parameters, such as database connection details, API secrets, or global configuration values at runtime. You can make these parameters available to your Lambda functions via secure, scalable, and highly available parameter stores, such as AWS Systems Manager Parameter Store or AWS Secrets Manager.
The Parameters utility for Powertools for AWS Lambda (TypeScript) simplifies the integration of these parameter stores inside your Lambda functions. The utility provides high-level functions for retrieving secrets and parameters, integrates caching and transformations, and reduces the amount of boilerplate code you must write.
The Parameters utility supports the following parameter stores:
- AWS Systems Manager Parameter Store
- AWS Secrets Manager
- AWS AppConfig
- Amazon DynamoDB
- Custom parameter store providers
The Parameters utility is part of the Powertools for AWS Lambda (TypeScript), which you can use in both JavaScript and TypeScript code bases. Implementing guidance from the Serverless Applications Lens of the AWS Well-Architected Framework, Powertools provides utilities to ease the adoption of best practices such as distributed tracing, structured logging, and asynchronous business and application metrics.
For more details, see the Powertools for AWS Lambda (TypeScript) documentation on GitHub and the introduction blog post.
This blog post shows how to use the new Parameters utility to retrieve parameters and secrets in your JavaScript and TypeScript Lambda functions securely.
Getting started with the Parameters utility
Initial setup
The Powertools toolkit is modular, meaning that you can install the Parameters utility independently from the Logger, Tracing, or Metrics packages. Install the Parameters utility library in your project via npm:
npm install @aws-lambda-powertools/parameters
In addition, you must add the AWS SDK client for the parameter store you are planning to use. The Parameters utility supports AWS SDK v3 for JavaScript only, which allows the utility to be modular. You install only the needed SDK packages to keep your bundle size small.
Next, assign appropriate AWS Identity and Access Management (IAM) permissions to the Lambda function execution role of your Lambda function that allow retrieving parameters from the parameter store.
The following sections illustrate how to perform the previously mentioned steps for some typical parameter retrieval scenarios.
Retrieving a single parameter from SSM Parameter Store
To retrieve parameters from SSM Parameter Store, install the AWS SDK client for SSM in addition to the Parameters utility:
npm install @aws-sdk/client-ssm
To retrieve an individual parameter, the Parameters utility provides the getParameter
function:
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
// Retrieve a single parameter
const parameter = await getParameter('/my/parameter');
console.log(parameter);
};
Finally, you need to assign an IAM policy with the ssm:GetParameter
permission to your Lambda function execution role. Apply the principle of least privilege by scoping the permission to the specific parameter resource as shown in the following policy example:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:GetParameter"
],
"Resource": [
"arn:aws:ssm:AWS_REGION:AWS_ACCOUNT_ID:my/parameter"
]
}
]
}
Adjusting cache TTL
By default, the retrieved parameters are cached in-memory for 5 seconds. This cached value is used for further invocations of the Lambda function until it expires. If your application requires a different behavior, the Parameters utility allows you to adjust the time-to-live (TTL) via the maxAge
argument.
Building on the previous example, if you want to cache your retrieved parameter for 30 instead of 5 seconds, you can adapt your function code as follows:
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
// Retrieve a single parameter with a 30 seconds cache TTL
const parameter = await getParameter('/my/parameter', { maxAge: 30 });
console.log(parameter);
};
In other cases, you may want to always retrieve the latest value from the parameter store and ignore any cached value. To achieve this, set the forceFetch
parameter to true
:
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
// Always retrieve the latest value of a single parameter
const parameter = await getParameter('/my/parameter', { forceFetch: true });
console.log(parameter);
};
For details, see Always fetching the latest in the Powertools for AWS Lambda (TypeScript) documentation.
Decoding parameters stored in JSON or base64 format
If some of your parameters are stored in base64 or JSON, you can deserialize them via the Parameters utility’s transform
argument.
Considering a parameter stored in SSM as JSON, it can be retrieved and deserialized as follows:
import { Transform } from '@aws-lambda-powertools/parameters';
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise => {
// Retrieve and deserialize a single JSON parameter
const valueFromJson = await getParameter('/my/json/parameter', { transform: Transform.JSON });
console.log(valueFromJson);
};
The Parameters utility supports the transform
argument for all parameter store providers and high-level functions. For details, see Deserializing values with transform parameters.
Working with encrypted parameters in SSM Parameter Store
SSM Parameter Store supports encrypted secure string parameters via the AWS Key Management Service (AWS KMS). The Parameters utility allows you to retrieve these encrypted parameters by adding the decrypt
argument to your request.
For example, you could retrieve an encrypted parameter as follows:
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
// Decrypt the parameter
const decryptedParameter = await getParameter('/my/encrypted/parameter', { decrypt: true });
console.log(decryptedParameter);
};
In this case, the Lambda function execution role needs to have the kms:Decrypt
IAM permission in addition to ssm:GetParameter
.
Retrieving multiple parameters from SSM Parameter Store
Besides retrieving a single parameter using getParameter, you can also use getParameters
to recursively retrieve multiple parameters under a SSM Parameter Store path, or getParametersByName
to retrieve multiple distinct parameters by their full name.
You can also apply custom caching, transform, or decrypt configurations per parameter when using getParametersByName
. The following example retrieves three distinct parameters from SSM Parameter Store with different caching and transform configurations:
import { getParametersByName } from '@aws-lambda-powertools/parameters/ssm';
import type {
SSMGetParametersByNameOptionsInterface
} from '@aws-lambda-powertools/parameters/ssm/types';
const props: Record<string, SSMGetParametersByNameOptionsInterface> = {
'/develop/service/commons/telemetry/config': { maxAge: 300, transform: 'json' },
'/no_cache_param': { maxAge: 0 },
'/develop/service/payment/api/capture/url': {}, // When empty or undefined, it uses default values
};
export const handler = async (): Promise<void> => {
// This returns an object with the parameter name as key
const parameters = await getParametersByName(props);
for (const [ key, value ] of Object.entries(parameters)) {
console.log(`${key}: ${value}`);
}
};
Retrieving multiple parameters requires the GetParameter
and GetParameters
permissions to be present in the Lambda function execution role.
Retrieving secrets from Secrets Manager
To securely store sensitive parameters such as passwords or API keys for external services, Secrets Manager is a suitable option. To retrieve secrets from Secrets Manager using the Parameters utility, install the AWS SDK client for Secrets Manager in addition to the Parameters utility:
npm install @aws-sdk/client-secrets-manager
Now you can access a secret using its key as follows:
import { getSecret } from '@aws-lambda-powertools/parameters/secrets';
export const handler = async (): Promise<void> => {
// Retrieve a single secret
const secret = await getSecret('my-secret');
console.log(secret);
};
Getting a secret from Secrets Manager requires you to add the secretsmanager:GetSecretValue
IAM permission to your Lambda function execution role.
Retrieving an application configuration from AppConfig
If you plan to leverage feature flags or dynamic application configurations in your applications built on Lambda, AppConfig is a suitable option. The Parameters utility makes it easy to fetch configurations from AppConfig while benefitting from utility features such as caching and transformations.
For example, considering an AppConfig application called my-app
with an environment called my-env
, you can retrieve its configuration profile my-configuration
as follows:
import { getAppConfig } from '@aws-lambda-powertools/parameters/appconfig';
export const handler = async (): Promise<void> => {
// Retrieve a configuration, latest version
const config = await getAppConfig('my-configuration', {
environment: 'my-env',
application: 'my-app'
});
console.log(config);
};
Retrieving a configuration requires both the appconfig:GetLatestConfiguration
and appconfig:StartConfigurationSession
IAM permissions to be attached to the Lambda function execution role.
Retrieving a parameter from a DynamoDB table
DynamoDB’s low latency and high flexibility make it a great option for storing parameters. To use DynamoDB as a parameter store via the Parameters utility, install the DynamoDB AWS SDK client and utility package in addition to the Parameters utility.
npm install @aws-sdk/client-dynamodb @aws-sdk/util-dynamodb
By default, the Parameters utility expects the DynamoDB table containing the parameters to have a partition key of id and an attribute called value. For example, assuming an item with an id of my-parameter
and a value of my-value
stored in an DynamoDB table called my-table
, you can retrieve it as follows:
import { DynamoDBProvider } from '@aws-lambda-powertools/parameters/dynamodb';
const dynamoDBProvider = new DynamoDBProvider({ tableName: 'my-table' });
export const handler = async (): Promise<void> => {
// Retrieve a value from DynamoDB
const value = await dynamoDBProvider.get('my-parameter');
console.log(value);
};
In case of retrieving a single parameter from DynamoDB, the Lambda function execution role needs to have the dynamodb:GetItem
IAM permission.
The Parameters utility DynamoDB provider can also retrieve multiple parameters from a table with a single request via a DynamoDB query. See DynamoDB provider in the Powertools for AWS Lambda (TypeScript) documentation for details.
Conclusion
This blog post introduces the Powertools for AWS Lambda (TypeScript) Parameters utility and demonstrates how it is used with different parameter stores. The Parameters utility allows you to retrieve secrets and parameters in your Lambda function from SSM Parameter Store, Secrets Manager, AppConfig, DynamoDB, and custom parameter stores. By using the utility, you get access to functionality such as caching and transformation, and reduce the amount of boilerplate code you need to write for your Lambda functions.
To learn more about the Parameters utility and its full set of functionality, take a look at the Powertools for AWS Lambda (TypeScript) documentation.
Share your feedback for Powertools for AWS Lambda (TypeScript) by opening a GitHub issue.
For more serverless learning resources, visit Serverless Land.