Last active
July 10, 2024 15:05
-
-
Save baztian/7183e83f265862dfba92c3cbf7bb84b4 to your computer and use it in GitHub Desktop.
Allows selecting an aws profile and logs into the account via sso
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
PROFILE="$1" | |
if [ -z "$PROFILE" ]; then | |
PROFILE=$(aws-list-sso-profiles|fzf --preview "sed -n \"/\[profile \"{}\"/,/^\[/ { /^\[/!p; }\" ~/.aws/config | sed \"\$d\"") | |
if [ -z "$PROFILE" ]; then | |
echo No profile selected. Exiting. >&2 | |
return 1 | |
fi | |
fi | |
bold=$(tput bold) | |
normal=$(tput sgr0) | |
printf "Logging in to AWS pro file %s%s%s\n" "$bold" "$PROFILE" "$normal" | |
if ! aws sso login --profile "$PROFILE"; then | |
echo "AWS SSO login failed. Exiting." >&2 | |
return 1 | |
fi | |
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}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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())) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_sso_completions() | |
{ | |
COMPREPLY=($(compgen -W "$(aws-list-sso-profiles)" -- "${COMP_WORDS[1]}")) | |
} | |
complete -F _sso_completions sso |
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
Prerequisite: fzf needs to be installed
Recommended use is to set up an alias in
.bashrc
Now you can use it like this: