How to assume roles interactively and quickly in AWS CLI

How to assume roles interactively and quickly in AWS CLI

Working on AWS projects in the terminal can be annoying sometimes, especially when you have a large list of accounts and roles to work with. Typing in the multi-part command and the role ARN is just too much work to do over and over again:
aws sts assume-role --role-arn arn:aws:iam::123456789012:role/roletoassume
Defining an alias for each role is impracticable, as well, because it would require to edit the AWS CLI config file (~/.aws/config and ~/.aws/credentials) and update the aliases (~/.bash_aliases or similar depending on your shell). It would be so much easier if the assume-role command would just query the AWS config.

Just like this:

The solution is the little helper programm assume-role in combination with fzf.

Installation and setup

The following assumes bash as your shell of choice and aptitude as the package manager. Other shells or package managers work just as well.

AWS CLI

Download and install AWS CLI: This covers the base functionality, i.e. interacting with AWS services.

Go

Install Go through your standard package manager.

Go binaries are by default placed in ~/go/bin, so this location must be added to the PATH by appending the following to lines to the ~/.bashrc file.

Assume-role

Install assume-role from Remind.

Update [12.09.2022]: In newer versions of go you might have to install assume-role with
go install github.com/remind101/assume-role@latest
because the way go handles installations outside modules changed.

Fzf

Install fzf, a fuzzy finder for the command line. Here, fzf is used to query the AWS config file but it can do so much more.

(Optional) Enable the key bindings for more convienent use. This is not necessary if fzf should only query the config file.

Bring it all together in one function

Create a short function to interactively assume roles by adding to folowing to ~/.bashrc. It might be useful to give this function a shorter and more unique name, so it can be typed as wuickly as possible with the help of auto-completion.

Don’t forget to reload .bashrc after these updates (or open a new terminal).

Usage

Just type assume-role-p and the interactive profile switcher will open, just like you see in the GIF above.