Skip to content

Instantly share code, notes, and snippets.

@baztian
Last active April 16, 2024 21:17
Show Gist options
  • Save baztian/7183e83f265862dfba92c3cbf7bb84b4 to your computer and use it in GitHub Desktop.
Save baztian/7183e83f265862dfba92c3cbf7bb84b4 to your computer and use it in GitHub Desktop.
Allows selecting an aws profile and logs into the account via sso
#!/bin/sh
PROFILE="$1"
if [ -z "$PROFILE" ]; then
PROFILE=$(aws-list-sso-profiles|fzf)
if [ -z "$PROFILE" ]; then
echo No profile selected. Exiting. > /dev/stderr
return
fi
fi
aws sso login --profile "$PROFILE"
export AWS_PROFILE="$PROFILE"
unset AWS_SECRET_ACCESS_KEY
unset AWS_CREDENTIAL_EXPIRATION
unset AWS_SESSION_TOKEN
eval "$(aws configure export-credentials --profile "$AWS_PROFILE" --format env)"
aws configure set aws_access_key_id "${AWS_ACCESS_KEY_ID}" --profile "${AWS_PROFILE}"
aws configure set aws_secret_access_key "${AWS_SECRET_ACCESS_KEY}" --profile "${AWS_PROFILE}"
aws configure set aws_session_token "${AWS_SESSION_TOKEN}" --profile "${AWS_PROFILE}"
#!/usr/bin/env python3
import re
import os
def find_sso_profiles():
config_path = os.path.expanduser('~/.aws/config')
with open(config_path, 'r') as file:
config_content = file.read()
sections = re.finditer(r'\[profile\s+(.*?)\](.*?)(?=\n\[|$)', config_content, re.DOTALL)
return [m.group(1) for m in sections if 'sso_start_url' in m.group(2)]
if __name__ == "__main__":
print('\n'.join(find_sso_profiles()))
_sso_completions()
{
COMPREPLY=($(compgen -W "$(aws-list-sso-profiles)" -- "${COMP_WORDS[1]}"))
}
complete -F _sso_completions sso
@baztian
Copy link
Author

baztian commented Apr 4, 2024

Prerequisite: fzf needs to be installed

Recommended use is to set up an alias in .bashrc

alias sso='. _aws-sso.sh'

Now you can use it like this:

$ sso
<dialog to choose profile from>
$ sso <TAB>
$ sso your-<TAB>
your-profile-one        your-profile-two      ....
$ sso your-profile-one
$ aws s3 ls
...

@baztian
Copy link
Author

baztian commented Apr 4, 2024

If you don't want to install it manually you could also consider using the ansible module https://galaxy.ansible.com/baztian/aws.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment