First I'd like to point this is NOT the same problem as this similar question. As I have looked through all the answers and none could actually help in my case.
I have a Python script that must be executed inside containers (we're going to ship it as an encapsulated solution to run on-premises for some customers) in which I have to send an email using boto3.
here is the code for it:
from os import stat
import boto3
from botocore.config import Config
import botocore.exceptions
class EmailHandler:
def __init__(self, business_rules, integrations, credentials, event):
self.business_rules = business_rules
self.integrations = integrations
self.credentials = credentials
self.event = event
def send_message(self, message):
region_name = 'us-east-1'
role_arn = self.credentials['role_arn']
my_config = Config(
region_name = region_name,
signature_version = 'v4',
retries = {
'max_attempts': 10,
'mode': 'standard'
},
)
sts = boto3.client('sts',
aws_access_key_id=self.credentials['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=self.credentials['AWS_ACCESS_KEY_ID'])
response = sts.assume_role(
RoleArn=role_arn,
RoleSessionName = 'SES_operation'
)
tempAccessKeyId = response['Credentials']['AccessKeyId']
tempSecretAccessKey = response['Credentials']['SecretAccessKey']
tempSessionToken = response['Credentials']['SessionToken']
client = boto3.client('ses',
aws_access_key_id = tempAccessKeyId,
aws_secret_access_key = tempSecretAccessKey,
aws_session_token = tempSessionToken,
config=my_config)
subject = self.event['alert_message']
to_email = self.credentials['email_receivers']
status = 900
state = 'failure'
data = {'message': ''}
try:
response = client.send_email(
Source= self.credentials['source_email'],
Destination= {
'ToAddresses': [
to_email,
]
},
Message={
'Subject': {
'Data': subject,
},
'Body': {
'Text': {
'Data': message,
},
'Html': {
'Data': '<p>'+ message +'</p>'
}
}
},
SourceArn = self.credentials['source_identity'],
)
state = 'success'
status = 200
data = {'message': response.MessageId }
except botocore.exceptions.ClientError as error:
data = {'message': error.response['Error']['Message']}
raise error
return(status, state, data)
As you can see, I am trying to assume role so I can use the session token provided to create a client for SES.
The problem is that I am getting the following error whenever this handler is executed:
An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid.
But I'm not providing any tokens since my goal is exactly to get it using this method call. Am I missing something?
PS: I can't use config file as per you can see in the code, the credentials are passed from an outside source.