-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaliasrc
242 lines (205 loc) · 6.57 KB
/
aliasrc
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# vim: filetype=zsh
alias dotf='cd $HOME/.dotfiles'
alias la='ls -a'
alias ll='ls -l'
alias l.='ls -d .*'
alias lrt='ll -rt'
alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'
alias mkdir='mkdir -p'
alias ..='cd ..'
alias g='git'
alias k='kubectl'
alias mux='tmuxinator'
alias tf='terraform'
if [[ -v VI ]]; then
alias vi=$VI
fi
if [[ "$OSTYPE" == darwin* ]]; then
alias ls='ls -G'
export LSCOLORS=gxfxcxdxbxegedabagacad
fi
tox() {
if [[ -z "$TOX_PATH" && -x $(command -v pyenv) ]]; then
for pyv in $(pyenv versions --bare); do
TOX_PATH="$TOX_PATH:$(pyenv prefix $pyv)/bin"
done
fi
export TOX_PATH=$TOX_PATH
env PATH=$TOX_PATH:$PATH tox $@
}
aws-profile() {
read -r -d '' SCRIPT <<'EOF'
import argparse
from configparser import RawConfigParser
import os
import shutil
import subprocess
import sys
from textwrap import dedent
# interactive output needs to be over stderr to avoid being captured
# by the bash script looking for a profile name on stdout
out = lambda *a, **kw: print(*a, **kw, file=sys.stderr)
def parse_profiles():
config_profile_prefix = 'profile '
config_path = os.path.expanduser('~/.aws/config')
config = RawConfigParser()
config.read(config_path)
profiles = []
for section in config.sections():
if section.startswith(config_profile_prefix):
profile = section[len(config_profile_prefix):]
profiles.append(profile)
return profiles
def select_profile_manual(profiles, current_profile=None):
out('--- Choose AWS profile ---')
for idx, profile in enumerate(profiles, 1):
suffix = ' ** current **' if profile == current_profile else ''
out(f'{idx}: {profile}{suffix}')
out()
while True:
out(f'Pick one: [1-{len(profiles)}] ', end='')
choice = input().strip()
try:
if not choice and current_profile:
return current_profile
if choice == 'q':
sys.exit(0)
choice = int(choice) - 1
if not 0 <= choice < len(profiles):
raise Exception
except Exception:
out('Unrecognized option, try again.')
else:
break
return profiles[choice]
def select_profile_fzf(profiles, current_profile=None):
args = ['fzf', '--height', '40%']
if current_profile is not None:
try:
idx = profiles.index(current_profile)
# pull the current profile to the front of the list so that
# it's the default selection
profiles = [profiles[idx]] + profiles[:idx] + profiles[idx + 1 :]
except ValueError:
pass
in_profiles = '\n'.join(profiles)
p = subprocess.run(args, input=in_profiles, text=True, stdout=subprocess.PIPE)
if p.returncode != 0:
return
# the selected profile should be the last line in the output
profile = p.stdout.strip().split()[-1].strip()
return profile
def parse_args():
try:
args = sys.argv[sys.argv.index('--') + 1:]
except IndexError:
args = sys.argv[1:]
parser = argparse.ArgumentParser(prog='aws-profile', add_help=False)
parser.add_argument('-h', '--help', action='store_true')
parser.add_argument('-c', '--current', action='store_true')
parser.add_argument('--unset', action='store_true')
parser.add_argument('profile', nargs='?')
args = parser.parse_args(args)
# take over help so that we can use stderr and exit with an error
# to avoid the output being eval'd
if args.help:
parser.print_help(file=sys.stderr)
raise SystemExit(1)
return args
def main():
args = parse_args()
current_profile = os.getenv('AWS_PROFILE', '')
if args.current:
out(f'Current AWS_PROFILE={current_profile}')
return 1
if args.unset:
print(dedent(
'''
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
unset AWS_PROFILE
unset AWS_DEFAULT_PROFILE
'''
))
return 0
profile = args.profile
if not profile:
profiles = parse_profiles()
if not profiles:
out('No profiles found in ~/.aws/config')
return 1
if shutil.which('fzf') is None:
profile = select_profile_manual(profiles, current_profile)
else:
profile = select_profile_fzf(profiles, current_profile)
if profile is None:
out(f'No profile selected.')
return 1
args = ['aws', 'configure', 'list']
env = {**dict(os.environ), 'AWS_PROFILE': profile}
p = subprocess.run(args, capture_output=True, text=True, env=env)
stderr = p.stderr.lower()
if p.returncode != 0 and (
'error loading sso token' in stderr
or 'error when retrieving token' in stderr
or 'sso session associated with this profile has expired' in stderr
):
out('Session is invalid, triggering an SSO login ...')
args = ['aws', 'sso', 'login', '--no-browser']
p = subprocess.run(args, stdout=sys.stderr, env=env, text=True)
if p.returncode != 0:
raise SystemExit(1)
elif p.returncode != 0:
out(p.stderr)
raise SystemExit(p.returncode)
out(f'Activated AWS_PROFILE={profile}')
print(dedent(
f'''
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
export AWS_PROFILE={profile}
export AWS_DEFAULT_PROFILE={profile}
'''
))
return 0
if __name__ == '__main__':
try:
raise SystemExit(main())
except KeyboardInterrupt:
raise SystemExit(1)
EOF
result=$(python3 -c "$SCRIPT" -- "$@")
rc=$?
if [ $rc -ne 0 ]; then
return $rc
fi
eval "$result"
}
alias ap=aws-profile
alias kp=switch
function curlt {
curl -w "\
namelookup: %{time_namelookup}s\n\
connect: %{time_connect}s\n\
appconnect: %{time_appconnect}s\n\
pretransfer: %{time_pretransfer}s\n\
redirect: %{time_redirect}s\n\
starttransfer: %{time_starttransfer}s\n\
time_total: %{time_total}s\n\
size_header: %{size_header} bytes\n\
size_download: %{size_download} bytes\n\
speed_download: %{speed_download} bytes/sec\n\
speed_upload: %{speed_upload} bytes/sec\n\
---------------\n\
total: %{time_total}s\n" "$@"
}
function urlencode {
python3 -c 'import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.readline()), end="")'
}
function urldecode {
python3 -c 'import urllib.parse, sys; print(urllib.parse.unquote(sys.stdin.readline()), end="")'
}