Skip to content

SSM

AWS SSM Parameter retrieval and caching utility

CLASS DESCRIPTION
SSMProvider

AWS Systems Manager Parameter Store Provider

FUNCTION DESCRIPTION
get_parameter

Retrieve a parameter value from AWS Systems Manager (SSM) Parameter Store

get_parameters

Retrieve multiple parameter values from AWS Systems Manager (SSM) Parameter Store

get_parameters_by_name

Retrieve multiple parameter values by name from AWS Systems Manager (SSM) Parameter Store

set_parameter

Sets a parameter in AWS Systems Manager Parameter Store.

SSMProvider

SSMProvider(
    config: Config | None = None,
    boto_config: Config | None = None,
    boto3_session: boto3.session.Session | None = None,
    boto3_client: SSMClient | None = None,
)

Bases: BaseProvider

AWS Systems Manager Parameter Store Provider

PARAMETER DESCRIPTION
config

Botocore configuration to pass during client initialization

TYPE: Config | None DEFAULT: None

boto3_session
1
Boto3 session to create a boto3_client from

TYPE: Session DEFAULT: None

boto3_client
1
Boto3 SSM Client to use, boto3_session will be ignored if both are provided

TYPE: SSMClient | None DEFAULT: None

Example

Retrieves a parameter value from Systems Manager Parameter Store

1
2
3
4
5
6
7
>>> from aws_lambda_powertools.utilities.parameters import SSMProvider
>>> ssm_provider = SSMProvider()
>>>
>>> value = ssm_provider.get("/my/parameter")
>>>
>>> print(value)
My parameter value

Retrieves a parameter value from Systems Manager Parameter Store in another AWS region

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> from botocore.config import Config
>>> from aws_lambda_powertools.utilities.parameters import SSMProvider
>>>
>>> config = Config(region_name="us-west-1")
>>> ssm_provider = SSMProvider(config=config)
>>>
>>> value = ssm_provider.get("/my/parameter")
>>>
>>> print(value)
My parameter value

Retrieves multiple parameter values from Systems Manager Parameter Store using a path prefix

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> from aws_lambda_powertools.utilities.parameters import SSMProvider
>>> ssm_provider = SSMProvider()
>>>
>>> values = ssm_provider.get_multiple("/my/path/prefix")
>>>
>>> for key, value in values.items():
...     print(key, value)
/my/path/prefix/a   Parameter value a
/my/path/prefix/b   Parameter value b
/my/path/prefix/c   Parameter value c

Retrieves multiple parameter values from Systems Manager Parameter Store passing options to the SDK call

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> from aws_lambda_powertools.utilities.parameters import SSMProvider
>>> ssm_provider = SSMProvider()
>>>
>>> values = ssm_provider.get_multiple("/my/path/prefix", MaxResults=10)
>>>
>>> for key, value in values.items():
...     print(key, value)
/my/path/prefix/a   Parameter value a
/my/path/prefix/b   Parameter value b
/my/path/prefix/c   Parameter value c
METHOD DESCRIPTION
get

Retrieve a parameter value or return the cached value

get_multiple

Retrieve multiple parameters based on a path prefix

get_parameters_by_name

Retrieve multiple parameter values by name from SSM or cache.

set

Sets a parameter in AWS Systems Manager Parameter Store.

Source code in aws_lambda_powertools/utilities/parameters/ssm.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def __init__(
    self,
    config: Config | None = None,
    boto_config: Config | None = None,
    boto3_session: boto3.session.Session | None = None,
    boto3_client: SSMClient | None = None,
):
    """
    Initialize the SSM Parameter Store client
    """
    if config:
        warnings.warn(
            message="The 'config' parameter is deprecated in V3 and will be removed in V4. "
            "Please use 'boto_config' instead.",
            category=PowertoolsDeprecationWarning,
            stacklevel=2,
        )

    if boto3_client is None:
        boto3_session = boto3_session or boto3.session.Session()
        boto3_client = boto3_session.client("ssm", config=boto_config or config)
    self.client = boto3_client

    super().__init__(client=self.client)

get

get(
    name: str,
    max_age: int | None = None,
    transform: TransformOptions = None,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    **sdk_options
) -> str | bytes | dict | None

Retrieve a parameter value or return the cached value

PARAMETER DESCRIPTION
name

Parameter name

TYPE: str

max_age

Maximum age of the cached value

TYPE: int | None DEFAULT: None

transform

Optional transformation of the parameter value. Supported values are "json" for JSON strings and "binary" for base 64 encoded values.

TYPE: TransformOptions DEFAULT: None

decrypt

If the parameter value should be decrypted

TYPE: bool | None DEFAULT: None

force_fetch

Force update even before a cached item has expired, defaults to False

TYPE: bool DEFAULT: False

sdk_options

Arguments that will be passed directly to the underlying API call

DEFAULT: {}

RAISES DESCRIPTION
GetParameterError

When the parameter provider fails to retrieve a parameter value for a given name.

TransformParameterError

When the parameter provider fails to transform a parameter value.

Source code in aws_lambda_powertools/utilities/parameters/ssm.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def get(  # type: ignore[override]
    self,
    name: str,
    max_age: int | None = None,
    transform: TransformOptions = None,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    **sdk_options,
) -> str | bytes | dict | None:
    """
    Retrieve a parameter value or return the cached value

    Parameters
    ----------
    name: str
        Parameter name
    max_age: int, optional
        Maximum age of the cached value
    transform: str
        Optional transformation of the parameter value. Supported values
        are "json" for JSON strings and "binary" for base 64 encoded
        values.
    decrypt: bool, optional
        If the parameter value should be decrypted
    force_fetch: bool, optional
        Force update even before a cached item has expired, defaults to False
    sdk_options: dict, optional
        Arguments that will be passed directly to the underlying API call

    Raises
    ------
    GetParameterError
        When the parameter provider fails to retrieve a parameter value for
        a given name.
    TransformParameterError
        When the parameter provider fails to transform a parameter value.
    """

    # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS
    max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age)

    # If decrypt is not set, resolve it from the environment variable, defaulting to False
    decrypt = resolve_truthy_env_var_choice(
        env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"),
        choice=decrypt,
    )

    # Add to `decrypt` sdk_options to we can have an explicit option for this
    sdk_options["decrypt"] = decrypt

    return super().get(name, max_age, transform, force_fetch, **sdk_options)

get_multiple

get_multiple(
    path: str,
    max_age: int | None = None,
    transform: TransformOptions = None,
    raise_on_transform_error: bool = False,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    recursive: bool = False,
    **sdk_options
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]

Retrieve multiple parameters based on a path prefix

PARAMETER DESCRIPTION
path

Parameter path used to retrieve multiple parameters

TYPE: str

max_age

Maximum age of the cached value

TYPE: int | None DEFAULT: None

transform

Optional transformation of the parameter value. Supported values are "json" for JSON strings, "binary" for base 64 encoded values or "auto" which looks at the attribute key to determine the type.

TYPE: TransformOptions DEFAULT: None

raise_on_transform_error

Raises an exception if any transform fails, otherwise this will return a None value for each transform that failed

TYPE: bool DEFAULT: False

force_fetch

Force update even before a cached item has expired, defaults to False

TYPE: bool DEFAULT: False

recursive

If this should retrieve the parameter values recursively or not

TYPE: bool DEFAULT: False

sdk_options

Arguments that will be passed directly to the underlying API call

DEFAULT: {}

RAISES DESCRIPTION
GetParameterError

When the parameter provider fails to retrieve parameter values for a given path.

TransformParameterError

When the parameter provider fails to transform a parameter value.

Source code in aws_lambda_powertools/utilities/parameters/ssm.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def get_multiple(  # type: ignore[override]
    self,
    path: str,
    max_age: int | None = None,
    transform: TransformOptions = None,
    raise_on_transform_error: bool = False,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    recursive: bool = False,
    **sdk_options,
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]:
    """
    Retrieve multiple parameters based on a path prefix

    Parameters
    ----------
    path: str
        Parameter path used to retrieve multiple parameters
    max_age: int, optional
        Maximum age of the cached value
    transform: str, optional
        Optional transformation of the parameter value. Supported values
        are "json" for JSON strings, "binary" for base 64 encoded
        values or "auto" which looks at the attribute key to determine the type.
    raise_on_transform_error: bool, optional
        Raises an exception if any transform fails, otherwise this will
        return a None value for each transform that failed
    force_fetch: bool, optional
        Force update even before a cached item has expired, defaults to False
    recursive: bool, optional
        If this should retrieve the parameter values recursively or not
    sdk_options: dict, optional
        Arguments that will be passed directly to the underlying API call

    Raises
    ------
    GetParameterError
        When the parameter provider fails to retrieve parameter values for
        a given path.
    TransformParameterError
        When the parameter provider fails to transform a parameter value.
    """

    # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS
    max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age)

    # If decrypt is not set, resolve it from the environment variable, defaulting to False
    decrypt = resolve_truthy_env_var_choice(
        env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"),
        choice=decrypt,
    )

    sdk_options["decrypt"] = decrypt
    sdk_options["recursive"] = recursive

    return super().get_multiple(path, max_age, transform, raise_on_transform_error, force_fetch, **sdk_options)

get_parameters_by_name

get_parameters_by_name(
    parameters: dict[str, dict],
    transform: TransformOptions = None,
    decrypt: bool | None = None,
    max_age: int | None = None,
    raise_on_error: bool = True,
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]

Retrieve multiple parameter values by name from SSM or cache.

Raise_on_error decides on error handling strategy:

  • A) Default to fail-fast. Raises GetParameterError upon any error
  • B) Gracefully aggregate all parameters that failed under "_errors" key

It transparently uses GetParameter and/or GetParameters depending on decryption requirements.

1
2
3
4
                        ┌────────────────────────┐
                    ┌───▶  Decrypt entire batch  │─────┐
                    │   └────────────────────────┘     │     ┌────────────────────┐
                    │                                  ├─────▶ GetParameters API  │

┌──────────────────┐ │ ┌────────────────────────┐ │ └────────────────────┘ │ Split batch │─── ┼──▶│ No decryption required │─────┘ └──────────────────┘ │ └────────────────────────┘ │ ┌────────────────────┐ │ ┌────────────────────────┐ │ GetParameter API │ └──▶│Decrypt some but not all│───────────▶────────────────────┤ └────────────────────────┘ │ GetParameters API │ └────────────────────┘

PARAMETER DESCRIPTION
parameters

List of parameter names, and any optional overrides

TYPE: dict[str, dict]

transform

Transforms the content from a JSON object ('json') or base64 binary string ('binary')

TYPE: TransformOptions DEFAULT: None

decrypt

If the parameter values should be decrypted

TYPE: bool | None DEFAULT: None

max_age

Maximum age of the cached value

TYPE: int | None DEFAULT: None

raise_on_error

Whether to fail-fast or fail gracefully by including "_errors" key in the response, by default True

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
GetParameterError

When the parameter provider fails to retrieve a parameter value for a given name.

When "_errors" reserved key is in parameters to be fetched from SSM.

Source code in aws_lambda_powertools/utilities/parameters/ssm.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def get_parameters_by_name(
    self,
    parameters: dict[str, dict],
    transform: TransformOptions = None,
    decrypt: bool | None = None,
    max_age: int | None = None,
    raise_on_error: bool = True,
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]:
    """
    Retrieve multiple parameter values by name from SSM or cache.

    Raise_on_error decides on error handling strategy:

    - A) Default to fail-fast. Raises GetParameterError upon any error
    - B) Gracefully aggregate all parameters that failed under "_errors" key

    It transparently uses GetParameter and/or GetParameters depending on decryption requirements.

                                ┌────────────────────────┐
                            ┌───▶  Decrypt entire batch  │─────┐
                            │   └────────────────────────┘     │     ┌────────────────────┐
                            │                                  ├─────▶ GetParameters API  │
    ┌──────────────────┐    │   ┌────────────────────────┐     │     └────────────────────┘
    │   Split batch    │─── ┼──▶│ No decryption required │─────┘
    └──────────────────┘    │   └────────────────────────┘
                            │                                        ┌────────────────────┐
                            │   ┌────────────────────────┐           │  GetParameter API  │
                            └──▶│Decrypt some but not all│───────────▶────────────────────┤
                                └────────────────────────┘           │ GetParameters API  │
                                                                     └────────────────────┘

    Parameters
    ----------
    parameters: dict[str, dict]
        List of parameter names, and any optional overrides
    transform: str, optional
        Transforms the content from a JSON object ('json') or base64 binary string ('binary')
    decrypt: bool, optional
        If the parameter values should be decrypted
    max_age: int, optional
        Maximum age of the cached value
    raise_on_error: bool
        Whether to fail-fast or fail gracefully by including "_errors" key in the response, by default True

    Raises
    ------
    GetParameterError
        When the parameter provider fails to retrieve a parameter value for a given name.

        When "_errors" reserved key is in parameters to be fetched from SSM.
    """

    # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS
    max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age)

    # If decrypt is not set, resolve it from the environment variable, defaulting to False
    decrypt = resolve_truthy_env_var_choice(
        env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"),
        choice=decrypt,
    )

    # Init potential batch/decrypt batch responses and errors
    batch_ret: dict[str, Any] = {}
    decrypt_ret: dict[str, Any] = {}
    batch_err: list[str] = []
    decrypt_err: list[str] = []
    response: dict[str, Any] = {}

    # NOTE: We fail early to avoid unintended graceful errors being replaced with their '_errors' param values
    self._raise_if_errors_key_is_present(parameters, self._ERRORS_KEY, raise_on_error)

    batch_params, decrypt_params = self._split_batch_and_decrypt_parameters(parameters, transform, max_age, decrypt)

    # NOTE: We need to find out whether all parameters must be decrypted or not to know which API to use
    ## Logic:
    ##
    ## GetParameters API -> When decrypt is used for all parameters in the the batch
    ## GetParameter  API -> When decrypt is used for one or more in the batch

    if len(decrypt_params) != len(parameters):
        decrypt_ret, decrypt_err = self._get_parameters_by_name_with_decrypt_option(decrypt_params, raise_on_error)
        batch_ret, batch_err = self._get_parameters_batch_by_name(batch_params, raise_on_error, decrypt=False)
    else:
        batch_ret, batch_err = self._get_parameters_batch_by_name(decrypt_params, raise_on_error, decrypt=True)

    # Fail-fast disabled, let's aggregate errors under "_errors" key so they can handle gracefully
    if not raise_on_error:
        response[self._ERRORS_KEY] = [*decrypt_err, *batch_err]

    return {**response, **batch_ret, **decrypt_ret}

set

set(
    name: str,
    value: list[str],
    *,
    overwrite: bool = False,
    description: str = "",
    parameter_type: Literal["StringList"] = "StringList",
    tier: Literal[
        "Standard", "Advanced", "Intelligent-Tiering"
    ] = "Standard",
    kms_key_id: str | None = "None",
    **sdk_options
)
set(
    name: str,
    value: str,
    *,
    overwrite: bool = False,
    description: str = "",
    parameter_type: Literal[
        "SecureString"
    ] = "SecureString",
    tier: Literal[
        "Standard", "Advanced", "Intelligent-Tiering"
    ] = "Standard",
    kms_key_id: str,
    **sdk_options
)
set(
    name: str,
    value: str,
    *,
    overwrite: bool = False,
    description: str = "",
    parameter_type: Literal["String"] = "String",
    tier: Literal[
        "Standard", "Advanced", "Intelligent-Tiering"
    ] = "Standard",
    kms_key_id: str | None = None,
    **sdk_options
)
set(
    name: str,
    value: str | list[str],
    *,
    overwrite: bool = False,
    description: str = "",
    parameter_type: SSM_PARAMETER_TYPES = "String",
    tier: SSM_PARAMETER_TIER = "Standard",
    kms_key_id: str | None = None,
    **sdk_options
) -> PutParameterResultTypeDef

Sets a parameter in AWS Systems Manager Parameter Store.

PARAMETER DESCRIPTION
name

The fully qualified name includes the complete hierarchy of the parameter name and name.

TYPE: str

value

The parameter value

TYPE: str | list[str]

overwrite

If the parameter value should be overwritten, False by default

TYPE: bool DEFAULT: False

description

The description of the parameter

TYPE: str DEFAULT: ''

parameter_type

Type of the parameter. Allowed values are String, StringList, and SecureString

TYPE: SSM_PARAMETER_TYPES DEFAULT: 'String'

tier

The parameter tier to use. Allowed values are Standard, Advanced, and Intelligent-Tiering

TYPE: SSM_PARAMETER_TIER DEFAULT: 'Standard'

kms_key_id

The KMS key id to use to encrypt the parameter

TYPE: str | None DEFAULT: None

sdk_options

Dictionary of options that will be passed to the Parameter Store get_parameter API call

DEFAULT: {}

RAISES DESCRIPTION
SetParameterError

When the parameter provider fails to retrieve a parameter value for a given name.

1
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm/client/put_parameter.html
Example

Sets a parameter value from Systems Manager Parameter Store

1
2
3
4
5
6
>>> from aws_lambda_powertools.utilities import parameters
>>>
>>> response = parameters.set_parameter(name="/my/example/parameter", value="More Powertools")
>>>
>>> print(response)
123
RETURNS DESCRIPTION
PutParameterResultTypeDef

The dict returned by boto3.

Source code in aws_lambda_powertools/utilities/parameters/ssm.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def set(
    self,
    name: str,
    value: str | list[str],
    *,
    overwrite: bool = False,
    description: str = "",
    parameter_type: SSM_PARAMETER_TYPES = "String",
    tier: SSM_PARAMETER_TIER = "Standard",
    kms_key_id: str | None = None,
    **sdk_options,
) -> PutParameterResultTypeDef:
    """
    Sets a parameter in AWS Systems Manager Parameter Store.

    Parameters
    ----------
    name: str
        The fully qualified name includes the complete hierarchy of the parameter name and name.
    value: str
        The parameter value
    overwrite: bool, optional
        If the parameter value should be overwritten, False by default
    description: str, optional
        The description of the parameter
    parameter_type: str, optional
        Type of the parameter.  Allowed values are String, StringList, and SecureString
    tier: str, optional
        The parameter tier to use. Allowed values are Standard, Advanced, and Intelligent-Tiering
    kms_key_id: str, optional
        The KMS key id to use to encrypt the parameter
    sdk_options: dict, optional
        Dictionary of options that will be passed to the Parameter Store get_parameter API call

    Raises
    ------
    SetParameterError
        When the parameter provider fails to retrieve a parameter value for
        a given name.

    URLs:
    -------
        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm/client/put_parameter.html

    Example
    -------
    **Sets a parameter value from Systems Manager Parameter Store**

        >>> from aws_lambda_powertools.utilities import parameters
        >>>
        >>> response = parameters.set_parameter(name="/my/example/parameter", value="More Powertools")
        >>>
        >>> print(response)
        123

    Returns
    -------
    PutParameterResultTypeDef
        The dict returned by boto3.
    """
    opts = {
        "Name": name,
        "Value": value,
        "Overwrite": overwrite,
        "Type": parameter_type,
        "Tier": tier,
        "Description": description,
        **sdk_options,
    }

    if kms_key_id:
        opts["KeyId"] = kms_key_id

    try:
        return self.client.put_parameter(**opts)
    except Exception as exc:
        raise SetParameterError(f"Error setting parameter - {str(exc)}") from exc

get_parameter

get_parameter(
    name: str,
    transform: None = None,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    **sdk_options
) -> str
get_parameter(
    name: str,
    transform: Literal["json"],
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    **sdk_options
) -> dict
get_parameter(
    name: str,
    transform: Literal["binary"],
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    **sdk_options
) -> str | bytes | dict
get_parameter(
    name: str,
    transform: Literal["auto"],
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    **sdk_options
) -> bytes
get_parameter(
    name: str,
    transform: TransformOptions = None,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    **sdk_options
) -> str | bytes | dict

Retrieve a parameter value from AWS Systems Manager (SSM) Parameter Store

PARAMETER DESCRIPTION
name

Name of the parameter

TYPE: str

transform

Transforms the content from a JSON object ('json') or base64 binary string ('binary')

TYPE: TransformOptions DEFAULT: None

decrypt

If the parameter values should be decrypted

TYPE: bool | None DEFAULT: None

force_fetch

Force update even before a cached item has expired, defaults to False

TYPE: bool DEFAULT: False

max_age

Maximum age of the cached value

TYPE: int | None DEFAULT: None

sdk_options

Dictionary of options that will be passed to the Parameter Store get_parameter API call

DEFAULT: {}

RAISES DESCRIPTION
GetParameterError

When the parameter provider fails to retrieve a parameter value for a given name.

TransformParameterError

When the parameter provider fails to transform a parameter value.

Example

Retrieves a parameter value from Systems Manager Parameter Store

1
2
3
4
5
6
>>> from aws_lambda_powertools.utilities.parameters import get_parameter
>>>
>>> value = get_parameter("/my/parameter")
>>>
>>> print(value)
My parameter value

Retrieves a parameter value and decodes it using a Base64 decoder

1
2
3
4
5
6
>>> from aws_lambda_powertools.utilities.parameters import get_parameter
>>>
>>> value = get_parameter("/my/parameter", transform='binary')
>>>
>>> print(value)
My parameter value
Source code in aws_lambda_powertools/utilities/parameters/ssm.py
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
def get_parameter(
    name: str,
    transform: TransformOptions = None,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    **sdk_options,
) -> str | bytes | dict:
    """
    Retrieve a parameter value from AWS Systems Manager (SSM) Parameter Store

    Parameters
    ----------
    name: str
        Name of the parameter
    transform: str, optional
        Transforms the content from a JSON object ('json') or base64 binary string ('binary')
    decrypt: bool, optional
        If the parameter values should be decrypted
    force_fetch: bool, optional
        Force update even before a cached item has expired, defaults to False
    max_age: int, optional
        Maximum age of the cached value
    sdk_options: dict, optional
        Dictionary of options that will be passed to the Parameter Store get_parameter API call

    Raises
    ------
    GetParameterError
        When the parameter provider fails to retrieve a parameter value for
        a given name.
    TransformParameterError
        When the parameter provider fails to transform a parameter value.

    Example
    -------
    **Retrieves a parameter value from Systems Manager Parameter Store**

        >>> from aws_lambda_powertools.utilities.parameters import get_parameter
        >>>
        >>> value = get_parameter("/my/parameter")
        >>>
        >>> print(value)
        My parameter value

    **Retrieves a parameter value and decodes it using a Base64 decoder**

        >>> from aws_lambda_powertools.utilities.parameters import get_parameter
        >>>
        >>> value = get_parameter("/my/parameter", transform='binary')
        >>>
        >>> print(value)
        My parameter value
    """

    # Only create the provider if this function is called at least once
    if "ssm" not in DEFAULT_PROVIDERS:
        DEFAULT_PROVIDERS["ssm"] = SSMProvider()

    # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS
    max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age)

    # If decrypt is not set, resolve it from the environment variable, defaulting to False
    decrypt = resolve_truthy_env_var_choice(
        env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"),
        choice=decrypt,
    )

    return DEFAULT_PROVIDERS["ssm"].get(
        name=name,
        max_age=max_age,
        transform=transform,
        force_fetch=force_fetch,
        decrypt=decrypt,
        **sdk_options,
    )

get_parameters

get_parameters(
    path: str,
    transform: None = None,
    recursive: bool = True,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    raise_on_transform_error: bool = False,
    **sdk_options
) -> dict[str, str]
get_parameters(
    path: str,
    transform: Literal["json"],
    recursive: bool = True,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    raise_on_transform_error: bool = False,
    **sdk_options
) -> dict[str, dict]
get_parameters(
    path: str,
    transform: Literal["binary"],
    recursive: bool = True,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    raise_on_transform_error: bool = False,
    **sdk_options
) -> dict[str, bytes]
get_parameters(
    path: str,
    transform: Literal["auto"],
    recursive: bool = True,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    raise_on_transform_error: bool = False,
    **sdk_options
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]
get_parameters(
    path: str,
    transform: TransformOptions = None,
    recursive: bool = True,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    raise_on_transform_error: bool = False,
    **sdk_options
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]

Retrieve multiple parameter values from AWS Systems Manager (SSM) Parameter Store

For readability, we strip the path prefix name in the response.

PARAMETER DESCRIPTION
path

Path to retrieve the parameters

TYPE: str

transform

Transforms the content from a JSON object ('json') or base64 binary string ('binary')

TYPE: TransformOptions DEFAULT: None

recursive

If this should retrieve the parameter values recursively or not, defaults to True

TYPE: bool DEFAULT: True

decrypt

If the parameter values should be decrypted

TYPE: bool | None DEFAULT: None

force_fetch

Force update even before a cached item has expired, defaults to False

TYPE: bool DEFAULT: False

max_age

Maximum age of the cached value

TYPE: int | None DEFAULT: None

raise_on_transform_error

Raises an exception if any transform fails, otherwise this will return a None value for each transform that failed

TYPE: bool DEFAULT: False

sdk_options

Dictionary of options that will be passed to the Parameter Store get_parameters_by_path API call

DEFAULT: {}

RAISES DESCRIPTION
GetParameterError

When the parameter provider fails to retrieve parameter values for a given path.

TransformParameterError

When the parameter provider fails to transform a parameter value.

Example

Retrieves parameter values from Systems Manager Parameter Store

1
2
3
4
5
6
7
8
>>> from aws_lambda_powertools.utilities.parameters import get_parameter
>>>
>>> values = get_parameters("/my/path/prefix")
>>>
>>> for key, value in values.items():
...     print(key, value)
config              Parameter value (/my/path/prefix/config)
webhook/config      Parameter value (/my/path/prefix/webhook/config)

Retrieves parameter values and decodes them using a Base64 decoder

1
2
3
>>> from aws_lambda_powertools.utilities.parameters import get_parameter
>>>
>>> values = get_parameters("/my/path/prefix", transform='binary')
Source code in aws_lambda_powertools/utilities/parameters/ssm.py
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
def get_parameters(
    path: str,
    transform: TransformOptions = None,
    recursive: bool = True,
    decrypt: bool | None = None,
    force_fetch: bool = False,
    max_age: int | None = None,
    raise_on_transform_error: bool = False,
    **sdk_options,
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]:
    """
    Retrieve multiple parameter values from AWS Systems Manager (SSM) Parameter Store

    For readability, we strip the path prefix name in the response.

    Parameters
    ----------
    path: str
        Path to retrieve the parameters
    transform: str, optional
        Transforms the content from a JSON object ('json') or base64 binary string ('binary')
    recursive: bool, optional
        If this should retrieve the parameter values recursively or not, defaults to True
    decrypt: bool, optional
        If the parameter values should be decrypted
    force_fetch: bool, optional
        Force update even before a cached item has expired, defaults to False
    max_age: int, optional
        Maximum age of the cached value
    raise_on_transform_error: bool, optional
        Raises an exception if any transform fails, otherwise this will
        return a None value for each transform that failed
    sdk_options: dict, optional
        Dictionary of options that will be passed to the Parameter Store get_parameters_by_path API call

    Raises
    ------
    GetParameterError
        When the parameter provider fails to retrieve parameter values for
        a given path.
    TransformParameterError
        When the parameter provider fails to transform a parameter value.

    Example
    -------
    **Retrieves parameter values from Systems Manager Parameter Store**

        >>> from aws_lambda_powertools.utilities.parameters import get_parameter
        >>>
        >>> values = get_parameters("/my/path/prefix")
        >>>
        >>> for key, value in values.items():
        ...     print(key, value)
        config              Parameter value (/my/path/prefix/config)
        webhook/config      Parameter value (/my/path/prefix/webhook/config)

    **Retrieves parameter values and decodes them using a Base64 decoder**

        >>> from aws_lambda_powertools.utilities.parameters import get_parameter
        >>>
        >>> values = get_parameters("/my/path/prefix", transform='binary')
    """

    # Only create the provider if this function is called at least once
    if "ssm" not in DEFAULT_PROVIDERS:
        DEFAULT_PROVIDERS["ssm"] = SSMProvider()

    # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS
    max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age)

    # If decrypt is not set, resolve it from the environment variable, defaulting to False
    decrypt = resolve_truthy_env_var_choice(
        env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"),
        choice=decrypt,
    )

    return DEFAULT_PROVIDERS["ssm"].get_multiple(
        path=path,
        max_age=max_age,
        transform=transform,
        raise_on_transform_error=raise_on_transform_error,
        force_fetch=force_fetch,
        recursive=recursive,
        decrypt=decrypt,
        **sdk_options,
    )

get_parameters_by_name

get_parameters_by_name(
    parameters: dict[str, dict],
    transform: None = None,
    decrypt: bool | None = None,
    max_age: int | None = None,
    raise_on_error: bool = True,
) -> dict[str, str]
get_parameters_by_name(
    parameters: dict[str, dict],
    transform: Literal["binary"],
    decrypt: bool | None = None,
    max_age: int | None = None,
    raise_on_error: bool = True,
) -> dict[str, bytes]
get_parameters_by_name(
    parameters: dict[str, dict],
    transform: Literal["json"],
    decrypt: bool | None = None,
    max_age: int | None = None,
    raise_on_error: bool = True,
) -> dict[str, dict[str, Any]]
get_parameters_by_name(
    parameters: dict[str, dict],
    transform: Literal["auto"],
    decrypt: bool | None = None,
    max_age: int | None = None,
    raise_on_error: bool = True,
) -> dict[str, str] | dict[str, dict]
get_parameters_by_name(
    parameters: dict[str, Any],
    transform: TransformOptions = None,
    decrypt: bool | None = None,
    max_age: int | None = None,
    raise_on_error: bool = True,
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]

Retrieve multiple parameter values by name from AWS Systems Manager (SSM) Parameter Store

PARAMETER DESCRIPTION
parameters

List of parameter names, and any optional overrides

TYPE: dict[str, Any]

transform

Transforms the content from a JSON object ('json') or base64 binary string ('binary')

TYPE: TransformOptions DEFAULT: None

decrypt

If the parameter values should be decrypted

TYPE: bool | None DEFAULT: None

max_age

Maximum age of the cached value

TYPE: int | None DEFAULT: None

raise_on_error

Whether to fail-fast or fail gracefully by including "_errors" key in the response, by default True

TYPE: bool DEFAULT: True

Example

Retrieves multiple parameters from distinct paths from Systems Manager Parameter Store

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from aws_lambda_powertools.utilities.parameters import get_parameters_by_name

params = {
    "/param": {},
    "/json": {"transform": "json"},
    "/binary": {"transform": "binary"},
    "/no_cache": {"max_age": 0},
    "/api_key": {"decrypt": True},
}

values = get_parameters_by_name(parameters=params)
for param_name, value in values.items():
    print(f"{param_name}: {value}")

# "/param": value
# "/json": value
# "/binary": value
# "/no_cache": value
# "/api_key": value
RAISES DESCRIPTION
GetParameterError

When the parameter provider fails to retrieve a parameter value for a given name.

Source code in aws_lambda_powertools/utilities/parameters/ssm.py
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
def get_parameters_by_name(
    parameters: dict[str, Any],
    transform: TransformOptions = None,
    decrypt: bool | None = None,
    max_age: int | None = None,
    raise_on_error: bool = True,
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]:
    """
    Retrieve multiple parameter values by name from AWS Systems Manager (SSM) Parameter Store

    Parameters
    ----------
    parameters: dict[str, Any]
        List of parameter names, and any optional overrides
    transform: str, optional
        Transforms the content from a JSON object ('json') or base64 binary string ('binary')
    decrypt: bool, optional
        If the parameter values should be decrypted
    max_age: int, optional
        Maximum age of the cached value
    raise_on_error: bool, optional
        Whether to fail-fast or fail gracefully by including "_errors" key in the response, by default True

    Example
    -------

    **Retrieves multiple parameters from distinct paths from Systems Manager Parameter Store**

        from aws_lambda_powertools.utilities.parameters import get_parameters_by_name

        params = {
            "/param": {},
            "/json": {"transform": "json"},
            "/binary": {"transform": "binary"},
            "/no_cache": {"max_age": 0},
            "/api_key": {"decrypt": True},
        }

        values = get_parameters_by_name(parameters=params)
        for param_name, value in values.items():
            print(f"{param_name}: {value}")

        # "/param": value
        # "/json": value
        # "/binary": value
        # "/no_cache": value
        # "/api_key": value

    Raises
    ------
    GetParameterError
        When the parameter provider fails to retrieve a parameter value for
        a given name.
    """

    # NOTE: Decided against using multi-thread due to single-thread outperforming in 128M and 1G + timeout risk
    # see: https://github.com/aws-powertools/powertools-lambda-python/issues/1040#issuecomment-1299954613

    # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS
    max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age)

    # If decrypt is not set, resolve it from the environment variable, defaulting to False
    decrypt = resolve_truthy_env_var_choice(
        env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"),
        choice=decrypt,
    )

    # Only create the provider if this function is called at least once
    if "ssm" not in DEFAULT_PROVIDERS:
        DEFAULT_PROVIDERS["ssm"] = SSMProvider()

    return DEFAULT_PROVIDERS["ssm"].get_parameters_by_name(
        parameters=parameters,
        max_age=max_age,
        transform=transform,
        decrypt=decrypt,
        raise_on_error=raise_on_error,
    )

set_parameter

set_parameter(
    name: str,
    value: str,
    *,
    overwrite: bool = False,
    description: str = "",
    parameter_type: SSM_PARAMETER_TYPES = "String",
    tier: SSM_PARAMETER_TIER = "Standard",
    kms_key_id: str | None = None,
    **sdk_options
) -> PutParameterResultTypeDef

Sets a parameter in AWS Systems Manager Parameter Store.

PARAMETER DESCRIPTION
name

The fully qualified name includes the complete hierarchy of the parameter name and name.

TYPE: str

value

The parameter value

TYPE: str

overwrite

If the parameter value should be overwritten, False by default

TYPE: bool DEFAULT: False

description

The description of the parameter

TYPE: str DEFAULT: ''

parameter_type

Type of the parameter. Allowed values are String, StringList, and SecureString

TYPE: SSM_PARAMETER_TYPES DEFAULT: 'String'

tier

The parameter tier to use. Allowed values are Standard, Advanced, and Intelligent-Tiering

TYPE: SSM_PARAMETER_TIER DEFAULT: 'Standard'

kms_key_id

The KMS key id to use to encrypt the parameter

TYPE: str | None DEFAULT: None

sdk_options

Dictionary of options that will be passed to the Parameter Store get_parameter API call

DEFAULT: {}

RAISES DESCRIPTION
SetParameterError

When attempting to set a parameter fails.

1
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm/client/put_parameter.html
Example

Sets a parameter value from Systems Manager Parameter Store

1
2
3
4
5
6
>>> from aws_lambda_powertools.utilities import parameters
>>>
>>> response = parameters.set_parameter(name="/my/example/parameter", value="More Powertools")
>>>
>>> print(response)
123
RETURNS DESCRIPTION
PutParameterResultTypeDef

The dict returned by boto3.

Source code in aws_lambda_powertools/utilities/parameters/ssm.py
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
def set_parameter(
    name: str,
    value: str,
    *,  # force keyword arguments
    overwrite: bool = False,
    description: str = "",
    parameter_type: SSM_PARAMETER_TYPES = "String",
    tier: SSM_PARAMETER_TIER = "Standard",
    kms_key_id: str | None = None,
    **sdk_options,
) -> PutParameterResultTypeDef:
    """
    Sets a parameter in AWS Systems Manager Parameter Store.

    Parameters
    ----------
    name: str
        The fully qualified name includes the complete hierarchy of the parameter name and name.
    value: str
        The parameter value
    overwrite: bool, optional
        If the parameter value should be overwritten, False by default
    description: str, optional
        The description of the parameter
    parameter_type: str, optional
        Type of the parameter.  Allowed values are String, StringList, and SecureString
    tier: str, optional
        The parameter tier to use. Allowed values are Standard, Advanced, and Intelligent-Tiering
    kms_key_id: str, optional
        The KMS key id to use to encrypt the parameter
    sdk_options: dict, optional
        Dictionary of options that will be passed to the Parameter Store get_parameter API call

    Raises
    ------
    SetParameterError
        When attempting to set a parameter fails.

    URLs:
    -------
        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm/client/put_parameter.html

    Example
    -------
    **Sets a parameter value from Systems Manager Parameter Store**

        >>> from aws_lambda_powertools.utilities import parameters
        >>>
        >>> response = parameters.set_parameter(name="/my/example/parameter", value="More Powertools")
        >>>
        >>> print(response)
        123

    Returns
    -------
    PutParameterResultTypeDef
        The dict returned by boto3.
    """

    # Only create the provider if this function is called at least once
    if "ssm" not in DEFAULT_PROVIDERS:
        DEFAULT_PROVIDERS["ssm"] = SSMProvider()

    return DEFAULT_PROVIDERS["ssm"].set(
        name,
        value,
        parameter_type=parameter_type,
        overwrite=overwrite,
        tier=tier,
        description=description,
        kms_key_id=kms_key_id,
        **sdk_options,
    )