AWS DynamoDB snippets
How to create a boto3 DynamoDB resource
Please note that this snippet is part of the DynamoDB-Simpsons-episodes-full-example repository on GitHub.
First of all, you have to import the module boto3 import boto3
and then create a YAML file named credentials.yml
where you store your AWS public and secret keys.
The YAML file should have the following structure:
dynamodb:
AWS_SERVER_PUBLIC_KEY: xxxxxxxxx
AWS_SERVER_SECRET_KEY: xxxxxxxxx
REGION_NAME: us-east-1
After that you can read your credentials and assign them to the variables of your script:
# Load credentials from YAML file
with open("credentials.yml", "r") as keyholder:
try:
credentials=yaml.safe_load(keyholder)
except yaml.YAMLError as exc:
print(exc)
AWS_SERVER_PUBLIC_KEY=credentials['dynamodb']['AWS_SERVER_PUBLIC_KEY']
AWS_SERVER_SECRET_KEY=credentials['dynamodb']['AWS_SERVER_SECRET_KEY']
REGION_NAME=credentials['dynamodb']['REGION_NAME']
and, finally, create your dynamodb resource:
dynamodbRes = boto3.resource(
"dynamodb",
region_name=REGION_NAME,
aws_access_key_id=AWS_SERVER_PUBLIC_KEY,
aws_secret_access_key=AWS_SERVER_SECRET_KEY,
)
print(dynamodbRes)
This will output:
dynamodb.ServiceResource()