-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaws-credy.py
147 lines (125 loc) · 4.44 KB
/
aws-credy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import configparser
import json
import os
import subprocess
import sys
import click
aws_executable = "/usr/local/bin/aws"
creds = configparser.ConfigParser()
file_path = os.path.expanduser("~/.aws/credentials")
creds.read(file_path)
@click.command()
@click.option("--profile", "-p", help="Name of AWS profile as listed in ~/.aws/config")
def main(profile):
if not profile:
return
sso_start_url, sso_region, sso_account_id, sso_role_name = get_sso_params(profile)
access_token = get_access_token(sso_start_url, sso_region, profile)
profile_access_key, profile_secret_key, profile_token = get_role_credentials(
access_token, sso_account_id, sso_role_name, sso_region, profile
)
if profile in creds:
creds.remove_section(profile)
add_profile(profile, profile_access_key, profile_secret_key, profile_token)
save_file()
click.echo(f"Credentials for {profile} updated.")
else:
add_profile(profile, profile_access_key, profile_secret_key, profile_token)
save_file()
click.echo(f"Credentials for {profile} added to credentials file.")
def get_sso_params(profile):
section = f"profile {profile}"
config_path = os.path.expanduser("~/.aws/config")
config = configparser.ConfigParser()
config.read(config_path)
sso_start_url = config[section]["sso_start_url"]
sso_region = config[section]["sso_region"]
sso_account_id = config[section]["sso_account_id"]
sso_role_name = config[section]["sso_role_name"]
return sso_start_url, sso_region, sso_account_id, sso_role_name
def get_access_token(sso_start_url, sso_region, profile):
sso_path = os.path.expanduser("~/.aws/sso/cache")
files = os.listdir(sso_path)
for f in files:
if (
f.endswith(".json")
and len(f.split(".")[0]) == 40
and int(f.split(".")[0], 16)
):
ff = open(f"{sso_path}/{f}", "r")
contents = ff.readline()
ff.close()
if (
json.loads(contents)["startUrl"] == sso_start_url
and json.loads(contents)["region"] == sso_region
):
return json.loads(contents)["accessToken"]
login(profile)
return get_access_token(sso_start_url, sso_region, profile)
def login(profile):
subprocess.run(
[aws_executable, "sso", "login", "--profile", profile],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
def get_role_credentials(access_token, account_id, role_name, region, profile):
process = subprocess.run(
[
aws_executable,
"sso",
"get-role-credentials",
"--access-token",
access_token,
"--account-id",
account_id,
"--role-name",
role_name,
"--region",
region,
"--profile",
profile,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if "UnauthorizedException" in process.stderr.decode(encoding="utf-8"):
login(profile)
subprocess.run(
[
aws_executable,
"sso",
"get-role-credentials",
"--access-token",
access_token,
"--account-id",
account_id,
"--role-name",
role_name,
"--region",
region,
"--profile",
profile,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
elif len(process.stderr.decode(encoding="utf-8")) > 1:
sys.tracebacklimit = 0
raise Exception(process.stderr.decode(encoding="utf-8"))
else:
output = process.stdout.decode(encoding="utf-8")
creds = json.loads(output)
access_key = creds["roleCredentials"]["accessKeyId"]
secret_key = creds["roleCredentials"]["secretAccessKey"]
session_token = creds["roleCredentials"]["sessionToken"]
return access_key, secret_key, session_token
def save_file():
with open(file_path, "w") as credsfile:
creds.write(credsfile)
def add_profile(profile, access_key, secret_key, session_token):
creds.add_section(profile)
creds[profile]["aws_access_key_id"] = access_key
creds[profile]["aws_secret_access_key"] = secret_key
creds[profile]["aws_session_token"] = session_token
if __name__ == "__main__":
main()