DEV Community

Cover image for How to Simplify AWS CLI Login with IAM Identity Center
Amandeep Singh
Amandeep Singh

Posted on

How to Simplify AWS CLI Login with IAM Identity Center

If you're using IAM Identity Center to manage access to AWS member accounts and regularly work with the AWS CLI, you've probably gotten tired of the usual login routine. You know the drill - copy those AWS environment variables from the Access portal, paste them into your shell, and repeat this every time your credentials expire.

There's a better way to handle this, and I'm going to show you how to set it up.

What's the Problem with the Current Approach?

Normally, when you need to access an AWS account, you click on the access keys icon in the AWS Access portal and copy the environment variables into your terminal session.

AWS Access Portal showing the access keys icon

AWS Access Portal with environment variables displayed

The problem? These credentials expire pretty quickly, and you end up refreshing them constantly throughout the day. It gets old fast, especially when you're juggling multiple accounts.

The Better Solution

AWS actually provides a recommended way to handle this: the aws configure sso command. But we're going to take it a step further and create some shell utilities that make switching between accounts almost effortless.

By the end of this tutorial, you'll have three handy commands:

  • aws-pick - Opens a searchable menu to select any account
  • aws-remind - Shows you the commands you need (because we all forget sometimes)
  • aws-session-remaining - Tells you when your session expires

What You'll Need

Before we start, make sure you have:

  • Access to AWS accounts through IAM Identity Center
  • Basic familiarity with Bash or Zsh
  • Your AWS Access Portal URL (looks like https://d-xxxxxxxxxx.awsapps.com/start)
  • The region where your IAM Identity Center is hosted

Step 1: Back Up Your Shell Config

First things first - let's not break anything. Make a backup of your shell configuration:

cp ~/.bashrc ~/.bashrc.bak
Enter fullscreen mode Exit fullscreen mode

If you're on macOS with Zsh:

cp ~/.zshrc ~/.zshrc.bak
Enter fullscreen mode Exit fullscreen mode

Step 2: Add the Shell Functions

Open your shell config file:

vim ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

Or on macOS:

vim ~/.zshrc
Enter fullscreen mode Exit fullscreen mode

Now, depending on your OS, add the appropriate functions below.

For Linux Users (Bash)

Paste these functions into your .bashrc:

# AWS SSO Login Functions
aws-pick() {
  # List only SSO profiles
  PROFILES=$(awk '/^\[profile / {gsub(/\[profile |\]/,""); print $0}' ~/.aws/config)

  # Use fzf to pick one
  SELECTED=$(echo "$PROFILES" | fzf --prompt="Select AWS SSO Profile: ")

  if [ -z "$SELECTED" ]; then
    echo "No profile selected. Exiting."
    return 1
  fi

  export AWS_PROFILE=${SELECTED}
}

aws-session-remaining() {
  profile=${1:-sso}
  url=$(aws configure get sso_start_url --profile "$profile")
  now_epoch=$(date +%s)
  max_expiry_epoch=0

  for file in ~/.aws/sso/cache/*.json; do
    if grep -q "$url" "$file" 2>/dev/null; then
      file_expiry=$(jq -r '.expiresAt // empty' "$file" 2>/dev/null)
      if [ -n "$file_expiry" ]; then
        file_expiry_epoch=$(date -u -d "$file_expiry" +%s 2>/dev/null)
        [ $? -eq 0 ] && [ "$file_expiry_epoch" -gt "$max_expiry_epoch" ] && max_expiry_epoch=$file_expiry_epoch
      fi
    fi
  done

  if [ "$max_expiry_epoch" -eq 0 ]; then
    echo "No valid session found for profile $profile"
    return 1
  fi

  remaining=$((max_expiry_epoch - now_epoch))

  if (( remaining > 0 )); then
    echo "Session for [$profile] expires in: $(date -ud "@$remaining" +'%H hours %M minutes %S seconds')"
  else
    echo "Session has already expired."
  fi
}

aws-remind() {
  echo "aws-sso-util: A really handy python wrapper for aws sso login!"
  echo -e "aws-sso util: Install with pip\n\nUsage:"
  echo "aws-sso-util login --profile sso"
  echo "aws-sso-util configure populate -u <AWS-access-portal-URL> --region <IAM-Identity-Center-region>"
  echo "aws-pick # Select a profile to use"
}
Enter fullscreen mode Exit fullscreen mode

For macOS Users (Zsh)

The macOS version is slightly different because it uses GNU date:

# AWS SSO Login Functions
aws-pick() {
  PROFILES=$(awk '/^\[profile / {gsub(/\[profile |\]/,""); print $0}' ~/.aws/config)

  SELECTED=$(echo "$PROFILES" | fzf --prompt="Select AWS SSO Profile: ")

  if [ -z "$SELECTED" ]; then
    echo "No profile selected. Exiting."
    return 1
  fi

  export AWS_PROFILE=${SELECTED}
}

aws-session-remaining() {
  profile=${1:-sso}
  url=$(aws configure get sso_start_url --profile "$profile")
  now_epoch=$(/opt/homebrew/bin/gdate +%s)
  max_expiry_epoch=0

  for file in ~/.aws/sso/cache/*.json; do
    if grep -q "$url" "$file" 2>/dev/null; then
      file_expiry=$(jq -r '.expiresAt // empty' "$file" 2>/dev/null)
      if [ -n "$file_expiry" ]; then
        file_expiry_epoch=$(/opt/homebrew/bin/gdate -u -d "$file_expiry" +%s 2>/dev/null)
        [ $? -eq 0 ] && [ "$file_expiry_epoch" -gt "$max_expiry_epoch" ] && max_expiry_epoch=$file_expiry_epoch
      fi
    fi
  done

  if [ "$max_expiry_epoch" -eq 0 ]; then
    echo "No valid session found for profile $profile"
    return 1
  fi

  remaining=$((max_expiry_epoch - now_epoch))

  if (( remaining > 0 )); then
    echo "Session for [$profile] expires in: $(/opt/homebrew/bin/gdate -ud "@$remaining" +'%H hours %M minutes %S seconds')"
  else
    echo "Session has already expired."
  fi
}

aws-remind() {
  echo "aws-sso-util: A really handy python wrapper for aws sso login!"
  echo "aws-sso util: Install with pip\n\nUsage:"
  echo "aws-sso-util login --profile sso"
  echo "aws-sso-util configure populate -u <AWS-access-portal-URL> --region <IAM-Identity-Center-region>"
  echo "aws-pick # Select a profile to use"
}
Enter fullscreen mode Exit fullscreen mode

After adding the functions, reload your shell config:

source ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

Or on macOS:

source ~/.zshrc
Enter fullscreen mode Exit fullscreen mode

Step 3: Install the Required Tools

These functions depend on a few utilities. Let's install them.

Install Fzf

Fzf is the fuzzy finder that powers the account selection menu.

On Ubuntu/Debian:

sudo apt install fzf
Enter fullscreen mode Exit fullscreen mode

On macOS:

brew install fzf
Enter fullscreen mode Exit fullscreen mode

Install jq

This tool helps parse JSON data from the AWS cache files.

On Ubuntu/Debian:

sudo apt install jq
Enter fullscreen mode Exit fullscreen mode

On macOS:

brew install jq
Enter fullscreen mode Exit fullscreen mode

Install AWS CLI

If you don't have it already:

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
Enter fullscreen mode Exit fullscreen mode

For other platforms, check the AWS CLI installation guide.

Install aws-sso-util

This tool makes SSO management much easier. I recommend installing it in a virtual environment:

python -m venv venv
source venv/bin/activate
pip install aws-sso-util
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure Your AWS SSO Profiles

Navigate to your AWS config directory:

cd ~/.aws/
Enter fullscreen mode Exit fullscreen mode

Create or edit the config file:

vim config
Enter fullscreen mode Exit fullscreen mode

Add your SSO profile. Replace the example values with your actual AWS Access Portal URL, region, and account ID:

[profile sso]
sso_start_url = https://d-11111aaa22.awsapps.com/start
sso_region = us-east-1
sso_account_id = 111112222255
sso_registration_scopes = sso:account:access
Enter fullscreen mode Exit fullscreen mode

If you work with multiple AWS organizations (like separate prod and dev orgs), add additional profiles:

[profile sso-dev]
sso_start_url = https://d-22222aaa33.awsapps.com/start
sso_region = eu-west-2
sso_account_id = 222224444466
sso_registration_scopes = sso:account:access
Enter fullscreen mode Exit fullscreen mode

A quick note: the account ID here is usually your organization's management account, and the region is wherever you're hosting IAM Identity Center.

Save and exit (in vim, hit Esc, type :wq, and press Enter).

Step 5: Populate Your Available Accounts

Now for the magic part. Run this command to automatically populate all the AWS accounts you have access to:

aws-sso-util configure populate -u https://d-11111aaa22.awsapps.com/start --region us-east-1
Enter fullscreen mode Exit fullscreen mode

If you have multiple organizations:

aws-sso-util configure populate -u https://d-22222aaa33.awsapps.com/start --region eu-west-2
Enter fullscreen mode Exit fullscreen mode

This command reaches out to IAM Identity Center and adds all your accessible accounts to the config file. Pretty neat.

AWS SSO authorization with device code

Step 6: Log Into IAM Identity Center

Time to authenticate. Run:

aws-sso-util login --profile sso
Enter fullscreen mode Exit fullscreen mode

For a second organization:

aws-sso-util login --profile sso-dev
Enter fullscreen mode Exit fullscreen mode

AWS SSO authorization with device code

Your browser will pop open with an authorization page:

Click "Confirm and Continue":

AWS SSO page with Allow access button

That's it. You're logged in, and this session will last for hours (typically 8-12 hours depending on your org's settings).

Step 7: Switch Between Accounts

Here's where it gets really convenient. Just run:

aws-pick
Enter fullscreen mode Exit fullscreen mode

You'll see an interactive menu like this:

Start typing to filter accounts, use arrow keys to navigate, and hit Enter to select:

Fzf menu showing list of AWS accounts

The selected account becomes your active profile. All AWS CLI commands will now run against that account. Need to switch? Just run aws-pick again.

Checking Your Session Status

Wondering how much time you have left before you need to re-authenticate?

aws-session-remaining
Enter fullscreen mode Exit fullscreen mode

You'll see something like:

Session for [sso] expires in: 08 hours 45 minutes 30 seconds
Enter fullscreen mode Exit fullscreen mode

Quick Reference

Forgot the commands? Just run:

aws-remind
Enter fullscreen mode Exit fullscreen mode

It'll show you everything you need.

Troubleshooting

"Session has already expired"

Just log in again:

aws-sso-util login --profile sso
Enter fullscreen mode Exit fullscreen mode

No profiles showing up in aws-pick

Make sure you ran the populate command:

aws-sso-util configure populate -u <your-portal-url> --region <your-region>
Enter fullscreen mode Exit fullscreen mode

Shell functions not working

Reload your config:

source ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

Or just open a new terminal.

Wrapping Up

That's it. You now have a much smoother workflow for managing multiple AWS accounts. Instead of constantly copying and pasting credentials, you log in once and switch between accounts with a simple command.

I've been using this setup for a while now, and it's made working with multiple AWS accounts so much less painful. The aws-pick command alone saves me probably 30 minutes a day.

If this helped you out, share it with your teammates who are dealing with the same credential juggling act.

Top comments (0)