I have a boto3 script that successfully uploads files to an S3 bucket, using my account's AccessKeyId and SecretAccessKey. This works fine.
But I'm supposed to remove my credentials from this instance and only use the IAM role attached to the instance. I've made various attempts but haven't gotten this to work, usually with:
botocore.exceptions.ClientError: An error occurred (InvalidToken) when
calling the PutObject operation: The provided token is malformed or
otherwise invalid.
My code:
!/usr/bin/env python
import datetime
import sys
import os
import ConfigParser
import boto3
s3 = boto3.resource('s3')
config = ConfigParser.ConfigParser()
configfile = config.read('edi.config')
s3bucket = config.get('default', 's3bucket')
s3bucket = s3bucket.strip()
print 's3bucket: ', s3bucket
today = datetime.date.today()
todaystr = today.strftime('%m_%d_%Y')
os.chdir(todaystr)
try:
os.mkdir('uploaded')
except:
pass
for f in os.listdir('.'):
if not os.path.isfile(f):
continue
print 'uploading', f
data = open(f)
s3.Bucket('ustc-submissions-non-prod').put_object(Key='closewatch/incoming/%s' % f, Body=data)
os.rename(f,'uploaded/%s' % f)
I found a note elsewhere that I need to assume the IAM role within boto3, but (a) I don't have permission to do that and (b) I don't have permission to give myself permission and (c) my colleague thinks this shouldn't be necessary anyway.
Anybody got a complete example of this sort of thing?