forked from awslabs/awscli-aliases
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalias
More file actions
291 lines (240 loc) · 9.46 KB
/
alias
File metadata and controls
291 lines (240 loc) · 9.46 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
[toplevel]
whoami = sts get-caller-identity
create-assume-role =
!f() {
aws iam create-role --role-name "${1}" \
--assume-role-policy-document \
"{\"Statement\":[{\
\"Action\":\"sts:AssumeRole\",\
\"Effect\":\"Allow\",\
\"Principal\":{\"Service\":\""${2}".amazonaws.com\"},\
\"Sid\":\"\"\
}],\
\"Version\":\"2012-10-17\"\
}";
}; f
running-instances = 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`}'
ebs-volumes= ec2 describe-volumes \
--query 'Volumes[].{VolumeId: VolumeId,State: State,Size: Size,Name: Tags[0].Value,AZ: AvailabilityZone}' \
--output table
amazon-linux-amis = ec2 describe-images \
--filter \
Name=owner-alias,Values=amazon \
Name=name,Values="amzn-ami-hvm-*" \
Name=architecture,Values=x86_64 \
Name=virtualization-type,Values=hvm \
Name=root-device-type,Values=ebs \
Name=block-device-mapping.volume-type,Values=gp2 \
--query "reverse(sort_by(Images, &CreationDate))[*].[ImageId,Name,Description]" \
--output text
list-sgs = ec2 describe-security-groups --query "SecurityGroups[].[GroupId, GroupName]" --output text
sg-rules = !f() { aws ec2 describe-security-groups \
--query "SecurityGroups[].IpPermissions[].[FromPort,ToPort,IpProtocol,join(',',IpRanges[].CidrIp)]" \
--group-id "$1" --output text; }; f
tostring =
!f() {
jp -f "${1}" 'to_string(@)'
}; f
tostring-with-jq =
!f() {
cat "${1}" | jq 'tostring'
}; f
authorize-my-ip =
!f() {
ip=$(aws myip)
aws ec2 authorize-security-group-ingress --group-id ${1} --cidr $ip/32 --protocol tcp --port 22
}; f
get-group-id =
!f() {
aws ec2 describe-security-groups --filters Name=group-name,Values=${1} --query SecurityGroups[0].GroupId --output text
}; f
authorize-my-ip-by-name =
!f() {
group_id=$(aws get-group-id "${1}")
aws authorize-my-ip "$group_id"
}; 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)])])
][]
}'
# List or set your region
region = !f() { [[ $# -eq 1 ]] && aws configure set region "$1" || aws configure get region; }; f
find-access-key = !f() {
clear_to_eol=$(tput el)
for i in $(aws iam list-users --query "Users[].UserName" --output text); do
printf "\r%sSearching...$i" "${clear_to_eol}"
result=$(aws iam list-access-keys --output text --user-name "${i}" --query "AccessKeyMetadata[?AccessKeyId=='${1}'].UserName";)
if [ -n "${result}" ]; then
printf "\r%s%s is owned by %s.\n" "${clear_to_eol}" "$1" "${result}"
break
fi
done
if [ -z "${result}" ]; then
printf "\r%sKey not found." "${clear_to_eol}"
fi
}; f
docker-ecr-login =
!f() {
region=$(aws configure get region)
endpoint=$(aws ecr get-authorization-token --region $region --output text --query authorizationData[].proxyEndpoint)
passwd=$(aws ecr get-authorization-token --region $region --output text --query authorizationData[].authorizationToken | base64 --decode | cut -d: -f2)
docker login -u AWS -p $passwd $endpoint
}; f
myip =
!f() {
dig +short myip.opendns.com @resolver1.opendns.com
}; f
allow-my-ip =
!f() {
my_ip=$(aws myip)
aws ec2 authorize-security-group-ingress --group-name ${1} --protocol ${2} --port ${3} --cidr $my_ip/32
}; f
revoke-my-ip =
!f() {
my_ip=$(aws myip)
aws ec2 revoke-security-group-ingress --group-name ${1} --protocol ${2} --port ${3} --cidr $my_ip/32
}; f
allow-my-ip-all =
!f() {
aws allow-my-ip ${1} all all
}; f
revoke-my-ip-all =
!f() {
aws revoke-my-ip ${1} all all
}; f
find-users-without-mfa =
!f() {
echo "Users withouth MFA enabled:"
for i in $(aws iam list-users --query "Users[?PasswordLastUsed].UserName" --output text); do
result=$(aws iam list-virtual-mfa-devices --query "length(VirtualMFADevices[?User.UserName=='${i}'])")
if [ "${result}" -eq "0" ]; then
echo "${i}"
fi
done
}; f
generate-sts-token =
!f() {
user_arn=$(aws whoami | jq -r .Arn)
duration=${1:-3600}
session_data=$(aws sts get-session-token --duration-seconds $duration)
echo "# temporary credentials on user ${user_arn} for $duration seconds (expires on $(echo $session_data | jq -r .Credentials.Expiration))"
echo "export AWS_DEFAULT_REGION=$(aws configure get region)"
echo "export AWS_ACCESS_KEY_ID=$(echo $session_data | jq -r .Credentials.AccessKeyId)"
echo "export AWS_SECRET_ACCESS_KEY=$(echo $session_data | jq -r .Credentials.SecretAccessKey)"
echo "export AWS_SESSION_TOKEN=$(echo $session_data | jq -r .Credentials.SessionToken)"
echo "export AWS_SECURITY_TOKEN=$(echo $session_data | jq -r .Credentials.SessionToken)"
}; f
describe-stack-params =
!f() {
aws cloudformation describe-stacks --stack-name ${1} | jq -r '.Stacks[0].Parameters[] | .ParameterKey + "=" + .ParameterValue' | sort
}; f
get-cfn-param-keys =
!f() {
stack_json=$(aws cloudformation describe-stacks --stack-name ${1})
echo ${stack_json} | jq -r '.Stacks[0].Parameters[] | .ParameterKey'
}; f
set-cfn-params =
!f() {
stack_name=$1
shift
stack_params=$(aws get-cfn-param-keys $stack_name)
declare -a params
for i in "$@"
do
key=$(echo ${i%%=*} | cksum | cut -d' ' -f1) # use cksum as sh array supports only integer indices
value=${i##*=}
params[$key]=$value
done
out_str=""
for param in $stack_params
do
param_index=$(echo ${param} | cksum | cut -d' ' -f1)
out_str="${out_str}ParameterKey=${param},"
if [ ${params[$param_index]+_} ]
then
out_str="${out_str}ParameterValue=\"${params[$param_index]}\""
else
out_str="${out_str}UsePreviousValue=true"
fi
out_str="${out_str} "
done
echo $out_str
}; f
get-cfn-params =
!f() {
stack_json=$(aws cloudformation describe-stacks --stack-name ${1})
echo ${stack_json} | jq -r '.Stacks[0].Parameters[] | { (.ParameterKey): .ParameterValue }' | jq -sS add
}; f
find-instances-in-sg =
!f() {
filter=${2:-Name}
for i in $(aws ec2 describe-instances --filters "Name=network-interface.group-id,Values=['${1}']" --query "Reservations[].Instances[].Tags[?Key == '${filter}'].Value[]" --output text)
do
echo ${i}
done
}; f
find-ssh-open = ec2 describe-security-groups \
--filters Name=ip-permission.from-port,Values=22 \
--query "SecurityGroups[].{
GroupName: GroupName,
GroupId: GroupId,
IPs: IpPermissions[?to_string(FromPort) == '22'][IpRanges[].CidrIp][][]
}"
delete-old-ecr-images =
!f() {
repository_name=${1}
leave_amount=${2:-10}
images=$(aws ecr describe-images --repository-name ${repository_name}) || exit $?
images_amount=$(echo ${images} | jq -r '.imageDetails | length')
[ "${images_amount}" -le "${leave_amount}" ] && echo "No old images found." && exit 255
delete_amount=$(expr ${images_amount} - ${leave_amount})
echo "Deleting ${delete_amount} image(s)"
image_digests=$(echo ${images} | jq -r '[(.imageDetails | sort_by(.imagePushedAt)[:'"${delete_amount}"'])[].imageDigest]|join(" imageDigest=")')
aws ecr batch-delete-image --repository-name ${repository_name} --image-ids imageDigest=${image_digests} || exit $?
}; f
describe-vpc-subnets =
!f() {
aws ec2 describe-subnets --filter="Name=vpc-id,Values=${1}" --query "Subnets[].{SubnetId: SubnetId, Name: Tags[?Key=='Name'].Value | [0], CidrBlock: CidrBlock}" | jq -r 'sort_by(.Name)'
}; f
list-newest-ecr-images =
!f() {
repository_name=${1}
show_amount=${2:-10}
images=$(aws ecr describe-images --repository-name ${repository_name}) || exit $?
images_amount=$(echo ${images} | jq -r '.imageDetails | length')
(>&2 echo "Found ${images_amount} images. Showing newest ${show_amount}.")
echo ${images} | jq -r '[(.imageDetails | sort_by(-.imagePushedAt)[:'"${show_amount}"'])[] | { imagePushedAt: .imagePushedAt | strftime("%Y-%m-%dT%H:%M:%SZ"), imageTags }]'
}; f
get-asg-instance-ips =
!f() {
asg_name=${1}
aws ec2 describe-instances --filters "Name=tag:aws:autoscaling:groupName,Values=${asg_name}" | jq -r '.Reservations[].Instances[].PrivateIpAddress'
}; f
find-host-by-instance-id =
!f() {
instance_id=${1}
aws ec2 describe-instances --filters "Name=instance-id,Values=${instance_id}" | jq -r '.Reservations[].Instances[].PrivateIpAddress' | sed -E 's/\./-/g; s/^/ip-/'
}; f
find-untagged-stacks =
!f() {
# use tag key as a parameter
aws cloudformation describe-stacks | jq -r '.Stacks[] | del(select(.Tags[].Key == "'$1'")) | select(.StackName != null) | .StackName'
}; f
find-instance-by-public-ip =
!f() {
aws ec2 describe-instances --filters "Name=ip-address,Values=$1" | jq -r '.Reservations[].Instances[].Tags[] | select(.Key == "Name").Value'
}; f
find-nat-gateway-by-public-ip =
!f() {
aws ec2 describe-nat-gateways | jq -r '.NatGateways[] | select(.NatGatewayAddresses[].PublicIp == "'$1'") | .Tags[] | select(.Key == "Name").Value'
}; f