• I recently came across the need to use AccessKeyId and SecretAccessKey values locally for an app I was developing
  • My IAM account has MFA enforced
  • I needed to assume a role and use the AccessKeyId and SecretAccessKey provided in the assumed role
  • If you try and assume a role like this it fails:
> aws sts assume-role --role-arn "arn:aws:iam::123456789123:role/MyRole" --role-session-name MyRoleSession

An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::123456789123:user/ is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::123456789123:role/MyRole


  • Have MFA set up already
  • Have set up your IAM credentials using aws configure on the command line


  • You need to get your MFA device details from the AWS console
    • You can find them here
    • The full ARN is required. See (1)
    • e.g. arn:aws:iam::123456789123:mfa/
    • Even if you use an app for your MFA codes AWS still refers to it as a device

MFA Device Details

  • You can then add two command line options to use the MFA device:
aws sts assume-role --role-arn "arn:aws:iam::123456789123:role/MyRole" --role-session-name MyRoleSession --token-code <MFA_CODE_HERE> --serial-number <MFA_DEVICE_DETAILS>
  • Replace the values:
    • <MFA_CODE_HERE> - With the code generated by your 2FA app/device
    • <MFA_DEVICE_DETAILS> - With the MFA device ARN


aws sts assume-role --role-arn "arn:aws:iam::123456789123:role/MyRole" --role-session-name MyRoleSession --token-code 123456 --serial-number "arn:aws:iam::123456789123:mfa/"

This will now generate session credentials similar to:

  "Credentials": {
    "AccessKeyId": "ASIA5SZTCEQL...",
    "SecretAccessKey": "RU2Iai2Tba56lGYI...",
    "SessionToken": "IQoJb3JpZ2luX2VjEF0aCWV1LX....",
    "Expiration": "2022-06-23T13:38:33+00:00"
  "AssumedRoleUser": {
    "AssumedRoleId": "AROA5SZTCEQLA7DA4LEEE:MyRole",
    "Arn": "arn:aws:sts::123456789123:assumed-role/MyRole/MyRoleSession"