When I use AWS I switch roles to see client data in the console and it works fine.
However I'm trying to do it using the boto3
package in python and running into an "access denied" error. I don't have permission to add an IAM role or edit trust policy in the console, but i feel like i shouldn't need to do this?
Example code and error below:
initial auth to my acct works fine
mfa_TOTP = input("Enter the MFA code: ")
sts_connection = STSConnection()
tempCredentials = sts_connection.get_session_token(
duration=3600,
mfa_serial_number="arn:aws:iam::123xyz123:mfa/my.name",
mfa_token=mfa_TOTP
)
print('MFA authentication successful :)')
Enter the MFA code: 123456
MFA authentication successful :)
trying to assume a role fails
account = df.Account[0]
acct_num = account.split('[')[1].split(']')[0]
role_arn = 'arn:aws:iam::' + str(acct_num) + ':role/this-user'
sts_client = boto3.client('sts')
assumed_role_object = sts_client.assume_role(
RoleArn = role_arn,
RoleSessionName = account.split(' ')[0]
)
ClientError: An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::123xyz123:user/my.name is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::456abc456:role/this-user
There is a problem in your policy, to make sts_client.assume_role
to work, you need to Allow STS Assume in your Lambda role . You can add below code in your IAM policy to make it work:
{
"Action": "sts:AssumeRole",
"Resource": [
"arn:aws:iam::*:role/this-user"
],
"Effect": "Allow"
}
you have to include the temporary credential when assuming the role as below.
sts_client = boto3.client('sts',
aws_access_key_id= tempCredentials['AWS_ACCESS_KEY_ID'],
aws_secret_access_key= tempCredentials['AWS_SECRET_ACCESS_KEY'],
aws_session_token= tempCredentials['AWS_SESSION_TOKEN']
)
assumed_role_object = sts_client.assume_role(
RoleArn = role_arn,
RoleSessionName = account.split(' ')[0]
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.