-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.js
More file actions
196 lines (175 loc) · 6.15 KB
/
Copy pathlib.js
File metadata and controls
196 lines (175 loc) · 6.15 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
import wildcard from 'wildcard';
import pLimit from 'p-limit';
import {paginateDescribeLaunchConfigurations} from '@aws-sdk/client-auto-scaling';
import {DescribeRegionsCommand, paginateDescribeInstances, DescribeLaunchTemplateVersionsCommand, paginateDescribeImages, DeregisterImageCommand, paginateDescribeLaunchTemplates} from '@aws-sdk/client-ec2';
function mapAMI(raw) {
return {
id: raw.ImageId,
name: raw.Name,
creationDate: Date.parse(raw.CreationDate),
tags: Array.isArray(raw.Tags) ? raw.Tags.reduce((acc, {Key: key, Value: value}) => {
acc[key] = value;
return acc;
}, {}) : {},
blockDeviceMappings: raw.BlockDeviceMappings.filter(raw => raw.Ebs).map(raw => ({snapshotId: raw.Ebs.SnapshotId})),
excluded: false,
excludeReasons: [],
included: false,
includeReasons: []
};
}
export async function fetchRegions(ec2, includeRegions, excludeRegions = []) {
const regions = new Set();
let allRegionNames = null;
const fetchAllRegionNames = async () => {
if (allRegionNames === null) {
const {Regions} = await ec2.send(new DescribeRegionsCommand({}));
allRegionNames = Regions.map(r => r.RegionName);
}
return allRegionNames;
};
if (includeRegions.length === 0) {
regions.add(undefined);
}
includeRegions.filter(region => !region.includes('*')).forEach(region => regions.add(region));
const includeRegionsWithWildcard = includeRegions.filter(region => region.includes('*'));
if (includeRegionsWithWildcard.length !== 0) {
const names = await fetchAllRegionNames();
includeRegionsWithWildcard.forEach(includeRegionWithWildcard => {
wildcard(includeRegionWithWildcard, names).forEach(region => regions.add(region));
});
}
if (excludeRegions.length > 0) {
const resolvedExcludes = new Set();
excludeRegions.filter(region => !region.includes('*')).forEach(region => resolvedExcludes.add(region));
const excludeRegionsWithWildcard = excludeRegions.filter(region => region.includes('*'));
if (excludeRegionsWithWildcard.length !== 0) {
const names = await fetchAllRegionNames();
excludeRegionsWithWildcard.forEach(excludeRegionWithWildcard => {
wildcard(excludeRegionWithWildcard, names).forEach(region => resolvedExcludes.add(region));
});
}
resolvedExcludes.forEach(region => regions.delete(region));
}
return regions;
}
export async function fetchInUseAMIIDs(ec2, autoscaling) {
const inUseAMIIDs = new Set();
const instancePaginator = paginateDescribeInstances({
client: ec2
}, {
Filters: [{
Name: 'instance-state-name',
Values: [
'pending',
'running',
'shutting-down',
'stopping',
'stopped'
]
}]
});
for await (const page of instancePaginator) {
for (const reservation of page.Reservations) {
reservation.Instances.forEach(instance => inUseAMIIDs.add(instance.ImageId));
}
}
const lcPaginator = paginateDescribeLaunchConfigurations({client: autoscaling}, {});
for await (const page of lcPaginator) {
page.LaunchConfigurations.forEach(lc => inUseAMIIDs.add(lc.ImageId));
}
const ltPaginator = paginateDescribeLaunchTemplates({client: ec2}, {});
const ltLimit = pLimit(5);
for await (const page of ltPaginator) {
await Promise.all(
page.LaunchTemplates.map(({LaunchTemplateId: id, DefaultVersionNumber: version}) => ltLimit(async () => {
const data = await ec2.send(new DescribeLaunchTemplateVersionsCommand({
LaunchTemplateId: id,
Versions: [version]
}));
inUseAMIIDs.add(data.LaunchTemplateVersions[0].LaunchTemplateData.ImageId);
}))
);
// CloudFormation does not update the default version of a launch template, therefore we are also considering the latest version as being used
await Promise.all(
page.LaunchTemplates.map(({LaunchTemplateId: id, LatestVersionNumber: version}) => ltLimit(async () => {
const data = await ec2.send(new DescribeLaunchTemplateVersionsCommand({
LaunchTemplateId: id,
Versions: [version]
}));
inUseAMIIDs.add(data.LaunchTemplateVersions[0].LaunchTemplateData.ImageId);
}))
);
}
return inUseAMIIDs;
}
export async function fetchAMIs(now, ec2, autoscaling, includeName, includeTagKey, includeTagValue, excludeNewest, excludeInUse, excludeDays) {
let amis = [];
const input = {
Owners: ['self']
};
if (includeTagKey !== undefined) {
input.Filters = [{
Name: 'tag-key',
Values: [includeTagKey]
}];
}
const paginator = paginateDescribeImages({
client: ec2
}, input);
for await (const page of paginator) {
page.Images.forEach(rawAMI => amis.push(mapAMI(rawAMI)));
}
if (includeName !== undefined) {
amis = amis.filter(ami => wildcard(includeName, ami.name)).map(ami => {
ami.included = true;
ami.includeReasons.push('name match');
return ami;
});
} else if (includeTagKey !== undefined) {
amis = amis.filter(ami => wildcard(includeTagValue, ami.tags[includeTagKey])).map(ami => {
ami.included = true;
ami.includeReasons.push('tag match');
return ami;
});
} else {
throw new Error('no include defined');
}
if (excludeInUse === true) {
const inUseAMIIDs = await fetchInUseAMIIDs(ec2, autoscaling);
amis = amis.map(ami => {
if (inUseAMIIDs.has(ami.id)) {
ami.excluded = true;
ami.excludeReasons.push('in use');
}
return ami;
});
}
if (excludeDays > 0) {
const ts = now-(excludeDays*24*60*60*1000);
amis = amis.map(ami => {
if (ami.creationDate > ts) {
ami.excluded = true;
ami.excludeReasons.push('days not passed');
}
return ami;
});
}
if (excludeNewest > 0) {
amis = amis.sort((a, b) => b.creationDate-a.creationDate).map((ami, i) => {
if (i < excludeNewest) {
ami.excluded = true;
ami.excludeReasons.push('newest');
}
return ami;
});
}
return amis;
}
export async function deleteAMI(ec2, ami) {
await ec2.send(new DeregisterImageCommand({
ImageId: ami.id,
DeleteAssociatedSnapshots: true
}));
console.log(`AMI ${ami.id} deregistered and deleted`);
}