Bootstrap FreeKB - Amazon Web Services (AWS) - Update Secret using Python boto3
Amazon Web Services (AWS) - Update Secret using Python boto3


This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using Python boto3. If not, check out my article Python (Scripting) - Getting Started with Amazon Web Services (AWS) boto3.

Here is the minimal boilerplate code without any error handling to update the key/value pairs in a secret.

#!/usr/bin/python3
import boto3

client = boto3.client('secretsmanager')

secrets_dict = client.list_secrets(
  Filters = [
    { 'Key': 'name', 'Values': ['my-secret'] }
  ]
)

for secret in secrets_dict['SecretList']:
  response = client.put_secret_value(
    SecretId=secret['ARN'],
    ClientRequestToken='abcdefgh-1234-5678-9001-abcdefg12345',
    SecretString='{"username":"john.doe","password":"mynewpassword"}'
  )

 

Here is a more practical example, with try/except/else error handling.

#!/usr/bin/python3
import boto3
import uuid
import sys

try:
  client = boto3.client('secretsmanager')
except Exception as exception:
  print(exception)
  sys.exit(1)

try:
  secrets_dict = client.list_secrets(
    Filters = [
      { 'Key': 'name', 'Values': ['my-secret'] }
    ]
  )
except Exception as exception:
  print(exception)
else:
  print(f"secret_dict= {secret_dict}")


for secret in secrets_dict['SecretList']:
  try:
    response = client.put_secret_value(
      SecretId=secret['ARN'],
      ClientRequestToken=str(uuid.uuid4()),
      SecretString='{"username":"john.doe","password":"mynewpassword"}'
    )
  except Exception as exception:
    print(exception)
  else:
    print(f"response = {response}")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 92b0e9 in the box below so that we can be sure you are a human.