Cross-Account IAM Role Assumption with MFA
Securely assume IAM roles across AWS accounts using MFA-protected temporary credentials for least-privilege access.
Prerequisites
- -AWS CLI v2 installed and configured
- -IAM role with trust policy allowing your account
- -MFA device registered on your IAM user
Steps
Get your MFA device ARN
List the virtual MFA devices associated with your IAM user to retrieve the ARN needed for authentication.
You can also find your MFA ARN in the IAM console under your user's Security credentials tab.
Get a session token with MFA
Request temporary session credentials by providing your MFA device ARN and a current TOTP code from your authenticator app.
The TOTP code expires every 30 seconds. Enter the command quickly after generating a fresh code.
Assume the cross-account role
Use the MFA-authenticated session to assume a role in the target account. This returns a new set of temporary credentials scoped to that role.
Add --duration-seconds to extend the session up to the role's MaxSessionDuration (default 1 hour, max 12 hours).
Export the temporary credentials
Set the returned temporary credentials as environment variables so subsequent AWS CLI commands use the assumed role.
Use jq to parse the JSON output cleanly. Install it with your package manager if not available.
Verify the assumed identity
Confirm that your CLI session is now operating under the assumed role in the target account.
The output should show the target account ID and the assumed role ARN, not your original user.
Unset credentials when done
Clear the temporary credentials from your environment to return to your default AWS profile.
Always unset assumed role credentials when finished to avoid accidentally running commands in the wrong account.
Full Script
FAQ
Discussion
Loading comments...