How to update AWS Secrets Manager via python?

aws secrets manager python example
aws secrets manager cli
aws secrets manager lambda example
aws secretsmanager get-secret-value
aws secrets manager node js example
aws secrets manager api
aws secrets manager c# example
aws secrets manager tutorial

I can't find any documentation on how to upload/update values to the AWS secrets manager. I can only retrieve the values via python. Is there a workaround on this?

You can use update_secret():

response = client.update_secret(
    SecretId='string',
    ClientRequestToken='string',
    Description='string',
    KmsKeyId='string',
    SecretBinary=b'bytes',
    SecretString='string'
)

For creating new secrets, use: put_secret_value()

SecretsManager — Boto3 Docs 1.14.25 documentation, Store the ARN of the CMK in the secret when you create the secret or when you update it by including it in the KMSKeyId . If you call an API that must encrypt or� If you create this secret by using the Secrets Manager console then Secrets Manager puts the protected secret text in only the SecretString parameter. The Secrets Manager console stores the information as a JSON structure of key/value pairs that the default Lambda rotation function knows how to parse.

import json
from boto3 import Session

# initialize session client

session = Session(
    aws_access_key_id="aws_access_key_id",
    aws_secret_access_key="aws_secret_access_key",
    region_name="region_name"
)

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

FOR CREATE

client.create_secret(Name="my_first_secret", SecretString=json.dumps({"favorite_character": "stitch!"}))


FOR UPDATE

# get original secrets
original_secret = client.get_secret_value(SecretId="my_first_secret")


# update secrets
updated_secret = original_secret.update({"UPDATE_KEY": "update_value"})
client.update_secret(SecretId="my_secret_name", SecretString=json.dumps(updated_secret))

How to update AWS Secrets Manager via python?, You can use update_secret() : response = client.update_secret( SecretId='string', ClientRequestToken='string', Description='string',� Secret Manager is not the only way you can store secrets on AWS. There is also an another service names AWS Simple System Manager (SSM) that comes with a similar feature, namely Parameter Store .

def init_aws_session():
    region_name = "us-east-1"
    my_access_id = 'my_access_id'
    my_secret_key = 'my_secret_key'
    # Create a Secrets Manager client
    session = boto3.session.Session(
        region_name=region_name,
        aws_access_key_id=my_access_id,
        aws_secret_access_key=my_secret_key
    )
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name,
    )
    return client


def update_secret(secret_name, key, value):
    client = init_aws_session()
    # get original secrets
    config_secret = get_secret(secret_name, client)
    secret.update({key: value})
    client.update_secret(SecretId=secret_name, SecretString=json.dumps(secret))
    print(secret)


def get_secret(secret_name):
    client = init_aws_session()

    # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
    # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
    # We rethrow the exception by default.

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'DecryptionFailureException':
            # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InternalServiceErrorException':
            # An error occurred on the server side.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            # You provided an invalid value for a parameter.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            # You provided a parameter value that is not valid for the current state of the resource.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'ResourceNotFoundException':
            # We can't find the resource that you asked for.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
    else:
        # Decrypts secret using the associated KMS CMK.
        # Depending on whether the secret is a string or binary, one of these fields will be populated.
        if 'SecretString' in get_secret_value_response:
            secret = get_secret_value_response['SecretString']
        else:
            decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])

    # Your code goes here.
    return json.loads(secret)


if __name__ == '__main__':
    update_secret(some_secret, key, value)

Tutorial: Creating and Retrieving a Secret, In this tutorial, you create a secret and store it in AWS Secrets Manager. You then retrieve the secret using the AWS Management Console or the AWS CLI. Using the Python cache feature, you can now use the cache library to reduce calls to the AWS Secrets Manager API, improving the availability and latency of your application. As shown in the diagram below, when you implement the Python cache, the call to retrieve the secret is routed to the local cache before reaching the AWS Secrets Manager API.

Modifying a Secret - AWS Secrets Manager, In the console, you can edit the description, edit or attach a new resource-based policy to modify permissions to the secret, change the AWS KMS customer� Note from May 10, 2019: We’ve updated a code sample for accuracy. Today, AWS Secrets Manager introduced a client-side caching library for Python that improves the availability and latency of accessing and distributing credentials to your applications. It can also help you reduce the cost associated with retrieving secrets.

update-secret — AWS CLI 1.18.103 Command Reference, Note that if an Secrets Manager API call results in AWS creating the account's AWS-managed CMK, it can result in a one-time significant delay in returning the� If you don't specify this value, then Secrets Manager defaults to using the AWS account's default CMK (the one named aws/secretsmanager). If a AWS KMS CMK with that name doesn't yet exist, then Secrets Manager creates it for you automatically the first time it needs to encrypt a version's SecretString or SecretBinary fields.

Improve availability and latency of applications by using AWS Secret , Note from May 10, 2019: We've updated a code sample for accuracy. Using the Secrets Manager client-side caching library for Python. You can start using Secrets Manager with Amazon VPC endpoints by creating an Amazon VPC endpoint for Secrets Manager with a few clicks on the VPC console or via AWS CLI. Once you create the VPC endpoint, you can start using it without making any code or configuration changes in your application.

Comments
  • oh i would not advise to have aws credentials in code. Demo's fine
  • We don't really put that in code. If running on EC2, it's already handled by the boto.utils.get_instance_identity() since we're using EC2 roles and avoided using ~/.aws as credentials