-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathindex.ts
61 lines (55 loc) · 1.79 KB
/
index.ts
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
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { randomBytes } from "crypto";
import {
CloudFormationCustomResourceHandler,
CloudFormationCustomResourceDeleteEvent,
CloudFormationCustomResourceUpdateEvent,
} from "aws-lambda";
import { sendCfnResponse, Status } from "./cfn-response";
export const handler: CloudFormationCustomResourceHandler = async (event) => {
console.log(JSON.stringify(event, undefined, 4));
const { ResourceProperties } = event;
const { PhysicalResourceId } = event as
| CloudFormationCustomResourceDeleteEvent
| CloudFormationCustomResourceUpdateEvent;
const {
Length = 16,
AllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",
} = ResourceProperties;
let status = Status.SUCCESS;
let physicalResourceId: string | undefined;
let data: { [key: string]: any } | undefined;
let reason: string | undefined;
try {
physicalResourceId =
PhysicalResourceId ||
[...new Array(parseInt(Length))]
.map(() => randomChoiceFromIndexable(AllowedCharacters))
.join("");
} catch (err) {
console.error(err);
status = Status.FAILED;
reason = `${err}`;
}
await sendCfnResponse({
event,
status,
data,
physicalResourceId,
reason,
});
};
function randomChoiceFromIndexable(indexable: string) {
if (indexable.length > 256) {
throw new Error(`indexable is too large: ${indexable.length}`);
}
const chunks = Math.floor(256 / indexable.length);
const firstBiassedIndex = indexable.length * chunks;
let randomNumber: number;
do {
randomNumber = randomBytes(1)[0];
} while (randomNumber >= firstBiassedIndex);
const index = randomNumber % indexable.length;
return indexable[index];
}