Search code examples
pythondjangoamazon-web-servicesboto3amazon-ses

How to use Amazon SES with dynamic credentials?


I'm using Django/Python and I want to use multiple Amazon SES credentials on same server.

I found boto3 to consume Amazon APIs but it requires to set the credentials using a file or environment variables. Which is I can't (or it's hard to) change it in the runtime.

How can I set the credentials dynamically on runtime?

I'm looking for a solution something like that: (boto3 is not mandatory, I can use any solution)

CREDS = {
    "foo": {
        "AWS_ACCESS_KEY_ID": "XXX",
        "AWS_SECRET_ACCESS_KEY": "XXX",
        "AWS_DEFAULT_REGION": "us-east-1",
    },
    "bar": {
        "AWS_ACCESS_KEY_ID": "YYY",
        "AWS_SECRET_ACCESS_KEY": "YYY",
        "AWS_DEFAULT_REGION": "us-east-1",
    },
}

my_config = CREDS.get("foo") # or "bar"
client = boto3.client('ses', config=my_config)

How can I implement this?


Solution

  • There is several ways actually to do it:

    The ways that you also wanted to is almost correct. I would advice either setting it up in the boto3.client or using the session and everything should work as expected.

    Example:

    import boto3
    
    client = boto3.client(
        's3',
        aws_access_key_id=ACCESS_KEY,
        aws_secret_access_key=SECRET_KEY,
        aws_session_token=SESSION_TOKEN
    )
    

    If you want, you could also create a aws config file with multiple profiles, which you can just get in your application.

    Everything is explained here: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html