Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add key/value pair to existing secrets path in AWS secrets manager without overwriting it using boto3

I have this code which I’m using to put secrets in AWS secrets manager

class SecretsManagerSecret:
    """Encapsulates Secrets Manager functions."""
    def __init__(self, env):
        """
        :param env: Environment on which DAG is running
        """
        self.secretsmanager_client = boto3.client("secretsmanager", region_name="us-east-1")
        self.env = env
        self.name = None

    def put_value(self, secret_value, stages=None):

        if self.name is None:
            raise ValueError("Secret Name/Path not defined")

        try:
            kwargs = {'SecretId': self.name}
            if isinstance(secret_value, str):
                kwargs['SecretString'] = secret_value
            elif isinstance(secret_value, bytes):
                kwargs['SecretBinary'] = secret_value
            if stages is not None:
                kwargs['VersionStages'] = stages
            response = self.secretsmanager_client.put_secret_value(**kwargs)
            logger.info("Value put in secret %s.", self.name)
        except ClientError:
            logger.exception("Couldn't put value in secret %s.", self.name)
            raise
        else:
            return response

secret_obj = SecretsManagerSecret("dev")
# Path of secret where multiple key value pair exists
secret_obj.name = "applications/keys/data_pipelines"
# This overwrites existing key value pairs and writes this
secret_obj.put_value('{"test":"test1235"}')

The issue here is when I call put_value method, it replaces all the existing key value pairs in path applications/keys/data_pipelines and writes '{"test":"test1235"}'. Is there any existing function in boto3 which can append rather than replacing it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What if you use the update_secret method from the boto3 client for secrets_manager

client = session.client(service_name="secretsmanager")

# get the secret value first
existing_secret = client.get_secret_value(SecretId="secret_id")

# then update it with your new value
updated_secret = existing_secret.update({"UPDATE_KEY": "update_value"})

client.update_secret(SecretId="secret_id", SecretString=json.dumps(updated_secret))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading