-
Notifications
You must be signed in to change notification settings - Fork 433
feat: add parameter utility #96
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
Merged
nmoutschen
merged 31 commits into
aws-powertools:develop
from
nmoutschen:parameter-utility
Aug 21, 2020
Merged
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 29d27b8
fix: add AWS_DEFAULT_REGION for boto3 tests
nmoutschen a805e74
revert "fix: add AWS_DEFAULT_REGION for boto3 tests"
nmoutschen 37964d1
fix: fix AWS_DEFAULT_REGION for get_parameter tests
nmoutschen dc3a5ab
fix: fix AWS_DEFAULT_REGION for get_parameter tests
nmoutschen 9731e0a
Merge branch 'parameter-utility' of github.com:nmoutschen/aws-lambda-…
nmoutschen 79bff7e
chore: rename _get_from_external_store to _get
nmoutschen a120528
feat: add get_multiple for parameter providers
nmoutschen d1c57ef
tests: increase test coverage
nmoutschen 285ac95
tests: increase test coverage (2)
nmoutschen 4c76276
tests: increase coverage to 100%
nmoutschen 6eb012f
fix: add get_parameters in __all__
nmoutschen e6416c0
chore: split parameter utilities into smaller files
nmoutschen de842a8
feat: use botocore.config.Config for parameter providers
nmoutschen 3569e21
feat: make arguments explicits in parameter utilities
nmoutschen 1278d2c
docs: add examples for parameter utilities
nmoutschen 5fb929d
feat: add override SDK options for parameter utilities
nmoutschen 7438766
docs: add examples for shorthands in the parameter utility
nmoutschen d53c373
fix: fix typo in DynamoDB parameter example
nmoutschen fce3268
feat: throw exception on failed transform for parameter utility
nmoutschen c765c90
docs: add examples on how to retrieve parameters in the parameter uti…
nmoutschen bec8de3
feat: use paginator for SSM parameter utility
nmoutschen 3ddc3bd
feat: make SSM parameter provider recursive by default
nmoutschen 5502215
feat: move sort_attr to init for DynamoDB parameter provider
nmoutschen c8c970f
feat: add 'raise_on_transform_error' for get_multiple parameter utility
nmoutschen ed45c4b
docs: add sdk_options to parameters for get and get_multiple
nmoutschen 4ecb17b
docs: add documentation for parameters utility
nmoutschen 616a98d
docs: add passing arguments to SDK
nmoutschen 68f6beb
docs: restructure based on feedback
nmoutschen dd3053d
docs: tweaks based on feedback
nmoutschen 7b87dfa
improv: iam permissions table
heitorlessa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# -*- coding: utf-8 -*- | ||
|
||
"""General utilities for Powertools""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.