-
Notifications
You must be signed in to change notification settings - Fork 0
/
alias
545 lines (476 loc) · 16.3 KB
/
alias
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
[toplevel]
#@IgnoreInspection BashAddShebang
# Setup:
# Read https://github.com/awslabs/awscli-aliases
# Install the aws cli (preferably v2) - https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html
# Setup aws shell completion - https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-completion.html
# In a nutshell, create this file in ~/.aws/cli/alias
#
# nb: If you don't want your console output paginated, add the following line to your .bash_profile
# export AWS_PAGER=''
#
# I tried to use jq (much as it is awesome), as little as possible in the commands, but sometimes i have, so...
# Install jq
#
# Using: execute the aws command with the alias, e.g.
# aws who
# aws lambdas
#
who = sts get-caller-identity
whoisme = aws sts get-caller-identity --query UserId --output text
tables = dynamodb list-tables --query 'TableNames'
# See gist, for details on the awscli
# https://gist.github.com/micklove/76b2cb13ea4d86f4b5f4ec42b0f9939b
#===================
# __ _____ ___
# \ \ / / _ \/ __|
# \ V /| _/ (__
# \_/ |_| \___|
#===================
##
## List or set your region
##
region = !f() {
[[ $# -eq 1 ]] && aws configure set region "$1" || aws configure get region;
}; f
##
## List vpcs by name
##
vpcs =
!f() {
aws ec2 describe-vpcs --query "Vpcs[].Tags[?Key=='Name'].Value" --output text \
| sort -d
}; f
##
## Get vpc id details, by tag name
## e.g. aws vpc-by-name VPC
##
vpc-by-name =
!f() {
aws ec2 describe-vpcs \
--filter "Name=tag:aws:cloudformation:logical-id,Values=*${1}*" \
--query Vpcs[].VpcId \
| jq ". | .[]" -r
}; f
##
## Get subnets, by tag name
## e.g aws subnets Public
##
subnets =
!f() {
ec2 describe-subnets \
--filter "Name=tag:aws:cloudformation:logical-id,Values=*${1}*" \
--query Subnets[].SubnetId \
| jq -r ". | .[]"
}; f
##
## List all security groups, sorted by Group Name
##
sgs =
!f() {
aws ec2 describe-security-groups \
--query "SecurityGroups[].[GroupId, GroupName]" \
--output text \
| sort -k 2
}; f
##
## list all security group port ranges open to 0.0.0.0/0
##
public-ports = ec2 describe-security-groups \
--filters Name=ip-permission.cidr,Values=0.0.0.0/0 \
--query 'SecurityGroups[].{
GroupName:GroupName,
GroupId:GroupId,
PortRanges:
IpPermissions[?contains(IpRanges[].CidrIp, `0.0.0.0/0`)].[
join(`:`, [IpProtocol, join(`-`, [to_string(FromPort), to_string(ToPort)])])
][]
}'
##
## Dump a table of info on the NAT gateways
##
nats = ec2 describe-nat-gateways \
--query "NatGateways[].{VpcId:VpcId, NatGatewayId: NatGatewayId, SubnetId: SubnetId, PublicIp: NatGatewayAddresses[].PublicIp | [0], PrivateIp: NatGatewayAddresses[].PrivateIp | [0] }" \
--output table
#======================================================
# _ _ ___ _
# /_\ _ __(_) / __|__ _| |_ _____ __ ____ _ _ _
# / _ \| '_ \ | | (_ / _` | _/ -_) V V / _` | || |
# /_/ \_\ .__/_| \___\__,_|\__\___|\_/\_/\__,_|\_, |
# |_| |__/
#======================================================
apis = apigateway get-rest-apis --output table
# =====================================
# _ _ _
# | | __ _ _ __ | |__ __| |__ _
# | |__/ _` | ' \| '_ \/ _` / _` |
# |____\__,_|_|_|_|_.__/\__,_\__,_|
#
#======================================
lambdas = lambda list-functions --query 'Functions[].FunctionName' --output table
# Get all log groups, sort by byte size, convert to GB, and filter to those of size 500mb or more (0.5GB in this case)
logs-by-size =
!f() {
aws logs describe-log-groups \
| jq '[.logGroups[] | {logGroupName: .logGroupName, storedBytes: (.storedBytes/1024/1024/1024), format: "GB", creationTime: (.creationTime/1000 | todateiso8601)}] | sort_by(.storedBytes) | .[] | select(.storedBytes >= 0.5)'
}; f
last-log =
!f() {
group="$1"
if ! stream="$(aws logs describe-log-streams --log-group-name "$group" \
--max-items 1 --order-by LastEventTime --descending \
--query "logStreams[0].logStreamName" --output "text")"; then
return 1
fi
stream="${stream%[[:space:]]None}"
aws logs get-log-events --log-group-name "$group" --log-stream-name "$stream" \
--query "events[].message" --output "text"
}; f
#===========================================================
# ____ _ ____ _ _ _
# / ___|___ __| | ___| _ \(_)_ __ ___| (_)_ __ ___
# | | / _ \ / _` |/ _ \ |_) | | '_ \ / _ \ | | '_ \ / _ \
# | |__| (_) | (_| | __/ __/| | |_) | __/ | | | | | __/
# \____\___/ \__,_|\___|_| |_| .__/ \___|_|_|_| |_|\___|
# |_|
#===========================================================
##
## List CodePipeline instances by name
##
pipes =
!f() {
aws codepipeline list-pipelines --query 'pipelines[].name | sort (@)' | jq -r '.[]'
}; f
#===================
# SSM
#===================
# Get a single parameter
param =
!g() {
aws ssm get-parameter --name $1
}; g
##
## Get multiple parameters, at path $1 e.g. aws params /backup
## e.g. aws params /my-path/bucket-names or.... aws params (to get all params)
##
params =
!g() {
# Use "/" as the default, if no parameter was given
aws ssm get-parameters-by-path --path ${1-"/"} --recursive | jq
}; g
#===================
# CLOUDFORMATION
#===================
stacks = cloudformation describe-stacks --query 'Stacks[].StackName'
exports = cloudformation list-exports
stax =
!f() {
aws cloudformation list-stacks \
--stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE UPDATE_ROLLBACK_COMPLETE \
--query 'StackSummaries[].StackName | sort(@)' \
| jq -r '.[]'
}; f
##
## Show stack details with dates
##
staxd =
!f() {
export WIDTH=30
aws cloudformation list-stacks \
--stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE UPDATE_ROLLBACK_COMPLETE \
--query 'StackSummaries[].{Updated: LastUpdatedTime, Created: CreationTime, StackName: StackName}' \
--output text \
| awk -v width=30 'BEGIN{printf "%*-s %*-s %s\n", width, "Updated", width, "Created", "StackName"}; {printf "%*-s %*-s %s\n", width, $3, width, $1, $2}' \
| grep -v -i vms \
| grep -v -i optimus
}; f
##
## List failed cloudformation stacks e.g. aws cfnfailed
##
cfnfailed = cloudformation list-stacks --stack-status-filter ROLLBACK_COMPLETE ROLLBACK_IN_PROGRESS ROLLBACK_FAILED
cfnevents =
!f() {
aws cloudformation describe-stack-events --stack-name $1
}; f
##
## List the most recently failed stack
## (TODO - the notion of "most recent" and "failed stacks" may need some work, in the command below)
## e.g. AWS_PROFILE=myprofile aws cfnlastfailed
cfnlastfailed =
!f() {
: ${AWS_PROFILE:?"AWS_PROFILE is required"}
local FAILED_STACK=$(AWS_PROFILE=${AWS_PROFILE} aws cloudformation list-stacks --stack-status-filter ROLLBACK_COMPLETE ROLLBACK_IN_PROGRESS ROLLBACK_FAILED --query StackSummaries[0].StackName | tr -d '"')
echo "FAILED_STACK=[${FAILED_STACK}]"
aws cloudformation describe-stack-events --stack-name ${FAILED_STACK} --query 'StackEvents[?ResourceStatus==`CREATE_FAILED`]' | jq
}; f
#===================
# ___ _ __ __
# |_ _| /_\ | \/ |
# | | / _ \| |\/| |
# |___/_/ \_\_| |_|
#
#===================
account =
!f() {
echo "Account alias [$(aws iam list-account-aliases --query AccountAliases --output text)]"
echo ==================================================================
aws sts get-caller-identity
}; f
role =
!f() {
aws iam get-role --role-name "${1}"
}; f
; Get roles containing the given param (note the quote, single quote in the matching, backticks wont work here) e.g. aws roles cross-acocunt
roles =
!f() {
aws iam list-roles --query "Roles[?contains(RoleName, '${1}')]"
}; f
users =
! f() {
aws iam list-users --query Users[].UserName --output text | xargs printf "%s\n"
}; f
##
## Show local profile names, from the aws credentials file
## e.g. aws profiles
##
profiles =
! g() {
echo "Profiles"
echo "================"
for i in $(grep -E "\[.*?\]" ~/.aws/credentials | sed 's#\[##g' | sed 's#\]##g'); do echo ${i}; done
}; g
#================
# ___ ___ ___
# | __/ __|_ )
# | _| (__ / /
# |___\___/___|
#
#================
running-instances = ec2 describe-instances \
--filter Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[].{ID: InstanceId,PrivateIpAddress: PrivateIpAddress, PublicIpAddress: PublicIpAddress, Hostname: PublicDnsName,Name: Tags[?Key==`Name`].Value | [0],Type: InstanceType, Platform: Platform || `Linux`}'
running-instances-table = ec2 describe-instances \
--filter Name=instance-state-name,Values=running \
--output table \
--query 'Reservations[].Instances[].{ID: InstanceId,Hostname: PublicDnsName,Name: Tags[?Key==`Name`].Value | [0],Type: InstanceType, Platform: Platform || `Linux`}'
##
## Loop through each region and count how many ec2 are running
##
all = !
! g() {
for region in $(aws ec2 describe-regions --query 'Regions[].RegionName | sort(@)' --output text); \
do echo $region; \
aws ec2 describe-instances \
--region "${region}" \
--filter Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[].{InstanceType:InstanceType}' \
| jq -r '.[].InstanceType' \
| sort \
| uniq -c \
| sort -r;
done
}; g
elbs =
! g() {
aws elb describe-load-balancers --query 'LoadBalancerDescriptions[].LoadBalancerName' | jq -r '.[]' | sort
}; g
##
## Print a list of instance types and their count, for the current region
##
types =
! g() {
aws ec2 describe-instances \
--filter Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[].InstanceType' \
| jq -r '.[]' \
| sort \
| uniq -c \
| sort -r
}; g
##
## Print a list of instance by ostype (e.g. windows or linux)
##
ostypes =
! g() {
aws ec2 describe-instances \
--filter Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[].{InstanceType: InstanceType, Platform: Platform || `Linux`}' --output text \
| sort \
| uniq -c \
| sort -r
}; g
asgs = autoscaling describe-auto-scaling-groups \
--query 'AutoScalingGroups[].{Name: AutoScalingGroupName, DesiredCapacity: DesiredCapacity, MinSize: MinSize, MaxSize: MaxSize, Instances: Instances}'
asg-settings = autoscaling describe-auto-scaling-groups \
--query "AutoScalingGroups[].{MDesired:DesiredCapacity, ASGName:AutoScalingGroupName, Min:MinSize, Max:MaxSize, lbname:LoadBalancerNames, LCName:LaunchConfigurationName, HealthCheckType:HealthCheckType}" \
--output table
##
## Print a table, with the status of the instances, for the given ASG
## e.g. aws asg-instance my-auto-scaling-group
##
asg-instance =
!f() {
printf "\n\n,------------------------------------------------------------------------------\n"
printf "| ASG: [%s]\n" "${1}"
aws autoscaling describe-auto-scaling-groups \
--query 'AutoScalingGroups[?AutoScalingGroupName ==`'$1'`].Instances[].{id:InstanceId, AZ:AvailabilityZone, HealthStatus:HealthStatus,LifecycleState:LifecycleState }' \
--output table
};f
##
## Print a table, with the status of the instances, for each ASG returned by the query
##
asg-instances =
!f() {
for i in $(aws autoscaling describe-auto-scaling-groups \
--query 'AutoScalingGroups[].AutoScalingGroupName | join(`"\n"`, @)' \
--output text)
do
aws asg-instance ${i}
done
}; f
#======================================================
# _ _ _ _ _
# | | | | | (_) |
# ___| | ___ _ _ __| | |_ _ __ __ _ _| |
# / __| |/ _ \| | | |/ _` | __| '__/ _` | | |
# | (__| | (_) | |_| | (_| | |_| | | (_| | | |
# \___|_|\___/ \__,_|\__,_|\__|_| \__,_|_|_|
#
#
#======================================================
## All Cloudtrail events, ignore Describe*, Get* and List* events
# nb: See the [.[] .... ] , notation. This is used for array construction (see https://stedolan.github.io/jq/manual/)
ct =
!f(){
aws cloudtrail lookup-events \
--query 'Events[].{EventName: EventName, Username: Username}' \
--max-items 1000 \
| jq '[.[] | select(.EventName | test("^(?!List|Get|Describe).*$"))]'
}; f
#==================================================================
# Get a unique list of actions from the past 'n' cloudtrail events e.g.
#
# AssumeRole
# AssumeRoleWithSAML
# AuthorizeSecurityGroupIngress
# CreateNetworkInterface
# CreateNetworkInterfacePermission
# Decrypt
# DeleteNetworkInterface
# GenerateDataKey
# ModifyNetworkInterfaceAttribute
# RevokeSecurityGroupIngress
# UpdateInstanceInformation
#==================================================================
ct-uniq =
!f(){
aws cloudtrail lookup-events \
--query 'Events[].{EventName: EventName, Username: Username}' \
--max-items 5000 \
| jq '[.[] | select(.EventName | test("^(?!List|Get|Describe).*$"))]' \
| jq -r '.[].EventName' \
| sort -u
}; f
## All Cloudtrail IAM events, ignore Describe*, Get* and List*., summarised listing
ct-iam =
!f(){
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventSource,AttributeValue="iam.amazonaws.com" \
--query 'Events[].{EventName: EventName, Username: Username}' \
--max-items 1000 \
| jq '[.[] | select(.EventName | test("^(?!List|Get|Describe).*$"))]'
}; f
#===================
# ___ ___ ___
# | _ \ \/ __|
# | / |) \__ \
# |_|_\___/|___/
#
#===================
##
## Show the status (available, etc...) of rds instances
## e.g. aws rds-status
##
rds-status =
!f() {
aws rds describe-db-instances \
--query "DBInstances[].{DBInstanceIdentifier:DBInstanceIdentifier, DBInstanceStatus:DBInstanceStatus, DBInstanceClass:DBInstanceClass, Engine:Engine }" \
--output text \
| sort
}; f
rds-available =
!f() {
aws rds describe-db-instances \
--query "DBInstances[?contains(DBInstanceStatus, 'available')].[DBInstanceIdentifier, DBInstanceStatus, DBInstanceClass ]" \
--output table
}; f
#===================
# ___ ____
# / __|__ /
# \__ \|_ \
# |___/___/
#
#===================
##
## Bucket policy (decodes the stringified json) e.g.
## aws bp my-bucket-name
##
bp =
! f() {
aws s3api get-bucket-policy --bucket "${1}" --query "Policy" | jq '. | fromjson'
}; f
##
## Show bucket notification - e.g. aws bn my-bucket
##
bn =
! f() {
aws s3api get-bucket-notification --bucket "${1}"
}; f
#===================
# ___ ___ _ _ _____ ___ ___ ____
# | _ \/ _ \| | | |_ _| __| __|__ /
# | / (_) | |_| | | | | _||__ \|_ \
# |_|_\\___/ \___/ |_| |___|___/___/
#
#===================
zones = route53 list-hosted-zones --query 'HostedZones[].{Name: Name, Id: Id, Private: Config.PrivateZone}'
# e.g. aws hosted "blah.blah.com." (returns ZABCDEBD07G)
hosted =
! g() {
aws route53 list-hosted-zones \
--query 'HostedZones[?Name ==`'${1}'`].Id' \
--output text \
| sed 's/\/hostedzone\///g'
}; g
# e.g. aws records "blah.blah.com."
records =
! g() {
local HOSTED_ZONE=$(aws route53 list-hosted-zones --query 'HostedZones[?Name ==`'${1}'`].Id' --output text | sed 's/\/hostedzone\///g')
aws route53 list-resource-record-sets --hosted-zone "${HOSTED_ZONE}"
}; g
##
## Find every AWS template in the current folder and execute cfn_nag against it
##
nag =
! g() {
cfn_nag $(find -E . -regex ".*(yaml|yml|json)" -not -path "*/node_modules/*" -exec grep -il AWSTemplate {} \;);
}; g
##
## Use cfn-flip to clean up your template and copy it to the clipboard. (nb also runs cfn-lint)
## (nb: then, you can use the "compare to clipboard" feature in most ides)
## e.g. aws tidy my-template-yaml
##
tidy =
! g() {
: ${1:?"Filename is required"}
cfn-lint "${1}"
cfn-flip "${1}" --clean --no-flip | pbcopy
echo "cfn-flip - output copied to clipboard"
}; g
##
## Find every AWS template in the current folder and execute cfn-lint against it
##
lint =
! g() {
cfn-lint $(find -E . -regex ".*(yaml|yml|json)" -not -path "*/node_modules/*" -exec grep -il AWSTemplate {} \;);
}; g