-
-
Save devmvallejo/c82814c4fe0767b37d94c05620fe50fa to your computer and use it in GitHub Desktop.
This script help to get the aws sso tokens and set them to windows environment variable
This file contains 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
import glob | |
import json | |
import os | |
import sys | |
defaultProfile = 'default' | |
ENV_VAR_NAMES = { | |
'access_key': 'AWS_ACCESS_KEY_ID', | |
'secret_key': 'AWS_SECRET_ACCESS_KEY', | |
'session_token': 'AWS_SESSION_TOKEN', | |
'profile': 'AWS_PROFILE' | |
} | |
def get_keys_from_file(): | |
# Get the credential file | |
home = os.path.expanduser('~') | |
path = os.path.join(home, '.aws','cli','cache','*.json') | |
files = glob.glob(path) | |
if(len(files) == 0): | |
print('No config file found') | |
return | |
credential_file = files[0] | |
# Read the JSON file content | |
with open(credential_file) as f: | |
data = json.load(f) | |
credentials = data['Credentials'] | |
access_key = credentials['AccessKeyId'] | |
secret_key = credentials['SecretAccessKey'] | |
session_token = credentials['SessionToken'] | |
return { | |
ENV_VAR_NAMES['access_key']: access_key, | |
ENV_VAR_NAMES['secret_key']: secret_key, | |
ENV_VAR_NAMES['session_token']: session_token | |
} | |
def set_env_variable(env_var, env_val, system=False): | |
os.system("SETX {0} {1} {2}".format(env_var,env_val,('/M' if system else ''))) | |
def awscreds(): | |
profile = defaultProfile | |
# Get the profile name from argument (optional) | |
args = sys.argv | |
if(len(args) > 1): | |
arg_profile = args[1] | |
if(len(arg_profile) > 0): | |
profile = arg_profile | |
print(f'Configuring profile {profile}..') | |
# Login the user into aws | |
os.system(f"aws sts get-caller-identity --profile {profile} || aws sso login --profile {profile}") | |
keys = get_keys_from_file() | |
# Setting the environment variables | |
set_env_variable(ENV_VAR_NAMES['access_key'], keys[ENV_VAR_NAMES['access_key']]) | |
set_env_variable(ENV_VAR_NAMES['secret_key'], keys[ENV_VAR_NAMES['secret_key']]) | |
set_env_variable(ENV_VAR_NAMES['session_token'], keys[ENV_VAR_NAMES['session_token']]) | |
set_env_variable(ENV_VAR_NAMES['profile'], 'default') | |
if __name__ == '__main__': | |
awscreds() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment