There are situations that one may have multiple AWS accounts (or IAM roles) and need switch among them sometimes. This is doable via the AWS website by clicking the username button at the top-right and then click switch role.
How to do this in the command line?
To switch IAM roles via AWS CLI, one can do the following:
Edit the file ~/.aws/credentials
The file ~/.aws/credentials stores the AWS credentials. It may include multiple profiles, in the following format:
|
|
So this file contatins two profiles: default and project_role, which may correspond to different accounts. If the same credentials for the different accounts, one can keep only one profile here.
Edit the file ~/.aws/config
Then in ~/.aws/config, one need to add a corresponding profile using the credentials and IAW roles. As an example below:
|
|
In the above file, the default profile uses the default setting in the credentials, and the project profile uses the credentials set in the profile project_role. DO NOT forget the keyword ‘profile’ when defining a new profile.
Here the parameter role_arn provides the arn for the IAM role in a different account, and it can be found by searching IAM service, then Roles after switching to that IAM role in the AWS web console. It may show something like arn:aws:sts::123456789012:assumed-role//
Here the role-name and the account numbers are needed to set the parameter role_arn as above.
To learn more about the config file setting, one can refer to here.
Switch the role in command line
With the above settings done, we can use the following command to swith roles on the fly.
|
|
As you can see, we just need to provide a parameter –profile to specify the new IAM role, which will allow us to access the resources assigned to this role.
References
Last modified on 2022-05-26