The Parameters utility provides high-level functions to retrieve one or multiple parameter values from AWS Systems Manager Parameter Store, AWS Secrets Manager, AWS AppConfig, Amazon DynamoDB, or your own parameter store.
Key features¶The Parameters Utility helps to retrieve parameters from the System Manager Parameter Store (SSM), secrets from the Secrets Manager, and application configuration from AppConfig. Additionally, the utility also offers support for a DynamoDB provider, enabling the retrieval of arbitrary parameters from specified tables.
Installation¶ NoteThis utility supports AWS SDK for JavaScript v3 only. This allows the utility to be modular, and you to install only the SDK packages you need and keep your bundle size small.
Depending on the provider you want to use, install the library and the corresponding AWS SDK package:
SSMProviderSecretsProviderAppConfigProviderDynamoDBProvider
npm install @aws-lambda-powertools/parameters @aws-sdk/client-ssm
npm install @aws-lambda-powertools/parameters @aws-sdk/client-secrets-manager
npm install @aws-lambda-powertools/parameters @aws-sdk/client-appconfigdata
npm install @aws-lambda-powertools/parameters @aws-sdk/client-dynamodb @aws-sdk/util-dynamodb
Tip
If you are using the nodejs18.x
runtime or newer, the AWS SDK for JavaScript v3 is already installed and you can install the utility only.
This utility requires additional permissions to work as expected.
NoteDifferent parameter providers require different permissions.
Provider Function/Method IAM Permission SSMgetParameter
, SSMProvider.get
ssm:GetParameter
SSM getParameters
, SSMProvider.getMultiple
ssm:GetParametersByPath
SSM getParametersByName
, SSMProvider.getParametersByName
ssm:GetParameter
and ssm:GetParameters
SSM If using decrypt: true
You must add an additional permission kms:Decrypt
SSM setParameter
, SSMProvider.set
ssm:PutParameter
Secrets getSecret
, SecretsProvider.get
secretsmanager:GetSecretValue
DynamoDB DynamoDBProvider.get
dynamodb:GetItem
DynamoDB DynamoDBProvider.getMultiple
dynamodb:Query
AppConfig getAppConfig
, AppConfigProvider.getAppConfig
appconfig:GetLatestConfiguration
and appconfig:StartConfigurationSession
Fetching parameters¶
You can retrieve a single parameter using the getParameter
high-level function.
1 2 3 4 5 6 7
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);
};
For multiple parameters, you can use either:
getParameters
to recursively fetch all parameters by path.getParametersByName
to fetch distinct parameters by their full name. It also accepts custom caching, transform, decrypt per parameter.getParametersgetParametersByName
Fetching multiple parameters by path from SSM1 2 3 4 5 6 7 8 9 10 11 12
import { getParameters } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
/**
* Retrieve multiple parameters from a path prefix recursively.
* This returns an object with the parameter name as key
*/
const parameters = await getParameters('/my/path/prefix');
for (const [key, value] of Object.entries(parameters || {})) {
console.log(`${key}: ${value}`);
}
};
Fetching multiple parameters by names from SSM
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
import { Transform } from '@aws-lambda-powertools/parameters';
import { getParametersByName } from '@aws-lambda-powertools/parameters/ssm';
import type { SSMGetParametersByNameOptions } from '@aws-lambda-powertools/parameters/ssm/types';
const props: Record<string, SSMGetParametersByNameOptions> = {
'/develop/service/commons/telemetry/config': {
maxAge: 300,
transform: 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, { maxAge: 60 });
for (const [key, value] of Object.entries(parameters)) {
console.log(`${key}: ${value}`);
}
};
getParametersByName
supports graceful error handling
By default, the provider will throw a GetParameterError
when any parameter fails to be fetched. You can override it by setting throwOnError: false
.
When disabled, instead the provider will take the following actions:
_errors
key, e.g., { _errors: [ '/param1', '/param2' ] }
GetParameterError
if any of your parameters is named _errors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import { getParametersByName } from '@aws-lambda-powertools/parameters/ssm';
import type { SSMGetParametersByNameOptions } from '@aws-lambda-powertools/parameters/ssm/types';
const props: Record<string, SSMGetParametersByNameOptions> = {
'/develop/service/commons/telemetry/config': {
maxAge: 300,
transform: 'json',
},
'/this/param/does/not/exist': {}, // <- Example of non-existent parameter
};
export const handler = async (): Promise<void> => {
const { _errors: errors, ...parameters } = await getParametersByName(props, {
throwOnError: false,
});
// Handle gracefully, since `/this/param/does/not/exist` will only be available in `_errors`
if (errors?.length) {
console.error(`Unable to retrieve parameters: ${errors.join(',')}`);
}
for (const [key, value] of Object.entries(parameters)) {
console.log(`${key}: ${value}`);
}
};
Storing parameters¶
You can store parameters in the System Manager Parameter Store using setParameter
.
1 2 3 4 5 6 7
import { setParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
// Store a string parameter
const parameter = await setParameter('/my/parameter', { value: 'my-value' });
console.log(parameter);
};
If the parameter is already existent, it needs to have the overwrite
parameter set to true
to update the value.
1 2 3 4 5 6 7 8 9 10
import { setParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
// Overwrite a string parameter
const parameter = await setParameter('/my/parameter', {
value: 'my-value',
overwrite: true,
});
console.log(parameter);
};
Fetching secrets¶
You can fetch secrets stored in Secrets Manager using getSecret
.
1 2 3 4 5 6 7
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);
};
Fetching app configurations¶
You can fetch application configurations in AWS AppConfig using getAppConfig
.
The following will retrieve the latest version and store it in the cache.
Fetching latest config from AppConfig1 2 3 4 5 6 7 8 9 10
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);
};
When using getAppConfig
, the underlying provider is cached. To fetch from different applications or environments, create separate AppConfigProvider
instances for each application/environment combination.
By default, the provider will cache parameters retrieved in-memory for 5 seconds.
You can adjust how long values should be kept in cache by using the param maxAge
, when using get()
or getMultiple()
methods across all providers.
If you want to set the same TTL for all parameters, you can set the POWERTOOLS_PARAMETERS_MAX_AGE
environment variable. This will override the default TTL of 5 seconds but can be overridden by the maxAge
parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import { SSMProvider } from '@aws-lambda-powertools/parameters/ssm';
const parametersProvider = new SSMProvider();
export const handler = async (): Promise<void> => {
// Retrieve a single parameter and cache it for 1 minute
const parameter = await parametersProvider.get('/my/parameter', {
maxAge: 60,
}); // (1)
console.log(parameter);
// Retrieve multiple parameters from a path prefix and cache them for 2 minutes
const parameters = await parametersProvider.getMultiple('/my/path/prefix', {
maxAge: 120,
});
for (const [key, value] of Object.entries(parameters || {})) {
console.log(`${key}: ${value}`);
}
};
get()
, getMultiple()
, and getParametersByName()
will override the values set in POWERTOOLS_PARAMETERS_MAX_AGE
environment variable.The maxAge
parameter is also available in high level functions like getParameter
, getSecret
, etc.
If you'd like to always ensure you fetch the latest parameter from the store regardless if already available in cache, use the forceFetch
parameter.
1 2 3 4 5 6 7
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
// Retrieve a single parameter
const parameter = await getParameter('/my/parameter', { forceFetch: true });
console.log(parameter);
};
Built-in provider class¶
For greater flexibility such as configuring the underlying SDK client used by built-in providers, you can use their respective Provider Classes directly.
TipThis can be used to retrieve values from other regions, change the retry behavior, etc.
SSMProvider¶ Example with SSMProvider for further extensibility1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import { SSMProvider } from '@aws-lambda-powertools/parameters/ssm';
import type { SSMClientConfig } from '@aws-sdk/client-ssm';
const clientConfig: SSMClientConfig = { region: 'us-east-1' };
const parametersProvider = new SSMProvider({ clientConfig });
export const handler = async (): Promise<void> => {
// Retrieve a single parameter
const parameter = await parametersProvider.get('/my/parameter');
console.log(parameter);
// Retrieve multiple parameters from a path prefix
const parameters = await parametersProvider.getMultiple('/my/path/prefix');
for (const [key, value] of Object.entries(parameters || {})) {
console.log(`${key}: ${value}`);
}
};
The AWS Systems Manager Parameter Store provider supports two additional arguments for the get()
and getMultiple()
methods:
false
Will automatically decrypt the parameter (see required IAM Permissions). recursive true
For getMultiple()
only, will fetch all parameter values recursively based on a path prefix. Tip
If you want to always decrypt parameters, you can set the POWERTOOLS_PARAMETERS_SSM_DECRYPT=true
environment variable. This will override the default value of false
but can be overridden by the decrypt
parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import { SSMProvider } from '@aws-lambda-powertools/parameters/ssm';
const parametersProvider = new SSMProvider();
export const handler = async (): Promise<void> => {
const decryptedValue = await parametersProvider.get(
'/my/encrypted/parameter',
{ decrypt: true }
); // (1)
console.log(decryptedValue);
const noRecursiveValues = await parametersProvider.getMultiple(
'/my/path/prefix',
{ recursive: false }
);
for (const [key, value] of Object.entries(noRecursiveValues || {})) {
console.log(`${key}: ${value}`);
}
};
get()
, getMultiple()
, and getParametersByName()
will override the values set in POWERTOOLS_PARAMETERS_SSM_DECRYPT
environment variable.1 2 3 4 5 6 7 8 9 10 11
import { SecretsProvider } from '@aws-lambda-powertools/parameters/secrets';
import type { SecretsManagerClientConfig } from '@aws-sdk/client-secrets-manager';
const clientConfig: SecretsManagerClientConfig = { region: 'us-east-1' };
const secretsProvider = new SecretsProvider({ clientConfig });
export const handler = async (): Promise<void> => {
// Retrieve a single secret
const secret = await secretsProvider.get('my-secret');
console.log(secret);
};
AppConfigProvider¶
The AWS AppConfig provider requires two arguments when initialized:
Parameter Mandatory in constructor Alternative Description application NoPOWERTOOLS_SERVICE_NAME
env variable The application in which your config resides. environment Yes (N/A) The environment that corresponds to your current config. Example with AppConfigProvider for further extensibility
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import { AppConfigProvider } from '@aws-lambda-powertools/parameters/appconfig';
import type { AppConfigDataClientConfig } from '@aws-sdk/client-appconfigdata';
const clientConfig: AppConfigDataClientConfig = { region: 'us-east-1' };
const configsProvider = new AppConfigProvider({
application: 'my-app',
environment: 'my-env',
clientConfig,
});
export const handler = async (): Promise<void> => {
// Retrieve a config
const config = await configsProvider.get('my-config');
console.log(config);
};
DynamoDBProvider¶
The DynamoDB Provider does not have any high-level functions and needs to know the name of the DynamoDB table containing the parameters.
DynamoDB table structure for single parameters
For single parameters, you must use id
as the partition key for that table.
DynamoDB table with id
partition key and value
as attribute
With this table, await dynamoDBProvider.get('my-param')
will return my-value
.
handler.tsDynamoDB Local example
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);
};
You can initialize the DynamoDB provider pointing to DynamoDB Local using the endpoint
field in the clientConfig
parameter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import { DynamoDBProvider } from '@aws-lambda-powertools/parameters/dynamodb';
const dynamoDBProvider = new DynamoDBProvider({
tableName: 'my-table',
clientConfig: {
endpoint: 'http://localhost:8000',
},
});
export const handler = async (): Promise<void> => {
// Retrieve a value from DynamoDB
const value = await dynamoDBProvider.get('my-parameter');
console.log(value);
};
DynamoDB table structure for multiple values parameters
You can retrieve multiple parameters sharing the same id
by having a sort key named sk
.
DynamoDB table with id
primary key, sk
as sort key and value
as attribute
With this table, await dynamoDBProvider.getMultiple('my-hash-key')
will return a dictionary response in the shape of sk:value
.
handler.tsvalues response object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import { DynamoDBProvider } from '@aws-lambda-powertools/parameters/dynamodb';
const dynamoDBProvider = new DynamoDBProvider({ tableName: 'my-table' });
export const handler = async (): Promise<void> => {
/**
* Retrieve multiple values by performing a Query on the DynamoDB table.
* This returns a dict with the sort key attribute as dict key.
*/
const values = await dynamoDBProvider.getMultiple('my-hash-key');
for (const [key, value] of Object.entries(values || {})) {
// key: param-a
// value: my-value-a
console.log(`${key}: ${value}`);
}
};
{
"param-a": "my-value-a",
"param-b": "my-value-b",
"param-c": "my-value-c"
}
Customizing DynamoDBProvider
DynamoDB provider can be customized at initialization to match your table structure:
Parameter Mandatory Default Description tableName Yes (N/A) Name of the DynamoDB table containing the parameter values. keyAttr Noid
Hash key for the DynamoDB table. sortAttr No sk
Range key for the DynamoDB table. You don't need to set this if you don't use the getMultiple()
method. valueAttr No value
Name of the attribute containing the parameter value. Customizing DynamoDBProvider to suit your table design
1 2 3 4 5 6 7 8 9 10 11 12 13
import { DynamoDBProvider } from '@aws-lambda-powertools/parameters/dynamodb';
const dynamoDBProvider = new DynamoDBProvider({
tableName: 'my-table',
keyAttr: 'key',
sortAttr: 'sort',
valueAttr: 'val',
});
export const handler = async (): Promise<void> => {
const value = await dynamoDBProvider.get('my-parameter');
console.log(value);
};
Create your own provider¶
You can create your own custom parameter store provider by extending the BaseProvider
class, and implementing the get()
and getMultiple()
methods, as well as its respective _get()
and _getMultiple()
private methods to retrieve a single, or multiple parameters from your custom store.
All caching logic is handled by the BaseProvider
, and provided that the return types of your store are compatible with the ones used in the BaseProvider
, all transformations will also work as expected.
Here's an example of implementing a custom parameter store using an external service like HashiCorp Vault, a widely popular key-value secret storage.
Provider usageProvider implementationProvider types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import { Logger } from '@aws-lambda-powertools/logger';
import { HashiCorpVaultProvider } from './customProviderVault.js';
const logger = new Logger({ serviceName: 'serverless-airline' });
const secretsProvider = new HashiCorpVaultProvider({
url: 'https://vault.example.com:8200/v1',
token: process.env.ROOT_TOKEN ?? '',
rootPath: 'kv',
});
// Retrieve a secret from HashiCorp Vault
const secret = await secretsProvider.get<{ foo: 'string' }>('my-secret');
const res = await fetch('https://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${secret?.foo}`,
},
body: JSON.stringify({ data: 'example' }),
});
logger.debug('res status', { status: res.status });
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
import { BaseProvider } from '@aws-lambda-powertools/parameters/base';
import { GetParameterError } from '@aws-lambda-powertools/parameters/errors';
import type {
HashiCorpVaultGetOptions,
HashiCorpVaultProviderOptions,
} from './customProviderVaultTypes.js';
class HashiCorpVaultProvider extends BaseProvider {
readonly #baseUrl: string;
readonly #token: string;
readonly #rootPath?: string;
readonly #timeout: number;
readonly #abortController: AbortController;
/**
* It initializes the HashiCorpVaultProvider class.
*
* @param config - The configuration object.
*/
public constructor(config: HashiCorpVaultProviderOptions) {
super({});
const { url, token, rootPath, timeout } = config;
this.#baseUrl = url;
this.#rootPath = rootPath ?? 'secret';
this.#timeout = timeout ?? 5000;
this.#token = token;
this.#abortController = new AbortController();
}
/**
* Retrieve a secret from HashiCorp Vault.
*
* You can customize the retrieval of the secret by passing options to the function:
* * `maxAge` - The maximum age of the value in cache before fetching a new one (in seconds) (default: 5)
* * `forceFetch` - Whether to always fetch a new value from the store regardless if already available in cache
* * `sdkOptions` - Extra options to pass to the HashiCorp Vault SDK, e.g. `mount` or `version`
*
* @param name - The name of the secret
* @param options - Options to customize the retrieval of the secret
*/
public async get<T extends Record<string, unknown>>(
name: string,
options?: HashiCorpVaultGetOptions
): Promise<T | undefined> {
return super.get(name, options) as Promise<
Record<string, unknown> | undefined
> as Promise<T | undefined>;
}
/**
* Retrieving multiple parameter values is not supported with HashiCorp Vault.
*/
public async getMultiple(path: string, _options?: unknown): Promise<void> {
await super.getMultiple(path);
}
/**
* Retrieve a secret from HashiCorp Vault.
*
* @param name - The name of the secret
* @param options - Options to customize the retrieval of the secret
*/
protected async _get(
name: string,
options?: HashiCorpVaultGetOptions
): Promise<Record<string, unknown>> {
const { sdkOptions } = options ?? {};
const mount = sdkOptions?.mount ?? this.#rootPath;
const version = sdkOptions?.version
? `?version=${sdkOptions?.version}`
: '';
setTimeout(() => {
this.#abortController.abort();
}, this.#timeout);
const res = await fetch(
`${this.#baseUrl}/${mount}/data/${name}${version}`,
{
headers: { 'X-Vault-Token': this.#token },
method: 'GET',
signal: this.#abortController.signal,
}
);
if (!res.ok) {
throw new GetParameterError(`Failed to fetch secret ${res.statusText}`);
}
const response = await res.json();
return response.data.data;
}
/**
* Retrieving multiple parameter values from HashiCorp Vault is not supported.
*
* @throws Not Implemented Error.
*/
protected async _getMultiple(
_path: string,
_options?: unknown
): Promise<Record<string, unknown> | undefined> {
throw new GetParameterError('Method not implemented.');
}
}
export { HashiCorpVaultProvider };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
import type { GetOptionsInterface } from '@aws-lambda-powertools/parameters/base/types';
/**
* Options for the HashiCorpVaultProvider class constructor.
*
* @param {string} url - Indicate the server name/IP, port and API version for the Vault instance, all paths are relative to this one.
* @param {string} token - The Vault token to use for authentication.
*
*/
interface HashiCorpVaultProviderOptions {
/**
* Indicate the server name/IP, port and API version for the Vault instance, all paths are relative to this one.
* @example 'https://vault.example.com:8200/v1'
*/
url: string;
/**
* The Vault token to use for authentication.
*/
token: string;
/**
* The root path to use for the secret engine. Defaults to `secret`.
*/
rootPath?: string;
/**
* The timeout in milliseconds for the HTTP requests. Defaults to `5000`.
* @example 10000
* @default 5000
*/
timeout?: number;
}
type HashiCorpVaultReadKVSecretOptions = {
/**
* The mount point of the secret engine to use. Defaults to `secret`.
* @example 'kv'
*/
mount?: string;
/**
* The version of the secret to retrieve. Defaults to `undefined`.
* @example 1
*/
version?: number;
};
interface HashiCorpVaultGetOptions extends GetOptionsInterface {
/**
* The Parameters utility does not support transforming `Record<string, unknown>` values as returned by the HashiCorp Vault SDK.
*/
transform?: never;
sdkOptions?: HashiCorpVaultReadKVSecretOptions;
}
export type { HashiCorpVaultProviderOptions, HashiCorpVaultGetOptions };
Deserializing values with transform parameter¶
For parameters stored in JSON or Base64 format, you can use the transform
argument for deserialization.
The transform
argument is available across all providers, including the high level functions.
High level functionsProviders
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (): Promise<void> => {
const valueFromJson = await getParameter('/my/json/parameter', {
transform: 'json',
});
console.log(valueFromJson);
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import { SecretsProvider } from '@aws-lambda-powertools/parameters/secrets';
const secretsProvider = new SecretsProvider();
export const handler = async (): Promise<void> => {
// Transform a JSON string
const json = await secretsProvider.get('my-secret-json', {
transform: 'json',
});
console.log(json);
// Transform a Base64 encoded string (e.g. binary)
const binary = await secretsProvider.getMultiple('my-secret-binary', {
transform: 'binary',
});
console.log(binary);
};
Partial transform failures with getMultiple()
¶
If you use transform
with getMultiple()
, you can have a single malformed parameter value. To prevent failing the entire request, the method will return an undefined
value for the parameters that failed to transform.
You can override this by setting the throwOnTransformError
argument to true
. If you do so, a single transform error will throw a TransformParameterError
error.
For example, if you have three parameters, /param/a, /param/b and /param/c, but /param/c is malformed:
Throwing TransformParameterError at first malformed parameter1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
import { SSMProvider } from '@aws-lambda-powertools/parameters/ssm';
const parametersProvider = new SSMProvider();
export const handler = async (): Promise<void> => {
/**
* This will display:
* /param/a: [some value]
* /param/b: [some value]
* /param/c: undefined
*/
const parameters = await parametersProvider.getMultiple('/param', {
transform: 'json',
});
for (const [key, value] of Object.entries(parameters || {})) {
console.log(`${key}: ${value}`);
}
try {
// This will throw a TransformParameterError
const parameters2 = await parametersProvider.getMultiple('/param', {
transform: 'json',
throwOnTransformError: true,
});
for (const [key, value] of Object.entries(parameters2 || {})) {
console.log(`${key}: ${value}`);
}
} catch (err) {
console.error(err);
}
};
Auto-transform values on suffix¶
If you use transform
with getMultiple()
, you might want to retrieve and transform parameters encoded in different formats.
You can do this with a single request by using transform: 'auto'
. This will instruct any provider to infer its type based on the suffix and transform it accordingly.
transform: 'auto'
feature is available across all providers, including the high level functions.
1 2 3 4 5 6 7 8 9 10 11 12
import { SSMProvider } from '@aws-lambda-powertools/parameters/ssm';
const parametersProvider = new SSMProvider();
export const handler = async (): Promise<void> => {
const values = await parametersProvider.getMultiple('/param', {
transform: 'auto',
});
for (const [key, value] of Object.entries(values || {})) {
console.log(`${key}: ${value}`);
}
};
For example, if you have three parameters: two with the following suffixes .json
and .binary
and one without any suffix:
The return of await parametersProvider.getMultiple('/param', transform: 'auto');
call will be an object like:
{
"a": [some encoded value],
"a.json": [some decoded value],
"b.binary": [some decoded value]
}
The two parameters with a suffix will be decoded, while the one without a suffix will be returned as is.
Passing additional SDK arguments¶You can use a special sdkOptions
object argument to pass any supported option directly to the underlying SDK method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import { SecretsProvider } from '@aws-lambda-powertools/parameters/secrets';
import type { GetSecretValueCommandInput } from '@aws-sdk/client-secrets-manager';
const secretsProvider = new SecretsProvider();
export const handler = async (): Promise<void> => {
const sdkOptions: Partial<GetSecretValueCommandInput> = {
VersionId: 'e62ec170-6b01-48c7-94f3-d7497851a8d2',
};
/**
* The 'VersionId' argument will be passed to the underlying
* `GetSecretValueCommand` call.
*/
const secret = await secretsProvider.get('my-secret', { sdkOptions });
console.log(secret);
};
Here is the mapping between this utility's functions and methods and the underlying SDK:
Bring your own AWS SDK v3 client¶You can use the awsSdkV3Client
parameter via any of the available Provider Classes.
Injecting a custom AWS SDK v3 client allows you to apply tracing or make unit/snapshot testing easier, including SDK customizations.
SSMProviderSecretsProviderAppConfigProviderDynamoDBProvider
1 2 3 4 5 6 7 8 9 10 11 12 13
import { SSMProvider } from '@aws-lambda-powertools/parameters/ssm';
import { SSMClient } from '@aws-sdk/client-ssm';
// construct your clients with any custom configuration
const ssmClient = new SSMClient({ region: 'us-east-1' });
// pass the client to the provider
const parametersProvider = new SSMProvider({ awsSdkV3Client: ssmClient });
export const handler = async (): Promise<void> => {
// Retrieve a single parameter
const parameter = await parametersProvider.get('/my/parameter');
console.log(parameter);
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import { SecretsProvider } from '@aws-lambda-powertools/parameters/secrets';
import { SecretsManagerClient } from '@aws-sdk/client-secrets-manager';
// construct your clients with any custom configuration
const secretsManagerClient = new SecretsManagerClient({ region: 'us-east-1' });
// pass the client to the provider
const secretsProvider = new SecretsProvider({
awsSdkV3Client: secretsManagerClient,
});
export const handler = async (): Promise<void> => {
// Retrieve a single secret
const secret = await secretsProvider.get('my-secret');
console.log(secret);
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import { AppConfigProvider } from '@aws-lambda-powertools/parameters/appconfig';
import { AppConfigDataClient } from '@aws-sdk/client-appconfigdata';
// construct your clients with any custom configuration
const appConfigClient = new AppConfigDataClient({ region: 'us-east-1' });
// pass the client to the provider
const configsProvider = new AppConfigProvider({
application: 'my-app',
environment: 'my-env',
awsSdkV3Client: appConfigClient,
});
export const handler = async (): Promise<void> => {
const config = await configsProvider.get('my-config');
console.log(config);
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import { DynamoDBProvider } from '@aws-lambda-powertools/parameters/dynamodb';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
// construct your clients with any custom configuration
const dynamoDBClient = new DynamoDBClient({ region: 'us-east-1' });
// pass the client to the provider
const valuesProvider = new DynamoDBProvider({
tableName: 'my-table',
awsSdkV3Client: dynamoDBClient,
});
export const handler = async (): Promise<void> => {
// Retrieve a single value
const value = await valuesProvider.get('my-value');
console.log(value);
};
Customizing AWS SDK v3 configuration¶
The clientConfig
parameter enables you to pass in a custom config object when constructing any of the built-in provider classes.
You can use a custom session for retrieving parameters cross-account/region and for snapshot testing.
When using VPC private endpoints, you can pass a custom client altogether. It's also useful for testing when injecting fake instances.
import { SSMProvider } from '@aws-lambda-powertools/parameters/ssm';
import type { SSMClientConfig } from '@aws-sdk/client-ssm';
const clientConfig: SSMClientConfig = { region: 'us-east-1' };
const parametersProvider = new SSMProvider({ clientConfig });
export const handler = async (): Promise<void> => {
// Retrieve a single parameter
const value = await parametersProvider.get('/my/parameter');
console.log(value);
};
Testing your code¶ Mocking parameter values¶
For unit testing your applications, you can mock the calls to the parameters utility to avoid calling AWS APIs. This can be achieved in a number of ways - in this example, we mock the module import to patch the getParameters
function.
handler.test.tshandler.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import { afterEach, describe, expect, it, vi } from 'vitest';
import { handler } from './testingYourCodeFunctionsHandler.js';
const mocks = vi.hoisted(() => ({
getParameter: vi.fn(),
}));
vi.mock('@aws-lambda-powertools/parameters/ssm', async (importOriginal) => ({
...(await importOriginal<
typeof import('@aws-lambda-powertools/parameters/ssm')
>()),
getParameter: mocks.getParameter,
}));
describe('Function tests', () => {
afterEach(() => {
vi.clearAllMocks();
});
it('returns the correct response', async () => {
// Prepare
mocks.getParameter.mockResolvedValueOnce('my/param');
// Act
const result = await handler({}, {});
// Assess
expect(result).toEqual({
value: 'my/param',
});
});
});
1 2 3 4 5 6 7 8 9 10 11 12
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
export const handler = async (
_event: unknown,
_context: unknown
): Promise<Record<string, unknown>> => {
const parameter = await getParameter('my/param');
return {
value: parameter,
};
};
With this pattern in place, you can customize the return values of the mocked function to test different scenarios without calling AWS APIs.
A similar pattern can be applied also to any of the built-in provider classes - in this other example, we use spies to patch the get
function of the AppConfigProvider
class. This is useful also when you want to test that the correct arguments are being passed to the Parameters utility.
handler.test.tshandler.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import { AppConfigProvider } from '@aws-lambda-powertools/parameters/appconfig';
import { Uint8ArrayBlobAdapter } from '@smithy/util-stream';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { handler } from './testingYourCodeFunctionsHandler.js';
describe('Function tests', () => {
const providerSpy = vi.spyOn(AppConfigProvider.prototype, 'get');
afterEach(() => {
vi.clearAllMocks();
});
it('retrieves the config once and uses the correct name', async () => {
// Prepare
const expectedConfig = {
feature: {
enabled: true,
name: 'paywall',
},
};
providerSpy.mockResolvedValueOnce(
Uint8ArrayBlobAdapter.fromString(JSON.stringify(expectedConfig))
);
// Act
const result = await handler({}, {});
// Assess
expect(result).toStrictEqual({ value: expectedConfig });
expect(providerSpy).toHaveBeenCalledTimes(1);
expect(providerSpy).toHaveBeenCalledWith('my-config');
});
});
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import { AppConfigProvider } from '@aws-lambda-powertools/parameters/appconfig';
const provider = new AppConfigProvider({
environment: 'dev',
application: 'my-app',
});
export const handler = async (
_event: unknown,
_context: unknown
): Promise<Record<string, unknown>> => {
const config = await provider.get('my-config');
return {
value: config,
};
};
For when you want to mock the AWS SDK v3 client directly, we recommend using the aws-sdk-client-mock
and aws-sdk-client-mock-vitest
libraries. This is useful when you want to test how your code behaves when the AWS SDK v3 client throws an error or a specific response.
handler.test.tshandler.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
import {
GetSecretValueCommand,
ResourceNotFoundException,
SecretsManagerClient,
} from '@aws-sdk/client-secrets-manager';
import { mockClient } from 'aws-sdk-client-mock';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { handler } from './testingYourCodeFunctionsHandler.js';
import 'aws-sdk-client-mock-vitest';
describe('Function tests', () => {
const client = mockClient(SecretsManagerClient);
afterEach(() => {
vi.clearAllMocks();
client.reset();
});
it('returns the correct error message', async () => {
// Prepare
client.on(GetSecretValueCommand).rejectsOnce(
new ResourceNotFoundException({
$metadata: {
httpStatusCode: 404,
},
message: 'Unable to retrieve secret',
})
);
// Act
const result = await handler({}, {});
// Assess
expect(result).toStrictEqual({ message: 'Unable to retrieve secret' });
});
});
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import { getSecret } from '@aws-lambda-powertools/parameters/secrets';
export const handler = async (
_event: unknown,
_context: unknown
): Promise<Record<string, unknown>> => {
try {
const parameter = await getSecret('my-secret');
return {
value: parameter,
};
} catch (error) {
console.error('Unable to retrieve secret: ', error);
return {
message: 'Unable to retrieve secret',
};
}
};
Clearing cache¶
Parameters utility caches all parameter values for performance and cost reasons. However, this can have unintended interference in tests using the same parameter name.
Within your tests, you can use clearCache
method available in every provider. When using multiple providers or higher level functions like getParameter
, use the clearCaches
standalone function to clear cache globally.
handler.test.ts
import { clearCaches } from '@aws-lambda-powertools/parameters';
import { afterEach, describe } from 'vitest';
describe('Function tests', () => {
afterEach(() => {
clearCaches();
});
// ...
});
2025-08-14
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4