RyeGuy
RyeGuy

Reputation: 4483

AWS SES - Connect to boto set without exposing access keys in code

I am using python to send emails via an AWS Simple Email Service.

In attempt to have the best security possible I would like to make a boto SES connection without exposing my access keys inside the code.

Right now I am establishing a connection like this

ses = boto.ses.connect_to_region(
   'us-west-2',
    aws_access_key_id='<ACCESS_KEY>',
    aws_secret_access_key='<SECRET_ACCESS_KEY>'
)

Is there a way to do this without exposing my access keys inside the script?

Upvotes: 1

Views: 2558

Answers (4)

glenfant
glenfant

Reputation: 1318

The simplest solution is to use environment variables you may retrieve in your Python code with os.environ.

export AWS_ACCESS_KEY_ID=<YOUR REAL ACCESS KEY>
export AWS_SECRET_ACCESS_KEY=<YOUR REAL SECRET KEY>

And in the Python code:

from os import environ as os_env

ses = boto.ses.connect_to_region(
   'us-west-2',
    aws_access_key_id=os_env['AWS_ACCESS_KEY_ID'],
    aws_secret_access_key=os_env['AWS_SECRET_ACCESS_KEY']'
)

Upvotes: 3

helloV
helloV

Reputation: 52375

To your EC2 instance attach an IAM role that has SES privileges, then you do not have to pass the credentials explicitly. Your script will get the credentials automatically from the metadata server.

See: Easily Replace or Attach an IAM Role to an Existing EC2 Instance by Using the EC2 Console. Then your code will be like:

ses = boto.ses.connect_to_region('us-west-2')

Upvotes: 3

it&#39;s-yer-boy-chet
it&#39;s-yer-boy-chet

Reputation: 2007

Two options are to set an environment variable named ACCESS_KEY and another named SECRET_ACCESS_KEY, then in your code you would have:

import os
ses = boto.ses.connect_to_region(
'us-west-2',
aws_access_key_id=os.environ['ACCESS_KEY'],
aws_secret_access_key=os.environ['SECRET_ACCESS_KEY']
)

or use a json file:

import json
path_to_json = 'your/path/here.json'

with open(path_to_json, 'r') as f:
    keys = json.load(f)

ses = boto.ses.connect_to_region(
'us-west-2',
aws_access_key_id=keys['ACCESS_KEY'],
aws_secret_access_key=keys['SECRET_ACCESS_KEY']
)

the json file would contain: {'ACCESS_KEY':<ACCESS_KEY>, 'SECRET_ACCESS_KEY':<SECRET_ACCESS_KEY>}

Upvotes: 2

Michael J
Michael J

Reputation: 1543

Preferred method of authentication is to use boto3's ability to read your AWS credential file.

Configure your AWS CLI using the aws configure command.

Then, in your script you can use the Session call to get the credentials: session = boto3.Session(profile_name='default')

Upvotes: 2

Related Questions