'specify role while uploading file to s3

I have a profile clientProject setup in my aws config file. I also have the necessary credentials in my aws credentials file. However, if I create a Python script from scratch:

import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file('catalog.json', 'testunzipping','catalog.json')

I am unable to run it because before uploading the file, I would need to switch/assume roles on AWS so that I can have the necessary permissions.

boto3.exceptions.S3UploadFailedError: Failed to upload catalog.json to testunzipping/catalog.json: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

How can I specify the profile and existing role using an isolated script?



Solution 1:[1]

As per boto3 documentation here, you cloud use the following to use your clientProject profile.

session = boto3.Session(profile_name='clientProject')
s3 = session.resource('s3')
s3.meta.client.upload_file('catalog.json', 'testunzipping','catalog.json')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 snowmanstark