You can configure the AWS CLI to assume an IAM role for you in combination with MFA. If you are a power user of the CLI, you will realize that you have to enter your MFA token every 60 minutes, which is annoying.

You will learn how to fix that in the following.

AWS account setup

Let’s assume we have three AWS accounts.

Account id Alias Description 000000000000 iam Only IAM users are created in this account 111111111111 dev Development workloads 222222222222 prod Production workloads

Besides that:

In the iam account, an IAM user named michael is created. MFA is enabled, and an access key is generated. In the dev and prod accounts, the following IAM role is created (CloudFormation template):



AWSTemplateFormatVersion: '2010-09-09'

Resources:

AdminRole:

Type: 'AWS::IAM::Role'

Properties:

AssumeRolePolicyDocument:

Version: '2012-10-17'

Statement:

- Effect: Allow

Principal:

AWS: 'arn:aws:iam::000000000000:root'

Action: 'sts:AssumeRole'

Condition:

Bool:

'aws:MultiFactorAuthPresent' : true

ManagedPolicyArns:

- 'arn:aws:iam::aws:policy/AdministratorAccess'

MaxSessionDuration: 43200

RoleName: Admin



Ensure that you set the MaxSessionDuration property! The default is 60 minutes.

Configuring the AWS CLI

The AWS CLI stores the configuration in ~/.aws/credentials (or %UserProfile%\.aws\credentials if you are using Windows).