What am I doing wrong here? I'm able to assume the roles via aws cli as well as boto if I use:
boto3.setup_default_session(profile_name="ROLE_TO_ASSUME")
What I'm trying to do: I have a number of AWS accounts my script needs to run in. I'm tired of typing my mfa each time I need to run the script on a different profile/role.
I get this error message with the code below:
User: arn:aws:iam::<management account>:user/Ops/<my user> is not authorized to perform: sts:AssumeRole on resource
Our AWS is setup like this: I am a user, part of a group on a management account. The group has a trust relationship set up with the ROLE_TO_ASSUME role on each account.
Here's my python:
import boto3
def main():
boto3.setup_default_session(profile_name="default")
ec2 = boto3.client('ec2')
get_assumerole_credentials('arn:aws:iam::<REPLACE WITH ACCOUNTID>:role/ROLE_TO_ASSUME')
def get_assumerole_credentials(arn):
sts_client = boto3.client('sts')
# Use client object and pass the role ARN
assumedRoleObject = sts_client.assume_role(RoleArn=arn,
RoleSessionName="AssumeRoleCredstashSession1")
credentials = assumedRoleObject['Credentials']
return dict(aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken'])
if __name__ == "__main__":
main()
Here's my ~/.aws/config
[profile default]
region = us-west-2
output = json
aws_access_key_id=<censored>
aws_secret_access_key=<censored>
[profile ROLE_TO_ASSUME]
region = us-west-2
source_profile = default
role_arn = arn:aws:iam::<accountid>:role/ROLE_TO_ASSUME
mfa_serial = arn:aws:iam::<accountid>:mfa/<my_user>
EDIT based on first reply:
To be clear, I am able to assume a role if I specify the 'profile' argument as in the following example:
boto3.setup_default_session(profile_name='ROLE_TO_ASSUME')
ec2 = boto3.resource('ec2', region_name='us-west-1')
But I need to assume a role and within the script using boto3's STS to get temp credentials.
I've noticed there is no MFA prompt when I use the boto3 STS assume role method of connecting.