Selecting AWS SSO profile for a terminal session with FZF

In this post I want to share with you my simple script which I use to select AWS SSO profile for a terminal session. As a developer of IaC for AWS, I have to switch between different AWS accounts and roles. In most cases customers use AWS Access portal (used to be known as SSO portal) for authentication and authorization. To quickly switch roles in the terminal I developed a simple script and aliases for shell to perform those operations quickly.

Prerequisites

AWS config structure

To identify AWS SSO profiles in the AWS config file I name related profiles with sso in the name. Here is an example of the AWS config file:

 1[default]
 2output = json
 3
 4[profile my-lz-sso-prod1_admin]
 5sso_start_url = https://d-abcde12345.awsapps.com/start#
 6sso_region = eu-central-1
 7region = eu-central-1
 8sso_account_id = 123456789012
 9sso_role_name = AdministratorAccess
10output = json
11
12[profile my-lz-sso-prod1_bedrock]
13sso_start_url = https://d-abcde12345.awsapps.com/start#
14sso_region = eu-central-1
15region = us-west-2
16sso_account_id = 123456789012
17sso_role_name = BedrockAccess
18output = json

Script

Script file will be called with eval command to export the selected profile to the current shell session. Therefore the script does not need to have “shebang” line and be executable.

1chosen=$(grep 'profile' ~/.aws/config | grep 'sso' | sed 's/^\[profile //; s/]//' | fzf --header='SSO profile' --border --height 10 --cycle --no-multi)
2
3if [ -z "$chosen" ]; then
4    exit 1
5fi
6
7export AWS_PROFILE=$chosen
8aws sso login

Aliases

These are my zsh aliases. You can adjust them to your shell.

1alias aws_sso_login='eval "$(cat ~/.scripts/sh/awssso)"'
2alias aws_sso_logout='aws sso logout && unset AWS_PROFILE'
3alias aws_clean_env='unset AWS_PROFILE AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SECURITY_TOKEN AWS_DEFAULT_REGION'

Usage

Demo video:

  • To select the AWS SSO profile you can use aws_sso_login command.
  • To close the session you can use aws_sso_logout or aws_clean_env aliases.