-
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 2 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,8 @@ | ||
# -*- coding: utf-8 -*- | ||
|
||
"""General utilities for Powertools""" | ||
|
||
|
||
from .parameters import get_parameter | ||
|
||
__all__ = ["get_parameter"] |
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,63 @@ | ||
""" | ||
Parameter retrieval and caching utility | ||
""" | ||
|
||
|
||
from collections import namedtuple | ||
from datetime import datetime, timedelta | ||
|
||
import boto3 | ||
|
||
DEFAULT_MAX_AGE = 5 | ||
ExpirableValue = namedtuple("ExpirableValue", ["value", "ttl"]) | ||
PARAMETER_VALUES = {} | ||
ssm = boto3.client("ssm") | ||
|
||
|
||
def get_parameter(name: str, max_age: int = DEFAULT_MAX_AGE) -> str: | ||
""" | ||
Retrieve a parameter from the AWS Systems Manager (SSM) Parameter Store | ||
|
||
This will keep a local version in cache for `max_age` seconds to prevent | ||
overfetching from SSM Parameter Store. | ||
|
||
See the [AWS Systems Manager Parameter Store documentation] | ||
(https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) | ||
for more information. | ||
|
||
Parameters | ||
---------- | ||
name: str | ||
Name of the SSM Parameter | ||
max_age: int | ||
Duration for which the parameter value can be cached | ||
|
||
Example | ||
------- | ||
|
||
from aws_lambda_powertools.utilities import get_parameter | ||
|
||
def lambda_handler(event, context): | ||
# This will only make a call to the SSM service every 30 seconds. | ||
value = get_parameter("my-parameter", max_age=30) | ||
|
||
Raises | ||
------ | ||
ssm.exceptions.InternalServerError | ||
When there is an internal server error from AWS Systems Manager | ||
ssm.exceptions.InvalidKeyId | ||
When the key ID is invalid | ||
ssm.exceptions.ParameterNotFound | ||
When the parameter name is not found in AWS Systems Manager | ||
ssm.exceptions.ParameterVersionNotFound | ||
When a version of the parameter is not found in AWS Systems Manager | ||
""" | ||
|
||
if name not in PARAMETER_VALUES or PARAMETER_VALUES[name].ttl < datetime.now(): | ||
# Retrieve the parameter from AWS Systems Manager | ||
parameter = ssm.get_parameter(Name=name) | ||
nmoutschen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
PARAMETER_VALUES[name] = ExpirableValue( | ||
parameter["Parameter"]["Value"], datetime.now() + timedelta(seconds=max_age) | ||
) | ||
|
||
return PARAMETER_VALUES[name].value |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,128 @@ | ||
import random | ||
import string | ||
from datetime import datetime, timedelta | ||
|
||
import pytest | ||
from botocore import stub | ||
|
||
from aws_lambda_powertools import utilities | ||
from aws_lambda_powertools.utilities import parameters | ||
|
||
|
||
@pytest.fixture(scope="function") | ||
def mock_name(): | ||
# Parameter name must match [a-zA-Z0-9_.-/]+ | ||
return "".join(random.choices(string.ascii_letters + string.digits + "_.-/", k=random.randrange(3, 200))) | ||
|
||
|
||
@pytest.fixture(scope="function") | ||
def mock_value(): | ||
# Standard parameters can be up to 4 KB | ||
return "".join(random.choices(string.printable, k=random.randrange(100, 4000))) | ||
|
||
|
||
@pytest.fixture(scope="function") | ||
def mock_version(): | ||
return random.randrange(1, 1000) | ||
|
||
|
||
def test_get_parameter_new(monkeypatch, mock_name, mock_value, mock_version): | ||
""" | ||
Test get_parameter() with a new parameter name | ||
""" | ||
|
||
# Patch the parameter value store | ||
monkeypatch.setattr(parameters, "PARAMETER_VALUES", {}) | ||
|
||
# Stub boto3 | ||
stubber = stub.Stubber(parameters.ssm) | ||
response = { | ||
"Parameter": { | ||
"Name": mock_name, | ||
"Type": "String", | ||
"Value": mock_value, | ||
"Version": mock_version, | ||
"Selector": f"{mock_name}:{mock_version}", | ||
"SourceResult": "string", | ||
"LastModifiedDate": datetime(2015, 1, 1), | ||
"ARN": f"arn:aws:ssm:us-east-2:111122223333:parameter/{mock_name}", | ||
} | ||
} | ||
expected_params = {"Name": mock_name} | ||
stubber.add_response("get_parameter", response, expected_params) | ||
stubber.activate() | ||
|
||
# Get the parameter value | ||
try: | ||
value = utilities.get_parameter(mock_name) | ||
|
||
assert value == mock_value | ||
stubber.assert_no_pending_responses() | ||
finally: | ||
stubber.deactivate() | ||
|
||
|
||
def test_get_parameter_cached(monkeypatch, mock_name, mock_value, mock_version): | ||
""" | ||
Test get_parameter() with a cached value for parameter name | ||
""" | ||
|
||
# Patch the parameter value store | ||
monkeypatch.setattr( | ||
parameters, | ||
"PARAMETER_VALUES", | ||
{mock_name: parameters.ExpirableValue(mock_value, datetime.now() + timedelta(seconds=60))}, | ||
) | ||
|
||
# Stub boto3 | ||
stubber = stub.Stubber(parameters.ssm) | ||
stubber.activate() | ||
|
||
# Get the parameter value | ||
try: | ||
value = utilities.get_parameter(mock_name) | ||
|
||
assert value == mock_value | ||
stubber.assert_no_pending_responses() | ||
finally: | ||
stubber.deactivate() | ||
|
||
|
||
def test_get_parameter_expired(monkeypatch, mock_name, mock_value, mock_version): | ||
""" | ||
Test get_parameter() with a cached, but expired value for parameter name | ||
""" | ||
|
||
# Patch the parameter value store | ||
monkeypatch.setattr( | ||
parameters, | ||
"PARAMETER_VALUES", | ||
{mock_name: parameters.ExpirableValue(mock_value, datetime.now() - timedelta(seconds=60))}, | ||
) | ||
|
||
# Stub boto3 | ||
stubber = stub.Stubber(parameters.ssm) | ||
response = { | ||
"Parameter": { | ||
"Name": mock_name, | ||
"Type": "String", | ||
"Value": mock_value, | ||
"Version": mock_version, | ||
"Selector": f"{mock_name}:{mock_version}", | ||
"SourceResult": "string", | ||
"LastModifiedDate": datetime(2015, 1, 1), | ||
"ARN": f"arn:aws:ssm:us-east-2:111122223333:parameter/{mock_name}", | ||
} | ||
} | ||
expected_params = {"Name": mock_name} | ||
stubber.add_response("get_parameter", response, expected_params) | ||
stubber.activate() | ||
|
||
# Get the parameter value | ||
try: | ||
value = utilities.get_parameter(mock_name) | ||
|
||
assert value == mock_value | ||
stubber.assert_no_pending_responses() | ||
finally: | ||
stubber.deactivate() |
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.