Skip to content

Instantly share code, notes, and snippets.

@jerm
Last active March 29, 2019 05:23
Show Gist options
  • Save jerm/7eedc094f3cd0f6ac2b4fda665f93762 to your computer and use it in GitHub Desktop.
Save jerm/7eedc094f3cd0f6ac2b4fda665f93762 to your computer and use it in GitHub Desktop.
POC python class and demo usage to get groups of credentials from parameter store
# This class retrieves /prefix/* parameters from aws parameter store and lets
# you either reference them individually or it will put them all into your os environment
# for fetching in familiar ways
import os
import boto3
class AWSParameterClass(object):
def __init__(self, prefix):
_project = boto3.client('ssm')
def get_param_batch(NextToken):
if NextToken:
return _project.get_parameters_by_path(
Path=prefix,
Recursive=True,
WithDecryption=True,
NextToken=NextToken,
)
else:
return _project.get_parameters_by_path(
Path=prefix,
Recursive=True,
WithDecryption=True,
)
_pstorage = {}
NextToken = False
while True:
_response = get_param_batch(NextToken)
for param in _response['Parameters']:
_pstorage[param['Name'].split('/')[-1]] = param['Value']
NextToken = _response.get('NextToken',False)
if not NextToken:
break
self.params = _pstorage
def get(self, name):
return self.params[name]
def list_keys(self):
keys = []
for key, value in self.params.items():
print(key)
keys.append(key)
return keys
def put_env(self):
for key, value in self.params.items():
os.environ[key] = value
params = AWSParameterClass("/mycompany/webapp/staging")
# You can use the dictionary directly, as further below, or keep an existing env-var based
# workflow by having the class inject the gotten paramters into your envrionment in one fell swoop
params.put_env()
# Parameter store only stores strings, so we end up having to convert them to
# strings in ie: secrets.yml, and then coercing them into the proper types on this end, ie:
# Strings are pretty easy
EMAIL_HOST = params.get('EMAIL_HOST')
# Booleans
EMAIL_USE_TLS = bool(params.get('EMAIL_USE_TLS'))
# Ints
EMAIL_PORT = int(params.get('EMAIL_PORT'))
# Lists get into interesting erritory with the eval. But if
# this isn't trusted data, we're already screwed
ALLOWED_HOSTS = eval(params.get('ALLOWED_HOSTS'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment