-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhandler.js
More file actions
executable file
·287 lines (251 loc) · 9.04 KB
/
Copy pathhandler.js
File metadata and controls
executable file
·287 lines (251 loc) · 9.04 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
"use strict";
const {
ECRClient,
DescribeImagesCommand,
BatchDeleteImageCommand,
} = require("@aws-sdk/client-ecr");
const moment = require("moment");
const filter = require("lodash.filter");
const rp = require("request-promise");
function postToSlack(text) {
if (typeof process.env.SLACK_WEBHOOK === "undefined") {
return Promise.resolve(text);
}
const options = {
method: "POST",
uri: process.env.SLACK_WEBHOOK,
body: { text },
json: true,
};
return rp(options);
}
async function getAllImages(ecr, registryId, repoName) {
const params = {
registryId: registryId,
repositoryName: repoName,
maxResults: 100,
};
const data = await ecr.send(new DescribeImagesCommand(params));
return data.imageDetails;
}
function buildReport(
isDryRun,
reposNotFound,
reposWithUntaggedImages,
reposWithDeletedImagesDryRun,
reposWithDeletedImages,
reposWithImagesThatFailedToDelete,
) {
const untaggedRepoKeys = Object.keys(reposWithUntaggedImages);
const deletedDryRunRepoKeys = Object.keys(reposWithDeletedImagesDryRun);
const deletedRepoKeys = Object.keys(reposWithDeletedImages);
const failedToDeletedRepoKeys = Object.keys(
reposWithImagesThatFailedToDelete,
);
if (
reposNotFound.length === 0 &&
untaggedRepoKeys.length === 0 &&
deletedDryRunRepoKeys === 0 &&
deletedRepoKeys.length === 0 &&
failedToDeletedRepoKeys === 0
) {
return "Robin ran but there no vigilamnte justice was needed";
}
const backticks = (str) => `\`${str}\``;
const dryRunText = isDryRun ? " [DRY RUN]" : "";
let text = "Robin has attempted to clean up the streets!";
if (reposNotFound.length !== 0) {
text += "\n\n\n===================================================";
text += `\nRepositories not found (${reposNotFound.length})${dryRunText}`;
text += "\n===================================================";
reposNotFound.forEach((repoName) => {
text += `\n${backticks(repoName)}`;
});
}
if (untaggedRepoKeys.length !== 0) {
text += "\n\n\n===================================================";
text += `\nRepositories with untagged images (${untaggedRepoKeys.length})${dryRunText}`;
text += "\n===================================================";
untaggedRepoKeys.forEach((repoName) => {
text += `\n${backticks(repoName)} - ${
reposWithUntaggedImages[repoName]
} image${reposWithUntaggedImages[repoName] > 1 ? "s" : ""}`;
});
}
if (isDryRun) {
text += "\n\n\n===================================================";
text += `\nRepositories with images deleted (${deletedDryRunRepoKeys.length})${dryRunText}`;
text += "\n===================================================";
if (deletedDryRunRepoKeys.length === 0) {
text += "\nNo images deleted";
} else {
deletedDryRunRepoKeys.forEach((repoName) => {
// eslint-disable-next-line max-len
text += `\n${backticks(repoName)} (${
reposWithDeletedImagesDryRun[repoName].length
} tags): ${reposWithDeletedImagesDryRun[repoName].join(", ")}`;
});
}
} else {
text += "\n\n\n===================================================";
text += `\nRepositories with images deleted (${deletedRepoKeys.length})`;
text += "\n===================================================";
if (deletedRepoKeys.length === 0) {
text += "\nNo images deleted";
} else {
deletedRepoKeys.forEach((repoName) => {
text += `\n${backticks(repoName)} (${
reposWithDeletedImages[repoName].length
} tags): ${reposWithDeletedImages[repoName].join(", ")}`;
});
}
if (failedToDeletedRepoKeys.length !== 0) {
text += "\n\n\n===================================================";
text += `\nRepositories with images that failed deleted (${failedToDeletedRepoKeys.length})`;
text += "\n===================================================";
deletedRepoKeys.forEach((repoName) => {
// eslint-disable-next-line max-len
text += `\n${backticks(repoName)} (${
reposWithImagesThatFailedToDelete[repoName].length
} tags): ${reposWithImagesThatFailedToDelete[repoName].join(", ")}`;
});
}
}
return text;
}
module.exports.cleanupImages = (event, context, callback) => {
if (typeof process.env.REPO_NAMES === "undefined") {
throw new Error(
"Can't start lambda: missing REPO_NAMES environment variable",
);
}
if (typeof process.env.AWS_ACCOUNT_ID === "undefined") {
throw new Error(
"Can't start lambda: missing AWS_ACCOUNT_ID environment variable",
);
}
const repoNames = process.env.REPO_NAMES.split(",");
const registry = process.env.AWS_ACCOUNT_ID;
const ecrRegion = process.env.ECR_REGION || "ap-southeast-2";
const ecr = new ECRClient({ region: ecrRegion });
const reposNotFound = [];
const reposWithUntaggedImages = {};
const reposWithDeletedImages = {};
const reposWithDeletedImagesDryRun = {};
const reposWithImagesThatFailedToDelete = {};
console.log("Robin is dealing out some of his own justice...");
console.log("Robin is using ECR Region: ", ecrRegion);
const isDryRun = process.env.DRY_RUN === "true";
console.log("Robin is running in dry run mode: ", isDryRun);
const cutOffDate = moment().add(-30, "d");
console.log("Using cut off date: ", cutOffDate);
const promises = repoNames.map((repoName) =>
getAllImages(ecr, registry, repoName)
.then((images) => {
// eslint-disable-line arrow-body-style
return filter(images, (image) => {
const isUntagged = typeof image.imageTags === "undefined";
if (isUntagged) {
if (typeof reposWithUntaggedImages[repoName] !== "number") {
reposWithUntaggedImages[repoName] = 1;
} else {
reposWithUntaggedImages[repoName]++;
}
return false;
}
// filters out images that are 30 days old and don't contain the master tag
return (
!isUntagged &&
moment(image.imagePushedAt).isBefore(cutOffDate) &&
!image.imageTags.find(
(tag) => tag.indexOf("master") > -1 || tag.indexOf("main") > -1,
)
);
});
})
.then(async (toDelete) => {
if (!toDelete || toDelete.length === 0) {
return Promise.resolve({ imageIds: "none", failures: "none" });
}
console.log("Images to delete: ", toDelete);
const convertedToDelete = toDelete.map((image) => {
if (isDryRun) {
image.imageTags.forEach((tag) => {
if (
typeof reposWithDeletedImagesDryRun[repoName] === "undefined"
) {
reposWithDeletedImagesDryRun[repoName] = [];
}
reposWithDeletedImagesDryRun[repoName].push(tag);
});
}
return { imageDigest: image.imageDigest };
});
if (isDryRun) {
return Promise.resolve({ imageIds: [], failures: [] });
}
const deleteParams = {
registryId: registry,
repositoryName: repoName,
imageIds: convertedToDelete,
};
return await ecr
.send(new BatchDeleteImageCommand(deleteParams))
.then((response) => {
console.log("failures: ", response.failures);
console.log("imageIds: ", response.imageIds);
response.failures.forEach(({ imageId }) => {
if (
typeof reposWithImagesThatFailedToDelete[repoName] ===
"undefined"
) {
reposWithImagesThatFailedToDelete[repoName] = [];
}
reposWithImagesThatFailedToDelete[repoName].push(
imageId.imageTag,
);
});
response.imageIds.forEach(({ imageTag }) => {
if (typeof reposWithDeletedImages[repoName] === "undefined") {
reposWithDeletedImages[repoName] = [];
}
reposWithDeletedImages[repoName].push(imageTag);
});
});
})
.catch((err) => {
if (
err.code === "RepositoryNotFoundException" &&
reposNotFound.indexOf(repoName) === -1
) {
reposNotFound.push(repoName);
}
console.log(err);
}),
);
return Promise.all(promises)
.then(() => {
const reportText = buildReport(
isDryRun,
reposNotFound,
reposWithUntaggedImages,
reposWithDeletedImagesDryRun,
reposWithDeletedImages,
reposWithImagesThatFailedToDelete,
);
// Log Results
console.log(reportText.replace(/`/g, "")); // strip backticks when logging to CloudWatch (backticks are for Slack!)
return Promise.resolve(reportText);
})
.then(
(text) => postToSlack(text), // Post results to Slack
)
.then(() => {
callback(null, { message: "robin executed successfully!", event });
})
.catch((err) => {
console.log(err); // an error occurred
callback(err);
return;
});
};