Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add parameter utility #96

Merged
merged 31 commits into from
Aug 21, 2020
Merged
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b6787f9
feat: add get_parameter utility
nmoutschen Jul 29, 2020
29d27b8
fix: add AWS_DEFAULT_REGION for boto3 tests
nmoutschen Jul 29, 2020
a805e74
revert "fix: add AWS_DEFAULT_REGION for boto3 tests"
nmoutschen Jul 29, 2020
37964d1
fix: fix AWS_DEFAULT_REGION for get_parameter tests
nmoutschen Jul 29, 2020
dc3a5ab
fix: fix AWS_DEFAULT_REGION for get_parameter tests
nmoutschen Jul 29, 2020
9731e0a
Merge branch 'parameter-utility' of github.com:nmoutschen/aws-lambda-…
nmoutschen Jul 30, 2020
79bff7e
chore: rename _get_from_external_store to _get
nmoutschen Jul 30, 2020
a120528
feat: add get_multiple for parameter providers
nmoutschen Jul 30, 2020
d1c57ef
tests: increase test coverage
nmoutschen Jul 30, 2020
285ac95
tests: increase test coverage (2)
nmoutschen Jul 30, 2020
4c76276
tests: increase coverage to 100%
nmoutschen Jul 30, 2020
6eb012f
fix: add get_parameters in __all__
nmoutschen Jul 30, 2020
e6416c0
chore: split parameter utilities into smaller files
nmoutschen Aug 17, 2020
de842a8
feat: use botocore.config.Config for parameter providers
nmoutschen Aug 17, 2020
3569e21
feat: make arguments explicits in parameter utilities
nmoutschen Aug 17, 2020
1278d2c
docs: add examples for parameter utilities
nmoutschen Aug 17, 2020
5fb929d
feat: add override SDK options for parameter utilities
nmoutschen Aug 17, 2020
7438766
docs: add examples for shorthands in the parameter utility
nmoutschen Aug 17, 2020
d53c373
fix: fix typo in DynamoDB parameter example
nmoutschen Aug 18, 2020
fce3268
feat: throw exception on failed transform for parameter utility
nmoutschen Aug 18, 2020
c765c90
docs: add examples on how to retrieve parameters in the parameter uti…
nmoutschen Aug 18, 2020
bec8de3
feat: use paginator for SSM parameter utility
nmoutschen Aug 18, 2020
3ddc3bd
feat: make SSM parameter provider recursive by default
nmoutschen Aug 18, 2020
5502215
feat: move sort_attr to init for DynamoDB parameter provider
nmoutschen Aug 18, 2020
c8c970f
feat: add 'raise_on_transform_error' for get_multiple parameter utility
nmoutschen Aug 19, 2020
ed45c4b
docs: add sdk_options to parameters for get and get_multiple
nmoutschen Aug 19, 2020
4ecb17b
docs: add documentation for parameters utility
nmoutschen Aug 19, 2020
616a98d
docs: add passing arguments to SDK
nmoutschen Aug 19, 2020
68f6beb
docs: restructure based on feedback
nmoutschen Aug 21, 2020
dd3053d
docs: tweaks based on feedback
nmoutschen Aug 21, 2020
7b87dfa
improv: iam permissions table
heitorlessa Aug 21, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ A suite of utilities for AWS Lambda Functions that makes tracing with AWS X-Ray,
* **[Logging](https://awslabs.github.io/aws-lambda-powertools-python/core/logger/)** - Structured logging made easier, and decorator to enrich structured logging with key Lambda context details
* **[Metrics](https://awslabs.github.io/aws-lambda-powertools-python/core/metrics/)** - Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF)
* **[Bring your own middleware](https://awslabs.github.io/aws-lambda-powertools-python/utilities/middleware_factory/)** - Decorator factory to create your own middleware to run logic before, and after each Lambda invocation
* **[Parameters utility](https://awslabs.github.io/aws-lambda-powertools-python/utilities/parameters/)** - Retrieve and cache parameter values
heitorlessa marked this conversation as resolved.
Show resolved Hide resolved

### Installation

Expand Down
3 changes: 3 additions & 0 deletions aws_lambda_powertools/utilities/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-

"""General utilities for Powertools"""
23 changes: 23 additions & 0 deletions aws_lambda_powertools/utilities/parameters/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
nmoutschen marked this conversation as resolved.
Show resolved Hide resolved

"""
Parameter retrieval and caching utility
"""

from .base import BaseProvider
heitorlessa marked this conversation as resolved.
Show resolved Hide resolved
from .dynamodb import DynamoDBProvider
from .exceptions import GetParameterError, TransformParameterError
from .secrets import SecretsProvider, get_secret
from .ssm import SSMProvider, get_parameter, get_parameters

__all__ = [
"BaseProvider",
"GetParameterError",
"DynamoDBProvider",
"SecretsProvider",
"SSMProvider",
"TransformParameterError",
"get_parameter",
"get_parameters",
"get_secret",
]
190 changes: 190 additions & 0 deletions aws_lambda_powertools/utilities/parameters/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
"""
Base for Parameter providers
"""

import base64
import json
from abc import ABC, abstractmethod
from collections import namedtuple
from datetime import datetime, timedelta
from typing import Dict, Optional, Union

from .exceptions import GetParameterError, TransformParameterError

DEFAULT_MAX_AGE_SECS = 5
ExpirableValue = namedtuple("ExpirableValue", ["value", "ttl"])
# These providers will be dynamically initialized on first use of the helper functions
DEFAULT_PROVIDERS = {}


class BaseProvider(ABC):
"""
Abstract Base Class for Parameter providers
"""

store = None

def __init__(self):
"""
Initialize the base provider
"""

self.store = {}

def get(
self, name: str, max_age: int = DEFAULT_MAX_AGE_SECS, transform: Optional[str] = None, **sdk_options
) -> Union[str, list, dict, bytes]:
"""
Retrieve a parameter value or return the cached value

Parameters
----------
name: str
Parameter name
max_age: int
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.
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 there are multiple calls to the same parameter but in a different
# transform, they will be stored multiple times. This allows us to
# optimize by transforming the data only once per retrieval, thus there
# is no need to transform cached values multiple times. However, this
# means that we need to make multiple calls to the underlying parameter
# store if we need to return it in different transforms. Since the number
# of supported transform is small and the probability that a given
# parameter will always be used in a specific transform, this should be
# an acceptable tradeoff.
key = (name, transform)

if key not in self.store or self.store[key].ttl < datetime.now():
try:
value = self._get(name, **sdk_options)
# Encapsulate all errors into a generic GetParameterError
except Exception as exc:
raise GetParameterError(str(exc))

if transform is not None:
value = transform_value(value, transform)

self.store[key] = ExpirableValue(value, datetime.now() + timedelta(seconds=max_age),)

return self.store[key].value

@abstractmethod
def _get(self, name: str, **sdk_options) -> str:
"""
Retrieve paramater value from the underlying parameter store
"""
raise NotImplementedError()

def get_multiple(
self,
path: str,
max_age: int = DEFAULT_MAX_AGE_SECS,
transform: Optional[str] = None,
raise_on_transform_error: bool = False,
**sdk_options,
) -> Union[Dict[str, str], Dict[str, dict], Dict[str, bytes]]:
"""
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 and "binary" for base 64 encoded
values.
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
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.
"""

key = (path, transform)

if key not in self.store or self.store[key].ttl < datetime.now():
try:
values = self._get_multiple(path, **sdk_options)
# Encapsulate all errors into a generic GetParameterError
except Exception as exc:
raise GetParameterError(str(exc))

if transform is not None:
new_values = {}
for key, value in values.items():
try:
new_values[key] = transform_value(value, transform)
except Exception as exc:
if raise_on_transform_error:
raise exc
else:
new_values[key] = None

values = new_values

self.store[key] = ExpirableValue(values, datetime.now() + timedelta(seconds=max_age),)

return self.store[key].value

@abstractmethod
def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
"""
Retrieve multiple parameter values from the underlying parameter store
"""
raise NotImplementedError()


def transform_value(value: str, transform: str) -> Union[dict, bytes]:
"""
Apply a transform to a value

Parameters
---------
value: str
Parameter alue to transform
transform: str
Type of transform, supported values are "json" and "binary"

Raises
------
TransformParameterError:
When the parameter value could not be transformed
"""

try:
if transform == "json":
return json.loads(value)
elif transform == "binary":
return base64.b64decode(value)
else:
raise ValueError(f"Invalid transform type '{transform}'")

except Exception as exc:
raise TransformParameterError(str(exc))
Loading