-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.functions_aws
852 lines (717 loc) · 28.5 KB
/
.functions_aws
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
#----- header -----
[ "${0##*/}" != "${BASH_SOURCE##*/}" ] || { >&2 echo -e "ERROR\tfile must be sourced ($0)"; return 2; }
#------------------
#=== WARNING WARNING WARNING ===
# long_opts are dangerous since AWSCLI doesn't obey '--long_opt=value' pattern
#
#ref: https://docs.aws.amazon.com/cli/latest/reference/index.html#cli-aws
__aws_bin=`is_exec -v "${AWS_BIN:-aws${AWS_VERSION}}"` || return 127
declare -i __aws_windows=0
#TODO theoretically windows OR cygwin could invoke a WSL binary
if is_windows "$__aws_bin"; then
__aws_windows=1
function __aws_postproc() { tr -d '\r'; }
fi
declare -F __JQ{,R} >/dev/null || { log.error "missing required function (__JQ)"; return 127; }
# should NEVER happen unless non-traditional invocation
is_windows && : ${HOME:=`cygpath -a "${USERPROFILE:-.}"`}
: ${HOME:=/}
export HOME
shopt -s extglob
declare -Ar __aws_defaults=(
# safety fall-back when neither AWS_[DEFAULT_]REGION or ec2.metadata
['region']='us-east-1'
['config']='$HOME/.aws/config'
['credentials']='$HOME/.aws/credentials'
['cache_dir']='$HOME/.aws/cli/cache'
['readTimeout']=30
['connectTimeout']=7
)
#json: .Credentials
declare -Ar __aws_session=(
['AccessKeyId']='aws_access_key_id'
['SecretAccessKey']='aws_secret_access_key'
['SessionToken']='aws_session_token'
['Expiration']='aws_session_expire'
)
#json: .AssumedRoleUser
declare -Ar __aws_role=(
['AssumedRoleId']='role_session_name'
['Arn']='role_arn'
)
declare -Ar __aws_regex=(
['token']='^[0-9]{6}'
['role_arn']='^arn:aws:iam::[0-9]{12}:role/'
['region']='^[a-z]{2}-[a-z]+-[0-9]'
['profile']='^[a-zA-Z]+'
)
#ref: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html
# aws ec2 describe-regions | __JQR '.Regions[].RegionName' | sort
[ ${#__aws_regions[@]} -ge 16 ] ||
declare -ar __aws_regions=(
af-south-1
ap-east-1
ap-south-{1,2}
ap-southeast-{1,2,3,4}
ap-northeast-{1,2,3}
ca-central-1
eu-central-{1,2}
eu-north-1
eu-south-{1,2}
eu-west-{1,2,3}
il-central-1
me-south-1
me-central-1
sa-east-1
us-east-{1,2}
us-west-{1,2}
us-gov-{east,west}-1
)
#for region in ${__aws_regions[@]}; do
# __aws_availability_zones[$region]=`aws ec2 describe-availability-zones \
# --region $region \
# --query 'AvailabilityZones[].{ Name:ZoneName }' --output text`
# #alt: ... | JQR '.AvailabilityZones[].ZoneName | @sh'`
#done
[ ${#__aws_availability_zones[@]} -ge 16 ] ||
declare -Ar __aws_availability_zones=(
['ap-northeast-1']=`echo ap-northeast-1{a,c,d}`
['ap-northeast-2']=`echo ap-northeast-2{a,c}`
['ap-south-1']=`echo ap-south-1{a..b}`
['ap-southeast-1']=`echo ap-southeast-1{a..c}`
['ap-southeast-2']=`echo ap-southeast-2{a..c}`
['ca-central-1']=`echo ca-central-1{a..b}`
['eu-central-1']=`echo eu-central-1{a..c}`
['eu-north-1']=`echo eu-north-1{a..c}`
['eu-west-1']=`echo eu-west-1{a..c}`
['eu-west-2']=`echo eu-west-2{a..c}`
['eu-west-3']=`echo eu-west-3{a..c}`
['sa-east-1']=`echo sa-east-1{a,c}`
['us-east-1']=`echo us-east-1{a..f}`
['us-east-2']=`echo us-east-2{a..c}`
['us-west-1']=`echo us-west-1{a,c}`
['us-west-2']=`echo us-west-2{a..c}`
['us-gov-east-1']=`echo us-gov-east-1{a..c}`
['us-gov-west-1']=`echo us-gov-west-1{a..c}`
)
function __AWS() {
local AWS_OUTPUT AWS_POSTPROC
local -i AWS_NOPIPE
local -a cmd=()
if [ -z "$AWS_CONFIG_FILE" ]; then
unset AWS_{CONFIG,SHARED_CREDENTIALS}_{FILE,WINDOWS}
else
is_file "$AWS_CONFIG_FILE" || return
#NOTE Amazon CLI can't derive CREDENTIALS_FILE from CONFIG_FILE
: ${AWS_SHARED_CREDENTIALS_FILE:=${AWS_CONFIG_FILE%/*}/credentials}
#FIXME use readlink to make honest compare
if [ "${AWS_CONFIG_FILE%/*}" != "${AWS_SHARED_CREDENTIALS_FILE%/*}" ]; then
log.warn "prefix mismatch; resetting CREDENTIALS_FILE ..." \
"AWS_CONFIG_FILE: $AWS_CONFIG_FILE" \
"AWS_SHARED_CREDENTIALS_FILE: $AWS_SHARED_CREDENTIALS_FILE"
AWS_SHARED_CREDENTIALS_FILE=${AWS_CONFIG_FILE%/*}/credentials
fi
#WARN! *_WINDOWS can easily diverge
if (( ${__aws_windows:-0} )); then
AWS_CONFIG_FILE=${AWS_CONFIG_WINDOWS:=`cygpath -am "$AWS_CONFIG_FILE"`}
AWS_SHARED_CREDENTIALS_FILE=${AWS_SHARED_CREDENTIALS_WINDOWS:=`cygpath -am "$AWS_SHARED_CREDENTIALS_FILE"`}
fi
cmd+=( 'env'
AWS_CONFIG_FILE="$AWS_CONFIG_FILE"
AWS_SHARED_CREDENTIALS_FILE="$AWS_SHARED_CREDENTIALS_FILE" )
fi
cmd+=( "$__aws_bin" )
# special keywords mimics ssh-wrapper
local sop
local -i __s3_mode=0
#WARN *seriously* brittle assumption #1; that ignores possibility of '--XXX' options+args
#FIXME? use getopt to re-flow all options
case "$1" in
edit) sop=${EDITOR:-vi} ;&
# assumes operation against either of AWS_CONFIG_FILE or AWS_SHARED_CREDENTIALS_FILE
file|echo|cat)
local file=${2:-'AWS_CONFIG_FILE'}
# leverage lazy evaluation
case "${file^^}" in
?(AWS_)CONFIG?(_FILE))
file=${AWS_CONFIG_FILE:-`eval echo "${__aws_defaults['config']}"`}
;;
?(AWS_SHARED_)CRED*?(_FILE))
file=${AWS_SHARED_CREDENTIALS_FILE:-`eval echo "${__aws_defaults['credentials']}"`}
esac
is_file "${file:?}" && ${sop:-$1} "$file"
return
;;
# mimic aws-shell
shell) "${cmd[@]}" --cli-auto-prompt; return ;;
# format='text' appears hard-coded; explicit '--output' ineffectual
config?(ure))
case "$2" in
delete-profile) #TODO
;;
delete-creds) #TODO
;;
load-creds) #TODO
;;
get|set|list?(-profiles))
;;
*) AWS_NOPIPE=1
esac
set -- 'configure' "${@:2}"
;;
# API v1 frequently ignores VPC endpoints (NOT exhaustive)
# ec2|sts|dynamodb|sqs|ses|ssm|s3)
# string.contains -- "$*" '--endpoint-url' || {
#
# local endpoint=`join_string -zd . "$1" "${AWS_DEFAULT_REGION:-$AWS_REGION}" 'amazonaws.com'`
#TODO? name resolution can be problematic and ping arguments inconsistent
# # DOS missing 'host', Linux missing 'bind-utils'
# if ( host -s "$endpoint" || nslookup "$endpoint" || ping -n 1 "$endpoint" ) &>/dev/null; then
# cmd+=( '--endpoint-url' "https://${endpoint}/" )
# else log.notice "name resolution failed ($endpoint)"; fi
# }
# do not post-process output when
# OpenSSH ProxyCommand pipe or sts prompting for MFA Token
sts) string.contains -o grep --extended-regexp -- "$*" '(assume-role|get-session-token)' && AWS_NOPIPE=1 ;;
ssm) string.contains -- "$*" 'start-session' && AWS_NOPIPE=1 ;;
'--version'|help)
AWS_NOPIPE=1 ;;
ec2) cmd+=( ${NOOP:+'--dry-run'} ) ;;
s3) cmd+=( ${NOOP:+'--dryrun'} ); __s3_mode=1 ;;
esac
# When running on EC2, the CLI *should* properly resolve its region but
# firewall rules or name resolution problems or incomplete config file with
# v1 client stupidity can still lead to failure.
if is_ec2 && [ -z "${AWS_DEFAULT_REGION}${AWS_REGION}" ]; then
if ! string.contains -- "$*" '--region'; then
local region=$( ec2.metadata region || "${cmd[@]}" configure get region )
if [ -z "$region" ]; then
log.warn "forcing AWS_REGION to hard-coded default ($region)"
region=${__aws_defaults['region']}
fi
cmd+=( '--region' "${region:?}" )
fi
fi
#WARN! format='text' is hazardous & unpredictable in programatic invocation
string.contains -- "$*" '--output' || cmd+=( '--output' ${AWS_OUTPUT:-json} )
string.contains -- "$*" '--debug' ||
if ([ ${DEBUG:-0} -gt 1 ] || [ -n "$TRACE" ]); then cmd+=( '--debug' ); fi
string.contains -- "$*" '--cli-connect-timeout' ||
cmd+=( '--cli-connect-timeout' ${AWS_CONNECT_TIMEOUT:-${__aws_defaults['connectTimeout']}} )
string.contains -- "$*" '--cli-read-timeout' ||
cmd+=( '--cli-read-timeout' ${AWS_READ_TIMEOUT:-${__aws_defaults['readTimeout']}} )
#WARN! *seriously* brittle assumption #2: <service> <operation>
cmd+=( $1 $2 ); shift 2 || shift
if (( ${__aws_windows:-0} )); then
local -a rewrite_args=()
while (( $# )); do
if [[ "$1" =~ ^file:// ]]; then
rewrite_args+=( "file://`cygpath -am "${1#file://}"`" )
elif (( ${__s3_mode:-0} )) && ! [[ "$1" =~ s3:// ]] &&
( is_file "$1" || is_dir "$1" ); then
# weak attempt to differentiate args from files
rewrite_args+=( "`cygpath -am "$1"`" )
else
rewrite_args+=( "$1" )
fi
shift
done
set -- "${rewrite_args[@]}"
fi
if is_function "${AWS_POSTPROC=__aws_postproc}" && ! (( ${AWS_NOPIPE:-0} )); then
${DEBUG:+ runv} "${cmd[@]}" "$@" | $AWS_POSTPROC
else
${DEBUG:+ runv} "${cmd[@]}" "$@"
fi
}
#alt: not sure if [...] is correct
# exec 3>&1
# ${DEBUG:+ runv} "${cmd[@]}" "$@" >&3 [3>&-] | tr -d '\r'
# exec 3>&-
# approximate clone of program from ec2-utils.rpm
function ec2.metadata() {
local -r url='http://169.254.169.254/latest/meta-data'
local -Ar mapping=(
[a]='ami-id'
[b]='block-device-mapping/'
[availability-zone]='placement/availability-zone'
[e]='reservation-id'
[h]='local-hostname'
[i]='instance-id'
[l]='ami-launch-index'
[m]='ami-manifest-path'
[o]='local-ipv4'
[p]='public-hostname'
[s]='security-groups'
[t]='instance-type'
[u]='public-keys'
[v]='public-ipv4'
)
local item=${1##-} mac
# special cases
case "$item" in
#-c/--product-codes Product codes associated with this instance.
#-d/--user-data User-supplied data.Only available if supplied at instance launch time.
self) item='i' ;;
#-k/--kernel-id The ID of the kernel launched with this instance, if applicable.
#-n/--ancestor-ami-ids The AMI IDs of any instances that were rebundled to create this AMI.
#-r/--ramdisk-id The ID of the RAM disk launched with this instance, if applicable.
_public-keys*)
item="${item#_}" ;;
public-keys)
while read line; do
while read format; do
# convert multi-line to single
$FUNCNAME "_$item/${line%%=*}/$format" | sed ':a;N;s/\n//;ta'
done < <( $FUNCNAME "_$item/${line%%=*}" )
done < <( $FUNCNAME "_$item" )
#TODO selective print by index or by key name
return
;;
region) $FUNCNAME 'availability-zone' | sed 's/[a-z]$//'; return
;;
subnet?(-id))
item="network/interfaces/macs/$($FUNCNAME mac)/subnet-id"
;;
type) item='t' ;;
vpc?(-id))
item="network/interfaces/macs/$($FUNCNAME mac)/vpc-id"
;;
z|az) item='availability-zone' ;;
#NOTE wildcard interferes with fall-through
# *) [ -n "${mapping[$item]}" ] ||
# log.error "unsupported format ($format)"; return 2
esac
# recursion for intermediary items (eg. MAC) can leave behind trailing '/'
__CURL "$url/${mapping[$item]:-$item}" | sed 's|/$||'
}
function is_ec2() { ec2.metadata self &>/dev/null; }
# function aws-kms-crypt (de/en) are simple 1 liner calls to kms-crypt
# -e for encrypt, -d for decrypt. -B to pipe results to base64 -d. must NOT decode (ie. consume the already base64-encoded
# cyphertext as-is for assignment to Bash variables. Pipes, however have no such limitation.
# shamelessly cribbed from https://stackoverflow.com/questions/49537224/how-can-i-call-amazons-aws-kms-decrypt-function-without-using-a-binary-file/53735748#53735748
# remember to whack Gruntwork's retarded 'kmscrypt::' header both forward and backward.
#
# also support -j and auto-detect on 1st char = '{'
# aws kms decrypt --ciphertext-blob fileb://<(sed -e 's/^kmscrypt:://' post | base64 -d) --query Plaintext --output text
# }
function aws.describe() {
# returns a series of JSON objects TODO? optionally wrapped in array (-a)
local keyword= type= field=
local -i single=0 sort_keys=0
local -a filter=() query=() post=() long_opts=()
local -i OPTIND; local opt OPTARG
while getopts ':1at:q:Q:sh' opt; do
case "$opt" in
1) single=1 ;;
q|Q) query+=( "$OPTARG" ) ;;
s) sort_keys=1 ;;
t) filter+=( "$OPTARG" ) ;;
:) log.error "missing argument (-$OPTARG)" ;;&
# \-) [[ "$OPTARG" =~ \= ]] || log.notice "assuming flag (--${OPTARG})"
# long_opts+=( "--${OPTARG}" )
# (( OPTIND++ ))
# ;;
\?) #long_opts+=( "-${OPTARG}" ) ;;
log.error "unsupported option (-${OPTARG})" ;&
h|*) >&2 echo "Usage: $FUNCNAME ... TODO"
return 2
esac
done
shift $((OPTIND - 1))
keyword=${1:?keyword}; shift
#FIXME rewrite all to use --filter syntax and generic ending below
#FIXME post should be JQ terms that join_string -d '|' glues together
local -a cmd=()
#!! WARN plural supported but beware side-effects !!
case "$keyword" in
vpc*) ;&
ec2.*) cmd=( ec2 ) ;;&
iam.*) cmd=( iam ) ;;&
asg|auto?(-)scaling-group?(s))
cmd=( autoscaling describe-auto-scaling-groups --auto-scaling-group-name "$@" )
field='AutoScalingGroups'
;;
# iam.user)
# iam.group?)
# iam.policy)
iam.role)
cmd+=( get-role --role-name "${1:?$keyword}" )
field='Role'
;;
s3|*bucket)
#TODO filter
__AWS s3api list-buckets | __JQ --arg bucket "${1:?bucket}" '.Buckets[] | select(.Name == $bucket)'
return
;;
*bucket-policy)
# last JQ used to un-escape embedded stanza (was: | __JQ .)
__AWS s3api get-bucket-policy --bucket "${1:?bucket}" | __JQ '.Policy | from_json'
return
;;
# ec2|*instance)
# instance-role)
# elastic-ip)
# internet-gateway
# nat-gateway
# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-tags.html
ec2.tag?(s))
type='instance'
cmd+=( describe-tags )
;;&
eip.tag?(s))
type='elastic-ip'
;;&
*tag?(s))
field='Tags'
#TODO non-EC2 items, but do we really need?
# sqs: list-queue-tags
# dynamodb: list-tags-of-resource
#
# ec2: customer-gateway | dedicated-host | dhcp-options | elastic-ip | fleet
# fpga-image | host-reservation | image | instance | internet-gateway
# key-pair | launch-template | natgateway | network-acl | network-interface
# placement-group | reserved-instances | route-table | security-group
# snapshot | spot-instances-request | subnet | volume | vpc | vpc-endpoint
# vpc-endpoint-service | vpc-peering-connection | vpn-connection | vpn-gateway
: ${type:=${keyword%.tag*}}
#TODO do all 'type's support filter?
filter=(
"Name=resource-type,Values=${type:?}"
"Name=resource-id,Values=${1:?resource_id}"
)
shift
# specify tags
#TODO escape special chars like '[],' also use aws.format_tags()
[ $# -ge 1 ] && filter+=( Name=key,Values=`string.join -zd ',' "$@"` )
function pre_process() {
__JQ '.[] | { (.ResourceId): { (.Key): (.Value) } }' | __JQ_merge
}
;;
# route)
# subnet)
*target-group?(s))
#FIXME use filter to pick items
__AWS elbv2 describe-target-groups |
__JQ --arg tg ${1:?target_group_name} '.TargetGroups[] | select(.TargetGroupName == $tg)'
return
;;
# ebs|volume) describe-volume
*volume-attachment)
__AWS ec2 describe-volumes --volume-ids ${1:?volume_id} | \
__JQ '.Volumes[].Attachments[0]'
return
;;
*volume-status)
#TODO? plural
__AWS ec2 describe-volume-status --volume-ids ${1:?volume_id} | \
__JQR '.VolumeStatuses[].VolumeStatus.Status'
return
;;
vpc?(s))
cmd+=( describe-vpcs '--vpc-ids' "$@" )
field='Vpcs'
;;
ec2.vpc-endpoint-service?(s))
cmd+=( describe-vpc-endpoint-services '--service-name'
"com.amazonaws.${AWS_DEFAULT_REGION:-${__aws_defaults[region]}}.${1:?service}"
)
field='ServiceDetails'
;;
ec2.vpc-endpoint?(s))
cmd+=( describe-vpc-endpoints '--vpc-endpoint-ids' "$@" )
field='VpcEndpoints'
;;
# target-group)
# elb|lb|load-blancer)
# security-group)
# launch-config)
# ssm.parameter?(s))
*) log.error "unsupported keyword ($keyword)"
return 2
esac
[ -n "$filter" ] && cmd+=( '--filters' "${filter[@]}" )
# 'query' strips default context indicated by 'field'
if [ -n "$query" ]; then
cmd+=( '--query' "${query[@]}" )
unset field
elif string.contains -- "$*" '--query'; then
unset field
fi
# non-trivial JQ operations defined above
is_function pre_process || function pre_process() { cat; }
is_function post_process || function post_process() { cat; }
#NOTE not found returns '{ <field>: [] }'
# each pipeline is a sub-shell, hinders short-circuit on-failure
__AWS "${cmd[@]}" |
if [ -n "$field" ]; then
__JQ --arg field "$field" '.[$field] | if length > 0 then . else empty end'
else cat; fi |
pre_process |
if [ ${sort_keys:-0} -eq 1 ]; then __JQ --sort-keys; else cat; fi |
if [ ${single:-0} -eq 1 ]; then __JQ '.[0]'; else cat; fi |
post_process
}
# similar to aws.describe() but intended to return singleton values safe for shell consumption, not long-winded JSON
function aws.get() {
local keyword
local -a filter=()
#TODO format with 'a' or 'A' like aws.list and use getopts()
keyword=${1:?item}; shift
case "$keyword" in
*.tag) aws.describe "$keyword" "${1:?resouce-id}" "${@:2}" |
__JQR --arg key "${2:?key}" '.[$key]'
;;
# *.tags) aws.describe "$keyword" "${1:?resouce-id}" "${@:2}" |
# format with 'a' or 'A' like aws.list
# ;;
ssm.parameter?(s))
# mute ParameterNotFound
if [ $# -eq 1 ]; then
__AWS ssm get-parameter --with-decryption --name "${1:?parameter}" |
__JQR '.Parameter.Value'
else
# key and value emitted on successive lines to simplify whitespace handling.
# consume via loop since direct eval() of ^/.+ which is not legal in SHELL.
# Example:
# while read -r key; do read -r value; ... done
# or
# IFS=, read -a foo < <( echo "one,three" )
# IFS=, read -a foo <<< "one,two"
__AWS ssm get-parameters --with-decryption --names "${@:?parameter(s)}" |
__JQR '.Parameters[] | .Name, .Value'
#TODO return Bash associative array '[key]=value' to minimize caller parsing
# ... | case $format in a), A) *) invokes JQR accordingly. If we can common-ize so it's just a function caller
# like json_to_array which is fed a standardized format of [ { "key": "kval", "value": "vval" }, ]
# __JQR '.Parameters[] | "[\(.Name)]=\'\(.Value)\'"'
fi
;;
sts.account)
__AWS sts get-caller-identity | __JQR '.Account'
;;
*) log.error "unsupported keyword ($keyword)"
return 2
esac
}
#target-group.instances - all EC2 instances assigned to a TG
#lb.instances - ditto for old LB style, detect if new (has TG) and iterate
#lb.membership - return all LB of which instance is a target. if LB is new (ie. has member TG) iterate thru them
#tg.membership - for new style
#aws elb describe-load-balancers | __JQR '.LoadBalancerDescriptions[] | select(.Instances[].InstanceId == "<YOUR-INSTANCE-ID>") | . LoadBalancerName '
# or
#aws elb describe-load-balancers --query "LoadBalancerDescriptions[?Instances[?InstanceId=='${instanceId}']].LoadBalancerName"
# but does NOT work with elbv2!!! have to loop thru all known target-groups
#
# for tg in `aws elbv2 describe-target-groups --query "TargetGroups[?VpcId=='${vpc_id}'].TargetGroupArn" | __JQR '.[]'`; do
# __AWS elbv2 describe-target-health --target-group-arn "$tg" --query "TargetHealthDescriptions[?Target.Id=='${instance_id}']" | __JQ
# '.[]' >/dev/null && echo $tg
#
# #alt: __JQR --arg instance "${instance_id:?}" 'select(.TargetHealthDescriptions[].Target.Id == $instance)'
# done
# Abstract out incompatible syntax for setting Tags. CURSE you AWS API team, you SUCK!!
function aws.format_tags() {
local -Ar __printf=(
['kv']= # $key=$value
['jKV']= # compose JSON via jq --null-input --arg K "$k" --arg V "$v" '{ "Key": $k, "Value": $v}'
['KkVv']='Key=%s,Value=%s'
['jKkVv']=
)
local delim= format keyword=
local -i use_stdin
local -i OPTIND; local opt OPTARG
while getopts ':k:S' opt; do
case "$opt" in
k) keyword=$OPTARG; break ;;
S) use_stdin=1 ;;
:) log.error "missing argument (-$OPTARG)" ;;&
\?) #if [ "${OPTARG:0:1}" = '-' ]; then break; fi # long_opts+=( "-$OPTARG" ); continue;
log.error "unsupported option (-${OPTARG})" ;&
h|*) >&2 cat << EOF
echo "Usage: $FUNCNAME ... TODO"
EOF
return 2
esac
done
shift $((OPTIND - 1))
local -a tags=()
case "{keyword:-ec2}" in
sqs) format=${__printf['kv']}; delim=','
# __JQR '[ to_entries[] | "\(.key)=\(.value)" ] | join(",")'
;;
# ddb|dynamodb)
# format=${__printf[???]}; delim=X
# ;;
#ref: https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-tags.html
ec2) format=${__printf['KkVv']}
tags=( '--tags' )
;;
*) log.error "unsupported format ($opt)"
return
esac
# read STDIN (pipe) if no args
(( $# )) || { [ ${use_stdin:-0} -eq 1 ] && set -- $( < /dev/stdin ); }
local -a kv=()
local -i is_json
while (( $# )); do
[ -n "$1" ] || { shift; continue; }
#TODO is_file "$1" detect JSON, or parse k=v
# if [ -f "$1" ]; then
# __JQ '.' "$1" &>/dev/null && : ${is_json:=1} ||
# set -- $( < "$f" )
# fi
# jq doesn't error on empty input, not even '4'
if [ -n "$1" ] && __JQ '.' <<< "$1" &>/dev/null; then
[ ${is_json:=1} -eq 1 ] ||
{ log.error "illegal intermixing of (non-)JSON" "$1"; return; }
tags=( '--cli-input-json' "$1" ) #XXX need re-encoding with to_json or @sh?
printf '%q\n' "${tags[*]}" #alt: local IFS=$'\n'; echo ... NOTE semi-colon!
return
fi
#WARN! does NOT handle embedded multi-line
kv=( `sed 's/[=,]/\n/g' <<< "$1"` ) #FIXME? assumes IFS=$'\n'
if [[ ${kv[0]:-X} =~ [kK]ey$ && ${kv[2]:-X} =~ [vV]alue$ ]]; then
tags+=( `printf "$format" "${kv[1]}" "${kv[3]}"` )
elif [ ${#kv[@]} -gt 1 ]; then
tags+=( `printf "$format" "${kv[0]}" "${kv[1]}"` )
else
log.error "unknown format ($1)"; return 2
fi
shift
done
#TODO escape special chars like '[],' nee Key=\"[Group]\",Value=test or 'Key="[Group]",Value=test'
printf '%s\n' "${tags[@]}"
#alt: declare -p tags | sed -E 's/^declare \-. \+=//'; and consume with eval
# or read() from multi-line or assign to array
}
# Invoked as single-ton - use external loop, though some items allow cheating via comma-delimited
function aws.set() {
local -a cmd=()
local keyword=${1:?keyword}; shift
case "$keyword" in
# sqs.tag)
# dynamodb.tag)
# ec2.tag)
# *.tag)
# ref: https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-tags.html
# Usage: item[,item]... <tags>
ec2.tag?(s))
[ ${DELETE:-0} -eq 1 ] && cmd=( ec2 delete-tags ) || cmd=( ec2 create-tags )
local -a tags=( `aws.format_tags "${@:2}"` )
#local IFS=,; for i in $1; do xxx; note non-quoted
# FIXME
__AWS "${cmd[@]}" --resources ${1//,/ } ${tags:+'--tags'} "${tags[@]}"
;;
ssm.parameter) #TODO getopt for 'force'
#[ "$1" = '-s' ] && { secure=1; shift; }
#or inspect ${1%%:*} where member of String, List|StringList, Secure|SecureString
local _type
[ ${DELETE:-0} -eq 1 ] &&
cmd=( delete-parameter ) ||
cmd=( put-parameter '--type' ${_type:-String} '--overwrite' '--value' "$2" )
__AWS ssm "${cmd[@]}" --name "${1:?key}" >/dev/null
;;
*) log.error "unsupported keyword ($keyword)"
return 2
esac
}
function asg.suspend() {
__AWS autoscaling enter-standby \
--auto-scaling-group-name "${1:?ASG_name}" \
--should-decrement-desired-capacity \
${2:+'--instance-ids' "${@:2}"}
}
function asg.resume() {
__AWS autoscaling exit-standby \
--auto-scaling-group-name "${1:?ASG_name}" \
${2:+'--instance-ids' "${@:2}"}
}
function asg.scale-zero() {
env min=0 desired=0 asg.set-capacity "$@"
}
#TODO aws.set asg.capacity
function asg.set-capacity() {
local -i min desired max
local -i OPTIND; local opt OPTARG
while getopts ':d:m:M:h' opt; do
case "$opt" in
d) desired=$OPTARG ;;
M) max=$OPTARG ;;
m) min=$OPTARG ;;
:) log.error "missing argument (-$OPTARG)" ;;&
\?) #if [ "${OPTARG:0:1}" = '-' ]; then break; fi # long_opts+=( "-$OPTARG" ); continue;
log.error "unsupported option (-${OPTARG})" ;&
h|*) >&2 echo "Usage: $FUNCNAME ... TODO"
return 2
esac
done
shift $((OPTIND - 1))
[ -n "${min}${desired}${max}" ] || {
log.error "none of 'min|max|desired' specified"; return 2
}
__AWS autoscaling update-auto-scaling-group \
--auto-scaling-group-name "${1:?ASG_name}" \
${min:+'--min-size' $min} \
${desired:+'--desired-capacity' $desired} \
${max:+'--max-size' $max} "${@:2}"
}
# wrapper around aws.describe emits 2 columns: <resource id> ["Tag:Name"] for
# human-friendly display of items and dynamic array assembly
# consume with readarray -t VAR < <(aws.list ...) or IFS=$'\n' ary=( `emit words` ), or
# hsh=( `emit [x]=y ...` )
#TODO really should be aws.get or aws.describe | aws.printf -a/-A <field> [<2nd_field>]
#FIXME this function doesn't actually DO anything yet!!!
function aws.list() {
local -i sort=0
local format keyword
local -i OPTIND; local opt OPTARG
while getopts ':aAf:hS' opt; do # no ^':' so pass args to aws.describe()
case "$opt" in
a) format='array' ;;
A) format='hash' ;;
f) format=$OPTARG ;;
S) sort=1 ;;
:) log.error "missing argument (-$OPTARG)"; return ;;
\?) #if [ "${OPTARG:0:1}" = '-' ]; then break; fi # long_opts+=( "-$OPTARG" ); continue;
log.error "unsupported option (-${OPTARG})" ;&
h|*) >&2 echo "Usage: $FUNCNAME ... TODO"
return 2
esac
done
shift $((OPTIND - 1))
keyword=${1:?keyword}; shift
local field
#FIXME describe() returns ARRAY without '-S' flag
case "$keyword" in
autoscaling-group?(s))
field='AutoScalingGroupName'
;;
vpc?(s)) field='VpcId' ;;
*) log.error "unsupported keyword ($keyword)"; return
esac
: ${field:?}
#TODO if name=0 cmd[1]=__JQ --arg field "$field" '.[$field], ""'
#TODO if sort=1 can JQ sort?
# shell-friendly output
case "${format:-json}" in
a?(rray)|t?(ext))
__JQR --arg field "$field" '.[$field]'
;;
# FIXME? if TAB, 'while IFS=$'\t' read -t key val
# otherwise, read key && read val
A|hash) __JQR --arg field "$field" '["\(.[$field])"]="\(.Tags | from_entries | .Name | @sh)"'
;;
json) __JQ --arg field "$field" '{ (.[$field]): (.Tags | from_entries | .Name // "") }' |
__JQ --slurp 'add'
;;
# not reached
*) log.error "unsupported format ($format)"; return 2
esac
#TODO generic execution - $cmd1 | $cmd2 | $cmd3
}
#function s3.restore
#aws s3 ls s3://<bucket_name> | awk '{print $4}' | xargs -L 1 aws s3api restore-object --restore-request Days=<days> --bucket <bucket_name> --key
# or better
# s3cmd restore --recursive s3://mybucketname/
# simple example of qlgrep but need to find my original from AWS
# szcat <file> | grep '^Key=' | sed -e 's|^\([^/]\+/[^/]\+\).*|\1|' | sort | uniq -dc
# vim: expandtab:ts=8:sw=4