ACTS Blog Selection
We use machine learning technology to do auto-translation. Click "English" on top navigation bar to check Chinese version.
Retrieving parameters and secrets with Powertools for Amazon Web Services Lambda (TypeScript)
This post is written by Andrea Amorosi, Senior Solutions Architect and Pascal Vogel, Solutions Architect.
When building serverless applications using
The
The Parameters utility supports the following parameter stores:
- Amazon Web Services Systems Manager Parameter Store
- Amazon Web Services Secrets Manager
-
Amazon Web Services AppConfig -
Amazon DynamoDB - Custom parameter store providers
The Parameters utility is part of the
For more details, see the
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 Amazon Web Services SDK client for the parameter store you are planning to use. The Parameters utility supports
Next, assign appropriate
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 Amazon Web Services 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
{
"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
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
Working with encrypted parameters in SSM Parameter Store
SSM Parameter Store supports encrypted secure string parameters via 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 Amazon Web Services 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
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 Amazon Web Services 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 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
Conclusion
This blog post introduces the Powertools for Amazon Web Services 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
Share your feedback for Powertools for Amazon Web Services Lambda (TypeScript) by opening a
For more serverless learning resources, visit