-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathawsctx
More file actions
executable file
·1551 lines (1357 loc) · 47 KB
/
Copy pathawsctx
File metadata and controls
executable file
·1551 lines (1357 loc) · 47 KB
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
set -euo pipefail
# This script generates AWS profiles for all accounts and roles associated with an AWS SSO profile.
# It also lets you switch between AWS accounts and roles using the 'awsctx' command with no arguments.
# This probably works best if you just remove your existing AWS config file and start fresh with 'awsctx -i'.
VERSION="0.1.0"
GITHUB_REPO="wallentx/awsctx"
# Check for color support
if ! tput colors >/dev/null 2>&1; then
echo "Warning: Your terminal doesn't support colors. Some features may not display correctly."
# Define color variables as empty strings
rd=gr=yl=bl=mg=cy=wh=gy=or=it=bd=nc=""
else
# Colors
rd=$(tput setaf 1) # Red
gr=$(tput setaf 2) # Green
yl=$(tput setaf 3) # Yellow
bl=$(tput setaf 4) # Blue
mg=$(tput setaf 5) # Magenta
cy=$(tput setaf 6) # Cyan
wh=$(tput setaf 7) # White
gy=$(tput setaf 8) # Gray
or=$(tput setaf 208) # Orange
it=$(tput sitm) # Italic
bd=$(tput bold) # Bold
nc=$(tput sgr0) # No Color / Reset
fi
# Unified message handling function
msg() {
local class="$1"
local message="$2"
local extra="${3:-}" # Used for default value, icon, or other extras
local response
case "$class" in
"header") echo "${bd}${mg}$message${nc}" ;;
"success") echo "${gr}$message${extra:+ $extra}${nc}" ;;
"warning") echo "${yl}$message${extra:+ $extra}${nc}" ;;
"error") echo "${rd}$message${extra:+ $extra}${nc}" ;;
"info") echo "${wh}$message${nc}" ;;
"help") echo "${gy}$message${nc}" ;;
"example") echo "${gy}${it}$message${nc}" ;;
"code") echo "${bl}$message${nc}" ;;
"highlight") echo "${or}$message${nc}" ;;
"section") echo "${cy}$message${nc}" ;;
"status") echo "${gy}$message${extra:+ $extra}${nc}" ;;
# Interactive prompts
"question")
local default="${extra:-}"
local prompt
# Format based on default value
if [[ ${default,,} == "n" ]]; then
prompt="${mg}$message ${bl}[${gr}y${bl}/${rd}N${bl}]${nc}"
elif [[ ${default,,} == "y" ]]; then
prompt="${mg}$message ${bl}[${gr}Y${bl}/${rd}n${bl}]${nc}"
else
prompt="${mg}$message ${bl}[${gr}y${bl}/${rd}n${bl}]${nc}"
fi
while true; do
echo -n "$prompt: "
read -r response
# Handle empty response
if [[ -z $response ]]; then
[[ -n $default ]] && response="$default" && break
continue
fi
# Handle valid responses
if [[ ${response,,} =~ ^[yn]$ ]]; then
break
fi
echo -e "${rd}Please answer y or n${nc}"
done
[[ ${response,,} =~ ^y ]]
return $?
;;
"input")
printf "${mg}%s${nc}: " "$message" >&2
read -r response
echo "$response"
;;
"input_default")
printf "${mg}%s ${bl}[${wh}%s${bl}]${nc}: " "$message" "$extra" >&2
read -r response
echo "${response:-$extra}"
;;
"select")
local -a options=("${@:3}") # Get all args after class and message
# Display the menu to stderr
for i in "${!options[@]}"; do
printf '%s%d%s %s%s\n' "${bl}" "$((i + 1))" "${gy})" "${wh}${options[$i]}" "${nc}" >&2
done
# Get selection
printf '%s%s%s: ' "${mg}" "$message" "${nc}" >&2
read -r selection
# Validate and return selection
if [[ $selection =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le "${#options[@]}" ]; then
echo "${options[$((selection - 1))]}"
return 0
else
printf '%s%s%s\n' "${rd}" "Invalid selection." "${nc}" >&2
msg "select" "$message" "${options[@]}"
fi
;;
*) echo "$message" ;;
esac
}
# Aliases for common message types (optional, for convenience)
code() { msg "code" "$1"; }
highlight() { msg "highlight" "$1"; }
error() { msg "error" "$1" "${2:-}"; }
warn() { msg "warning" "$1" "${2:-}"; }
info() { msg "info" "$1"; }
success() { msg "success" "$1" "${2:-}"; }
ask() { msg "question" "$1" "${2:-}"; }
prompt() { msg "input" "$1"; }
prompt_default() { msg "input_default" "$1" "$2"; }
select_option() { msg "select" "$1" "${@:2}"; }
title() { msg "header" "$1"; }
option() { msg "code" "$1"; }
section() { msg "section" "$1"; }
example() { msg "example" "$1"; }
# Initialize variables
DEBUG=false
CONTEXT_READY="false"
GENERATE_CONFIG="false"
OUTPUT_FORMAT=""
BROWSER_OVERRIDE=""
CLI_PAGER=""
# Declare global associative array for region counts
declare -A region_counts
get_config_dir() {
# First check if ~/.config exists
if [[ -d "${HOME}/.config" ]]; then
echo "${HOME}/.config/awsctx"
else
# Fall back to ~/.awsctxrc
echo "${HOME}"
fi
}
get_config_file() {
local config_dir
config_dir=$(get_config_dir)
if [[ $config_dir == "${HOME}" ]]; then
echo "${HOME}/.awsctxrc"
else
echo "${config_dir}/awsctxrc"
fi
}
load_config() {
local config_file
config_file=$(get_config_file)
local config_dir
config_dir=$(dirname "$config_file")
if [[ ! -f $config_file ]]; then
error "AWS Context configuration file not found at: $config_file"
info "Would you like to create a new configuration file?"
if ask "Create config file?"; then
create_config "$config_file"
else
error "Configuration file is required to run awsctx. Exiting..." "😢"
exit 1
fi
fi
# Check if config file is readable
if [[ ! -r $config_file ]]; then
error "Config file exists but is not readable: $config_file" "😢"
exit 1
fi
# Source the config file
if [[ -f $config_file ]]; then
# shellcheck source=/dev/null
source "$config_file"
else
error "Failed to load config file: $config_file" "😢"
exit 1
fi
# Validate required variables
if [[ -z ${SSO_START_URL:-} ]] || [[ -z ${SSO_REGION:-} ]] ||
[[ -z ${SSO_REGISTRATION_SCOPES:-} ]] || [[ -z ${CROSS_ACCOUNT_PROFILE:-} ]] ||
[[ -z ${OUTPUT_FORMAT:-} ]]; then
error "Config file is missing required variables" "😕"
warn "Please ensure all required variables are set in: $config_file"
info "Would you like to update the configuration file?"
if ask "Update config file?"; then
create_config "$config_file"
else
error "Configuration file is required to run awsctx. Exiting..." "😢"
exit 1
fi
fi
# Basic format check for region (just to catch obvious typos)
if [[ ! $SSO_REGION =~ ^[a-z]{2}-[a-z]+-[0-9]{1}$ ]]; then
error "Invalid AWS region format in config file: $SSO_REGION" "⚠️"
info "Region should be in the format: us-east-1, eu-west-2, etc."
exit 1
fi
}
create_config() {
local config_file="$1"
local config_dir
config_dir=$(dirname "$config_file")
info "Creating AWS Context configuration file..."
info "This will help you set up your AWS SSO configuration."
info "You can get these values from your AWS IAM administrator."
echo
# Create config directory if it doesn't exist
if [[ $config_dir != "${HOME}" ]]; then
mkdir -p "$config_dir"
fi
# Prompt for SSO Directory ID
while true; do
code "AWS SSO Directory ID"
info "This is your AWS SSO directory ID"
code "Format: d-xxxxxxxx"
example "Example: d-a1b2c3d4e5"
info "You can find this in your AWS SSO console under 'Directory ID'"
if [[ -n ${SSO_START_URL:-} ]]; then
# Extract just the directory ID from the full URL if needed
local default_id
if [[ $SSO_START_URL =~ ^https:// ]]; then
default_id=$(echo "$SSO_START_URL" | sed -E 's|https://([^.]+)\.awsapps\.com/start|\1|')
else
default_id="$SSO_START_URL"
fi
input=$(prompt_default "Enter Directory ID" "$default_id")
SSO_START_URL=${input}
else
SSO_START_URL=$(prompt "Enter Directory ID")
fi
echo
if [[ $SSO_START_URL =~ ^[a-zA-Z0-9-]+$ ]]; then
# Construct the full SSO start URL
SSO_START_URL="https://${SSO_START_URL}.awsapps.com/start"
break
else
error "Invalid format. Please enter only alphanumeric characters and hyphens"
fi
done
# Prompt for SSO_REGION
while true; do
code "AWS Region"
info "This is the AWS region where your SSO is configured"
highlight "Example: us-east-1"
if [[ -n ${SSO_REGION:-} ]]; then
input=$(prompt_default "Enter AWS Region" "$SSO_REGION")
SSO_REGION=${input}
else
SSO_REGION=$(prompt "Enter AWS Region")
fi
echo
if [[ $SSO_REGION =~ ^[a-z]{2}-[a-z]+-[0-9]{1}$ ]]; then
break
else
error "Invalid region format. Please enter a region in the format: us-east-1, eu-west-2, etc."
fi
done
# Prompt for SSO_REGISTRATION_SCOPES
code "SSO Registration Scopes"
info "This is the SSO permission scope for your AWS account"
highlight "Example: sso:account:access"
if [[ -n ${SSO_REGISTRATION_SCOPES:-} ]]; then
input=$(prompt_default "Enter SSO Registration Scopes" "$SSO_REGISTRATION_SCOPES")
SSO_REGISTRATION_SCOPES=${input}
else
SSO_REGISTRATION_SCOPES=$(prompt "Enter SSO Registration Scopes")
fi
echo
# Prompt for CROSS_ACCOUNT_PROFILE
code "Cross Account Profile"
info "This is the name of the AWS profile that will be used to assume roles in other accounts"
highlight "Example: cross-account-access"
if [[ -n ${CROSS_ACCOUNT_PROFILE:-} ]]; then
input=$(prompt_default "Enter Cross Account Profile name" "$CROSS_ACCOUNT_PROFILE")
CROSS_ACCOUNT_PROFILE=${input}
else
CROSS_ACCOUNT_PROFILE=$(prompt "Enter Cross Account Profile name")
fi
echo
# Prompt for OUTPUT_FORMAT
code "AWS CLI Output Format"
info "This is the default output format for AWS CLI commands"
highlight "Example: json, text, table, yaml, yaml-stream"
# Define options for output format selection
local output_options=(
"json"
"text"
"table"
"yaml"
"yaml-stream"
)
# Use fzf to get user's choice
local selected_format
selected_format=$(select_option "Select output format" "${output_options[@]}")
if [[ -n $selected_format ]]; then
OUTPUT_FORMAT="$selected_format"
else
error "No output format selected. Using default: json" "⚠️"
OUTPUT_FORMAT="json"
fi
success "Output format selected: $OUTPUT_FORMAT" "✅"
# Ask about CLI pager preference
if ask "Would you like to set a CLI pager for AWS output?"; then
info "Common pager options:"
# Define options for pager selection
local pager_options=(
"bat -Ppl yaml (Syntax highlighted output - requires bat)"
"less (Standard pager)"
"more (Simple pager)"
"custom (Enter your own pager command)"
)
# Use fzf to get user's choice
local selected_pager
selected_pager=$(select_option "Select pager" "${pager_options[@]}")
case "$selected_pager" in
"bat -Ppl yaml (Syntax highlighted output - requires bat)")
# Check if bat is installed
if ! command -v bat &>/dev/null; then
error "bat is not installed. Please install bat to use this option." "⚠️"
info "https://github.com/sharkdp/bat#installation"
CLI_PAGER=""
else
CLI_PAGER="bat -Ppl yaml"
fi
;;
"less (Standard pager)")
CLI_PAGER="less"
;;
"more (Simple pager)")
CLI_PAGER="more"
;;
"custom (Enter your own pager command)")
CLI_PAGER=$(prompt "Enter your custom pager command")
;;
*)
warn "Invalid selection. No pager will be set." "⚠️"
CLI_PAGER=""
;;
esac
fi
# Write config file
cat >"$config_file" <<EOF
# AWS Context Manager Configuration
# This file contains your AWS SSO configuration
# You can modify these values at any time
SSO_START_URL="$SSO_START_URL"
SSO_REGION="$SSO_REGION"
SSO_REGISTRATION_SCOPES="$SSO_REGISTRATION_SCOPES"
CROSS_ACCOUNT_PROFILE="$CROSS_ACCOUNT_PROFILE"
OUTPUT_FORMAT="$OUTPUT_FORMAT"
CLI_PAGER="$CLI_PAGER"
EOF
success "Configuration file created successfully at: $config_file" "✅"
info "You can edit this file at any time to update your configuration."
}
check_command() {
local cmd=$1
local url=$2
if ! command -v "$cmd" &>/dev/null; then
error "The '$cmd' command could not be found" "🤷♂️"
info "Please install '$cmd' from $url"
exit 1
fi
}
check_bash_version() {
local major_version=${BASH_VERSION%%.*}
if [[ $major_version -lt 5 ]]; then
error "Bash version 5 or higher is required" "🏚️"
info "You are currently running Bash version $BASH_VERSION"
info "Please upgrade your Bash installation"
info "On macOS, you can use: brew install bash"
info "On Linux, use your distribution's package manager"
exit 1
fi
}
check_aws_cli_v2() {
if ! command -v aws &>/dev/null; then
error "The 'aws' command could not be found" "🤷♂️"
info "Please install AWS CLI v2 from https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html"
exit 1
fi
local version
version=$(aws --version 2>&1)
if [[ $version != aws-cli/2* ]]; then
error "AWS CLI v2 is required" "🏚️"
info "Please install it from https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html"
exit 1
fi
}
# Check dependencies
check_bash_version
check_command "jq" "https://github.com/jqlang/jq"
check_command "fzf" "https://github.com/junegunn/fzf"
check_aws_cli_v2
# Set up debug mode if enabled
if [[ $DEBUG == "true" ]]; then
set -x
PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
fi
# Load configuration
load_config
AWS_CONFIG_HOME="${HOME}/.aws"
AWS_CONFIG_FILE="${AWS_CONFIG_HOME}/config"
SSO_CACHE_DIR="${AWS_CONFIG_HOME}/sso/cache"
KUBE_HOME="${HOME}/.kube"
CURRENT_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u "+%Y-%m-%dT%H:%M:%SZ")
[[ ! -d ${AWS_CONFIG_HOME} ]] && mkdir -p "${AWS_CONFIG_HOME}"
[[ ! -e ${AWS_CONFIG_FILE} ]] && touch "${AWS_CONFIG_FILE}"
# Create temporary files with better error handling
create_temp_file() {
local temp_file
temp_file=$(mktemp "${AWS_CONFIG_HOME}/$1.XXXXXX" 2>/dev/null)
if [[ -z $temp_file ]]; then
error "Failed to create temporary file for $1" "😢"
exit 1
fi
echo "$temp_file"
}
AWS_CONFIG_PROFILES=$(create_temp_file "AWS_CONFIG_PROFILES")
ACCOUNTS_LIST=$(create_temp_file "ACCOUNTS_LIST")
ACCOUNTS_ROLES=$(create_temp_file "ACCOUNTS_ROLES")
CTX_CONFIG=$(create_temp_file "CTX_CONFIG")
TMP_ROLES=$(create_temp_file "TMP_ROLES")
WRITE_TMP=$(create_temp_file "WRITE_TMP")
SPINTMP=$(create_temp_file "SPINTMP")
REGION_COUNTS=$(create_temp_file "aws_region_counts")
SESSION_BLOCK=$(
cat <<-EOF
[sso-session awsctx]
sso_start_url = $SSO_START_URL
sso_region = $SSO_REGION
sso_registration_scopes = $SSO_REGISTRATION_SCOPES
sso_client_name = awsctx
sdk_ua_app_id = awsctx
role_session_name = ${USER}_awsctx
EOF
)
cleanup_temp_files() {
[[ -n $ACCOUNTS_LIST && -f $ACCOUNTS_LIST ]] && rm -f "$ACCOUNTS_LIST"
[[ -n $ACCOUNTS_ROLES && -f $ACCOUNTS_ROLES ]] && rm -f "$ACCOUNTS_ROLES"
[[ -n $CTX_CONFIG && -f $CTX_CONFIG ]] && rm -f "$CTX_CONFIG"
[[ -n $TMP_ROLES && -f $TMP_ROLES ]] && rm -f "$TMP_ROLES"
[[ -n $WRITE_TMP && -f $WRITE_TMP ]] && rm -f "$WRITE_TMP"
[[ -n $AWS_CONFIG_PROFILES && -f $AWS_CONFIG_PROFILES ]] && rm -f "$AWS_CONFIG_PROFILES"
[[ -n $SPINTMP && -f $SPINTMP ]] && rm -f "$SPINTMP"
[[ -n $REGION_COUNTS && -f $REGION_COUNTS ]] && rm -f "$REGION_COUNTS"
}
shutdown() {
tput cnorm
cleanup_temp_files
# Kill any background processes
jobs -p | xargs -r kill 2>/dev/null
}
trap shutdown INT EXIT TERM ERR
_cursorBack() {
echo -en "\033[$1D"
}
_spinner() {
local xtrace
xtrace=$(set -o | grep xtrace | awk '{print $2}')
set +x
local LC_CTYPE=C
local LC_ALL=en_US.utf-8
tput civis
local CL="\e[2K"
local spin='⢿⣿⣻⣿⣽⣿⣾⣿⣷⣿⣿⣾⣿⣷⣿⣯⣿⣟⣿⡿⣿⢿⡿⣿'
local pid
pid=$(jobs -p)
local charwidth=2
local i=0
while kill -0 "$pid" 2>/dev/null; do
local i=$(((i + charwidth) % ${#spin}))
printf "%s" "${gr}${spin:i:charwidth}${nc}"
_cursorBack 2
sleep .1
done
echo -ne "$CL"
tput cnorm
wait "$pid"
if [[ $xtrace == "on" ]]; then
set -x
fi
}
use_spinner() {
local cmd=$1
shift
"$cmd" "$@" >"$SPINTMP" &
[[ $DEBUG == "true" ]] && set +x
_spinner
[[ $DEBUG == "true" ]] && set -x
echo -ne "\r"
cat "$SPINTMP"
}
run_aws_sso_login() {
if [[ -n $BROWSER_OVERRIDE && $BROWSER_OVERRIDE != "none" ]]; then
BROWSER="$BROWSER_OVERRIDE" aws sso login --sso-session awsctx
elif [[ $BROWSER_OVERRIDE == "none" ]]; then
aws sso login --sso-session awsctx --no-browser
else
aws sso login --sso-session awsctx
fi
}
validate_output() {
trap 'exit 2' SIGINT
if [[ -z $OUTPUT_FORMAT ]]; then
error "No output format provided with the ${it}-o${nc}${rd} flag 🪧${nc}"
# Define options for output format selection
local output_options=(
"json"
"text"
"table"
"yaml"
"yaml-stream"
)
# Use fzf to get user's choice
local selected_format
selected_format=$(select_option "Select output format" "${output_options[@]}")
if [[ -n $selected_format ]]; then
OUTPUT_FORMAT="$selected_format"
else
error "No output format selected. Using default: json" "⚠️"
OUTPUT_FORMAT="json"
fi
fi
success "Output format selected: $OUTPUT_FORMAT" "✅"
# Ask about CLI pager preference only if not already set
if [[ -z ${CLI_PAGER:-} ]]; then
if ask "Would you like to set a CLI pager for AWS output?" "y"; then
info "Common pager options:"
# Define options for pager selection
local pager_options=(
"bat -Ppl yaml (Syntax highlighted output - requires bat)"
"less (Standard pager)"
"more (Simple pager)"
"custom (Enter your own pager command)"
)
# Use fzf to get user's choice
local selected_pager
selected_pager=$(select_option "Select pager" "${pager_options[@]}")
case "$selected_pager" in
"bat -Ppl yaml (Syntax highlighted output - requires bat)")
# Check if bat is installed
if ! command -v bat &>/dev/null; then
error "bat is not installed. Please install bat to use this option." "⚠️"
info "https://github.com/sharkdp/bat#installation"
CLI_PAGER=""
else
CLI_PAGER="bat -Ppl yaml"
fi
;;
"less (Standard pager)")
CLI_PAGER="less"
;;
"more (Simple pager)")
CLI_PAGER="more"
;;
"custom (Enter your own pager command)")
CLI_PAGER=$(prompt "Enter your custom pager command")
;;
*)
warn "Invalid selection. No pager will be set." "⚠️"
CLI_PAGER=""
;;
esac
fi
fi
}
setup_aws_config() {
trap 'exit 2' SIGINT
unset AWS_PROFILE
if [[ -e ${AWS_CONFIG_FILE} && -s ${AWS_CONFIG_FILE} ]]; then
warn "This will overwrite your existing AWS config file: ${AWS_CONFIG_FILE}" "⚠️"
if ask "Would you like to backup your existing AWS config file?" "y"; then
success "Backing up existing AWS config file: ${AWS_CONFIG_FILE}" "💾"
mv "${AWS_CONFIG_FILE}" "${AWS_CONFIG_FILE}.$(date "+%d%b%Y_%H-%M-%S")"
touch "${AWS_CONFIG_FILE}"
fi
fi
echo "$SESSION_BLOCK" >"${AWS_CONFIG_FILE}"
if run_aws_sso_login; then
success "AWS SSO configuration initialized successfully" "✅"
if ask "Would you like to generate AWS profiles now?" "y"; then
GENERATE_CONFIG="true"
if [[ -z $OUTPUT_FORMAT ]]; then
validate_output
fi
generate_config
exit 0 # Exit after generating config to prevent double execution
else
info "You can run '${bl}${bd}awsctx -g${nc}' later to generate your AWS profiles"
fi
else
error "Failed to initialize AWS CLI configuration" "😭"
exit 1
fi
}
count_resources() {
local region=$1
local count=0
# Use set +e to prevent individual AWS command failures from stopping the script
set +e
# Capture counts, defaulting to 0 if commands fail
local ec2_count=0
local s3_count=0
local lambda_count=0
local rds_instance_count=0
local rds_cluster_count=0
ec2_count=$(aws ec2 describe-instances --region "$region" --query "Reservations[*].Instances[*].[InstanceId]" --output text 2>/dev/null | wc -l) || ec2_count=0
if [[ $region == "us-east-1" ]]; then
s3_count=$(aws s3api list-buckets --query "Buckets[*].Name" --output text 2>/dev/null | wc -l) || s3_count=0
fi
lambda_count=$(aws lambda list-functions --region "$region" --query "Functions[*].FunctionName" --output text 2>/dev/null | wc -l) || lambda_count=0
rds_instance_count=$(aws rds describe-db-instances --region "$region" --query "DBInstances[*].DBInstanceIdentifier" --output text 2>/dev/null | wc -l) || rds_instance_count=0
rds_cluster_count=$(aws rds describe-db-clusters --region "$region" --query "DBClusters[*].DBClusterIdentifier" --output text 2>/dev/null | wc -l) || rds_cluster_count=0
# Re-enable error checking
set -e
count=$((ec2_count + s3_count + lambda_count + rds_instance_count + rds_cluster_count))
printf "%s=%d\n" "$region" "$count" >>"$REGION_COUNTS"
return 0
}
calculate_region_counts() {
trap 'exit 2' SIGINT
rm -f "$REGION_COUNTS"
touch "$REGION_COUNTS"
# Clear the global associative array
region_counts=()
# Read regions into array
readarray -t region_array < <(echo "$regions" | tr '\t' '\n')
# Store PIDs for background processes
pids=()
# Start all region counts in background
for region in "${region_array[@]}"; do
count_resources "$region" &
pids+=($!)
done
# Wait for all background processes to complete and check their exit status
failed=0
for pid in "${pids[@]}"; do
wait "$pid" || ((failed++))
done
# Read the results
while IFS='=' read -r region count; do
if [[ -n $region && -n $count ]]; then
region_counts["$region"]=$count
fi
done <"$REGION_COUNTS"
# Find the maximum count and primary region
max_count=0
primary_region=""
for region in "${!region_counts[@]}"; do
if ((region_counts[$region] > max_count)); then
max_count=${region_counts[$region]}
primary_region=$region
fi
done
# Export scalar variables
export max_count primary_region
return 0
}
generate_bar() {
local count=$1
local max_count=$2
local length=70
local bar_length=$((count * length / max_count))
local bar=""
local part_length=$((length / 2))
for ((i = 0; i < bar_length; i++)); do
if ((i < part_length)); then
local ratio=$((i * 100 / part_length))
local red=$((255 * ratio / 100))
local green=255
local blue=0
else
local ratio=$(((i - part_length) * 100 / part_length))
local red=255
local green=$((255 * (100 - ratio) / 100))
local blue=0
fi
bar="${bar}\e[48;2;${red};${green};${blue}m \e[0m"
done
echo -e "$bar"
}
validate_token() {
trap 'exit 2' SIGINT
if [[ ! -s ${AWS_CONFIG_FILE} ]]; then
error "AWS config file empty: ${AWS_CONFIG_FILE}" "🫥"
info "Proceeding to initialize your AWS CLI configuration..."
setup_aws_config
return
fi
if [[ ! -d $SSO_CACHE_DIR ]]; then
error "SSO cache directory not found: $SSO_CACHE_DIR" "😰"
info "Proceeding to initialize your AWS CLI configuration..."
setup_aws_config
return
fi
LATEST_SSO_CACHE="$(find "${SSO_CACHE_DIR}" -type f -print0 | xargs -0 ls -t | head -n1)"
ACCESS_TOKEN_FILE="${LATEST_SSO_CACHE}"
ACCESS_TOKEN="" # Initialize ACCESS_TOKEN
if [[ ! -f $ACCESS_TOKEN_FILE ]]; then
error "SSO access token could not be found" "😦"
info "Proceeding to initialize your AWS CLI configuration..."
setup_aws_config
return
else
ACCESS_TOKEN=$(jq -e -r '.accessToken' "$ACCESS_TOKEN_FILE" || echo "")
if [[ -z $ACCESS_TOKEN ]]; then
if [[ ! -f ${AWS_CONFIG_FILE} ]]; then
error "AWS config file not found: $AWS_CONFIG_FILE" "🫥"
info "Proceeding to initialize your AWS CLI configuration..."
setup_aws_config
return
else
error "SSO access token not found in cache directory: $SSO_CACHE_DIR" "😶🌫️"
info "Please run '${bl}${bd}aws sso login --sso-session awsctx${nc}' to login to AWS SSO"
if ask "Attempt to login to AWS SSO?" "y"; then
run_aws_sso_login
else
exit 1
fi
fi
fi
EXPIRES_AT=$(jq -e -r '.expiresAt' "$ACCESS_TOKEN_FILE")
if [[ $CURRENT_TIME > $EXPIRES_AT ]]; then
error "SSO access token has expired" "👴🏼"
info "Please run '${bl}${bd}aws sso login --sso-session awsctx${nc}' to login to AWS SSO"
if ask "Attempt to login to AWS SSO?" "y"; then
run_aws_sso_login
else
exit 1
fi
fi
fi
}
build_accounts_list() {
# Ensure we have a valid token before proceeding
validate_token
# Now we can safely use ACCESS_TOKEN as it will be set by validate_token
aws \
sso \
list-accounts \
--region us-east-1 \
--access-token "$ACCESS_TOKEN" \
--output json \
--query "accountList[].{accountName: accountName, accountId: accountId}" |
jq 'map(
.accountName |= (
# Convert to lowercase, replace spaces and special chars with hyphens
gsub("[^a-zA-Z0-9-]"; "-") |
# Collapse multiple consecutive hyphens into a single hyphen
gsub("-+"; "-") |
# Remove leading/trailing hyphens
gsub("^-|-$"; "")
)
) | sort_by(.accountName|ascii_upcase)' \
>"$ACCOUNTS_LIST"
}
accounts_load() {
use_spinner build_accounts_list
}
build_roles_list() {
trap 'exit 2' SIGINT
# Ensure we have a valid token before proceeding
validate_token
echo "[]" >"$ACCOUNTS_ROLES"
jq -e -c '.[]' "$ACCOUNTS_LIST" | while read -r account; do
ACCOUNT_ID=$(echo "$account" | jq -e -r '.accountId')
ROLES=$(
aws \
sso \
list-account-roles \
--region us-east-1 \
--access-token "$ACCESS_TOKEN" \
--account-id "$ACCOUNT_ID" \
--output json \
--query "sort_by(roleList, &roleName) | [].roleName"
)
if [[ -z $ROLES || $ROLES == "[]" ]]; then
warn "No roles found for account ID $ACCOUNT_ID 🙅"
continue
fi
for role in $(echo "$ROLES" | jq -r '.[]'); do
UPDATED_ACCOUNT=$(echo "$account" | jq -e --arg role "$role" '. + {sso_role_name: $role}')
jq -e --argjson newAccount "$UPDATED_ACCOUNT" '. += [$newAccount]' "$ACCOUNTS_ROLES" >"$TMP_ROLES"
mv "$TMP_ROLES" "$ACCOUNTS_ROLES"
done
done
}
roles_load() {
use_spinner build_roles_list
}
write_config() {
# Create a temporary file for the default profile section
local default_section
default_section=$(create_temp_file "default_section")
# Extract the default profile section to a temporary file first
awk -v common_profile="profile $CROSS_ACCOUNT_PROFILE" '
$0 ~ common_profile {in_default = 1; next}
/^\[/ && in_default {in_default = 0}
in_default && NF {print}
' "${AWS_CONFIG_PROFILES}" >"$default_section"
# Write all config sections to AWS_CONFIG_PROFILES in a single operation
{
# Write session block
echo "$SESSION_BLOCK"
# Write account profiles
jq -r '
group_by(.accountName) |
.[] |
.[] | . + {
displayName: "\(.sso_role_name)@\(.accountName)"
} |
"[profile \(.displayName)]\n" +
"sso_session = awsctx\n" +
"sso_account_id = \(.accountId | gsub("\"";""))\n" +
"sso_role_name = \(.sso_role_name | gsub("\"";""))\n" +
"region = \(if (.accountName | test("^(?i)uk-?")) then "eu-west-1" else "us-east-1" end)\n" +
"output = '"$OUTPUT_FORMAT"'\n" +
if ("'"$CLI_PAGER"'" != "") then "cli_pager = '"$CLI_PAGER"'\n" else "" end
' "$ACCOUNTS_ROLES"
# Write default profile section
echo "[default]"
cat "$default_section"
} >"${AWS_CONFIG_PROFILES}"
# Clean up temporary file
rm -f "$default_section"
# Copy temporary file to final config file
cp "${AWS_CONFIG_PROFILES}" "${AWS_CONFIG_FILE}"
success "AWS profiles have been successfully generated, and written to: ${AWS_CONFIG_FILE}" "✅"
info "You can now use '${bl}${bd}awsctx${nc}' to switch between AWS accounts and roles 🏁"
}
generate_config() {
validate_output
echo -n "📇 Populating Accounts..."
accounts_load
echo "📇 Populating Accounts...${gr}✓${nc}"
echo -n "👥 Gathering roles for accounts..."
roles_load
echo "👥 Gathering roles for accounts...${gr}✓${nc}"
write_config
}
print_heatmap() {
printf '\n%s%-14s%s │ %s%s%s\n' "${bl}" "Region" "${nc}" "${bl}" "Resources" "${nc}"
printf '%-14s┼%s\n' "───────────────" "───────────"
# Sort regions alphabetically using mapfile
mapfile -t sorted_regions < <(printf '%s\n' "${!region_counts[@]}" | sort)
for region in "${sorted_regions[@]}"; do
local count=${region_counts["$region"]}
local bar=""
if ((count > 0)); then
bar=$(generate_bar "$count" "$max_count")
fi
printf '%-14s │ %s\n' "$region" "$bar"
done
if [[ -n $primary_region ]]; then
printf '\n%s%s%s%s%s (%d resources)\n\n' \
"${cy}" "The primary region with the majority of resources is: " \
"${mg}" "$primary_region" "${nc}" \
"${region_counts[$primary_region]}"
else
printf '\n%s%s%s\n\n' "${cy}" "No resources found in any region." "${nc}"
fi
return 0
}
process_profile() {
local profile_name="$1"
local temp_config="$2"
# Get list of all AWS regions and properly format them
local regions
regions=$(aws --profile "$profile_name" ec2 describe-regions --query "Regions[].RegionName" --output text 2>/dev/null | tr '\t' '\n' | sort) || {
echo "Failed to get regions for profile: $profile_name"
return 1
}
# Process each region
while IFS= read -r region; do
# Skip regions that are known to not have EKS (optional optimization)
case "$region" in
"ap-northeast-3") continue ;; # Osaka - Limited availability
"ap-southeast-4") continue ;; # Melbourne - Limited availability
"eu-south-2") continue ;; # Spain - Limited availability
"eu-central-2") continue ;; # Zurich - Limited availability
"il-central-1") continue ;; # Israel - Limited availability
esac