Created
October 26, 2021 08:52
-
-
Save alexsavio/a2a80bab6e7a4c5e91bc8ff7ff362185 to your computer and use it in GitHub Desktop.
SSM Secrets Repository
This file contains 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
""" | |
pip install boto3 'boto3-stubs[ssm]' | |
""" | |
from typing import TYPE_CHECKING | |
import boto3 | |
if TYPE_CHECKING: | |
from mypy_boto3_ssm.client import SSMClient | |
from mypy_boto3_ssm.type_defs import ( | |
GetParameterResultTypeDef, | |
PutParameterResultTypeDef, | |
) | |
from mypy_boto3_ssm.literals import ParameterTypeType | |
else: | |
SSMClient = object | |
GetParameterResultTypeDef = object | |
PutParameterResultTypeDef = object | |
ParameterTypeType = object | |
class Secrets: | |
""" | |
A repository of secrets that wrap | |
AWS Systems Manager - Parameter Store. | |
""" | |
def __init__(self, client: SSMClient = None): | |
self._client = client or boto3.client("ssm") | |
def get_parameter( | |
self, item: str, decrypt: bool = False | |
) -> GetParameterResultTypeDef: | |
result = self._client.get_parameter(Name=item, WithDecryption=decrypt) | |
return result | |
def _put_parameter( | |
self, | |
item: str, | |
value: str, | |
description: str, | |
type: ParameterTypeType, | |
**kwargs, | |
) -> PutParameterResultTypeDef: | |
return self._client.put_parameter( | |
Name=item, | |
Value=value, | |
Description=description, | |
Type=type, | |
**kwargs, | |
) | |
def get_secret(self, item: str) -> str: | |
parameter = self.get_parameter(item, decrypt=True) | |
return parameter["Parameter"]["Value"] | |
def get(self, item: str) -> str: | |
parameter = self.get_parameter(item) | |
return parameter["Parameter"]["Value"] | |
def put_secret(self, item: str, value: str, description: str): | |
_ = self._put_parameter(item, value, description, type="SecureString") | |
def put(self, item: str, value: str, description: str): | |
_ = self._put_parameter(item, value, description, type="String") | |
if __name__ == "__main__": | |
dev_session = boto3.Session(profile_name='dev') | |
dev_ssm_client = dev_session.client('ssm') | |
dev_secrets = Secrets(client=dev_ssm_client) | |
prod_session = boto3.Session(profile_name='prod') | |
prod_ssm_client = prod_session.client('ssm') | |
prod_secrets = Secrets(client=prod_ssm_client) | |
secret_names = [ | |
"secret1", | |
"secret2", | |
"secret3", | |
] | |
for secret_name in secret_names: | |
parameter = dev_secrets.get_parameter(secret_name, decrypt=True) | |
prod_secrets.put_secret( | |
item=parameter["Parameter"]["Name"], | |
value=parameter["Parameter"]["Value"], | |
description=parameter["Parameter"].get("Description", ""), | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment