joaonrb
joaonrb

Reputation: 1021

How to use access credentials in code instead of environment variables with PynamoDB

I have a python app that uses several services from aws. I have one access key and secret for each service. For most of the services I use boto and don't need AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY in the environment. For dynamoDB I use pynamoDB and I have no idea how to set the credentials without these variables.

I want to standardize the credential in a settings file to avoid errors like clash of credentials.

Is this possible? If so, how is it done?

Upvotes: 4

Views: 1656

Answers (2)

Venkatesh Marepalli
Venkatesh Marepalli

Reputation: 606

I was searching for this online and came across this question, though this is old, I am sharing my solution so that it might be helpful someone.

When defining the Dynamo DB model all we need is to add one additional line of code which contains the IAM rolename. Below is a sample model.

If you change the model like the one below we don't need ~/.aws/credentials file on the container.

Note: Make sure you attach DynamoDBRead or write policy to the IAM role, I have attached AmazonDynamoDBFullAccess policy for my instances IAM role.

from pynamodb.models import Model
from pynamodb.attributes import (
        UnicodeAttribute, NumberAttribute, UnicodeSetAttribute, UTCDateTimeAttribute
    )
import urllib2  
class TestClass(Model):
    email = UnicodeAttribute(hash_key=True)
    UUID = UnicodeAttribute(range_key=True)


    class Meta:
        region = 'eu-west-2'
        # Refer: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
        instanceProfileName = urllib2.urlopen(
            'http://169.254.169.254/latest/meta-data/iam/security-credentials/').read()

        table_name = 'dynamodb-tablename'

Upvotes: 0

Mark B
Mark B

Reputation: 200486

From the PynamoDB documentation:

PynamoDB uses botocore to interact with the DynamoDB API. Thus, any method of configuration supported by botocore works with PynamoDB. For local development the use of environment variables such as AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY is probably preferable. You can of course use IAM users, as recommended by AWS. In addition EC2 roles will work as well and would be recommended when running on EC2.

Note that if all the services you are interacting with are within the same AWS account, then the preferred way to supply credentials would be to create a single IAM account with all the necessary permissions attached, or an IAM role if the code is running on EC2 or Lambda.

Upvotes: 2

Related Questions