-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
297 lines (284 loc) · 9.02 KB
/
index.js
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
'use strict';
module.exports = class ServerlessPlugin {
/**
*
* @param {Serverless} serverless Serverless object.
* @param {*} options Options object.
*/
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
'create-zone': {
lifecycleEvents: ['create'],
usage: 'Creates a Route 53 hosted zone.',
},
'remove-zone': {
lifecycleEvents: ['remove'],
usage: 'Removes a Route 53 hosted zone.',
},
'create-aliases': {
lifecycleEvents: ['create'],
usage: 'Creates Route 53 aliases.',
},
'remove-aliases': {
lifecycleEvents: ['remove'],
usage: 'Removes Route 53 aliases.',
},
};
this.hooks = {
// TODO: Enable the printSummary
// 'aws:info:displayStackOutputs': this.printSummary.bind(this),
// 'after:info:info': this.printSummary.bind(this),
'create-zone:create': this.createHostedZone.bind(this),
'remove-zone:remove': this.removeHostedZone.bind(this),
'create-aliases:create': this.createAliases.bind(this),
'remove-aliases:remove': this.createAliases.bind(this),
};
this.config =
this.serverless.service.custom &&
this.serverless.service.custom['hostedZone'];
this.provider = this.serverless.getProvider('aws');
}
/**
* Send a log message via the Serverless Framework.
* @param {any} msg
*/
log(msg) {
this.serverless.cli.log(`Hosted Zone: ${msg}`);
}
/**
* Throw an error via the Serverless Framework.
* @param {any} msg
*/
throwError(msg) {
throw new this.serverless.classes.Error(`Hosted Zone: ${msg}`);
}
/**
* Get those hosted zone from the config.
* @return {string} name
*/
getHostedZoneName() {
let { name } = this.config;
if (!/\.$/.test(name)) {
name += '.';
}
return name;
}
/**
* Get the hosted zone object from AWS.
* @return {Object} HostedZone object
*/
async getHostedZone() {
const name = this.getHostedZoneName();
const { HostedZones } = await this.provider.request(
'Route53',
'listHostedZones',
);
return HostedZones.find((x) => x.Name === name);
}
/**
* Logs that the module config is missing.
* @return {void}
*/
reportMissingConfig() {
this.log('Missing config. Skipping...');
}
/**
* Create a hosted zone.
* @return {void}
*/
async createHostedZone() {
if (!this.config) {
return this.reportMissingConfig();
}
const { vpc, config, delegationSetId } = this.config;
const name = this.getHostedZoneName();
this.log(`Attempting to create ${name}`);
try {
const hostedZone = await this.getHostedZone();
if (hostedZone) {
this.log(`${name} already exists.`);
return;
}
const createParams = {
CallerReference: new Date().toISOString(),
Name: name,
};
if (delegationSetId) {
createParams.DelegationSetId = delegationSetId;
}
if (vpc) {
if (!vpc.id) {
this.throwError(
`custom.hostedZone.vpc needs the id property.`,
);
}
if (!vpc.region) {
this.throwError(
`custom.hostedZone.vpc needs the region property.`,
);
}
createParams.VPC = {
VPCId: vpc.id,
VPCRegion: vpc.region,
};
}
if (config) {
createParams.HostedZoneConfig = {};
if (config.comment) {
createParams.HostedZoneConfig.Comment = config.comment;
}
if (config.private) {
createParams.HostedZoneConfig.PrivateZone =
config.privateZone;
}
if (!Object.keys(createParams.HostedZoneConfig).length) {
this.throwError(
'custom.hostedZone.config needs a ' +
'comment or private property.',
);
}
}
const { HostedZone } = await this.provider.request(
'Route53',
'createHostedZone',
createParams,
);
if (!HostedZone || !HostedZone.Id) {
this.throwError(`Failed to create ${name}`);
}
this.log(`Created ${name}`);
} catch (e) {
this.throwError(e.message);
}
}
/**
* Create the aliases.
* @return {void}
*/
async createAliases() {
if (!this.config) {
return this.reportMissingConfig();
}
const hostedZone = await this.getHostedZone();
const { aliases } = this.config;
if (hostedZone && aliases && Array.isArray(aliases)) {
aliases.forEach((alias, i) => {
switch (alias.type) {
case 'cloudfrontDistribution':
const { cname } = alias;
this.createDistributionAlias(cname, hostedZone);
break;
default:
this.log(
`Alias index ${i} does not have a valid entry.`,
);
}
});
} else {
this.log('No aliases to create.');
}
}
/**
* Create the alias for a CloudFront Distribution.
* @param {string} cname
* @param {object} hostedZone HostedZone object
* @return {void}
*/
async createDistributionAlias(cname, hostedZone) {
if (!hostedZone) {
this.throwError('Could not find the hosted zone.');
}
const hostedZoneId = hostedZone.Id.replace('/hostedzone/', '');
if (!/\.$/.test(cname)) {
cname += '.';
}
const { DistributionList } = await this.provider.request(
'CloudFront',
'listDistributions',
);
const distributions = DistributionList.Items || [];
const distribution = distributions.find((x) => {
const aliases = (x.Aliases || []).Items || [];
if (aliases.find((a) => `${a}.` === cname)) {
return x;
}
});
const listParams = {
HostedZoneId: hostedZoneId,
};
const { ResourceRecordSets } =
(await this.provider.request(
'Route53',
'listResourceRecordSets',
listParams,
)) || [];
const recordSet = ResourceRecordSets.find(
(x) => x.Name === cname && x.Type === 'A',
);
if (recordSet) {
this.log(`Route 53 record for ${cname} already exists.`);
return;
}
const createParams = {
ChangeBatch: {
Changes: [
{
Action: 'CREATE',
ResourceRecordSet: {
Name: cname,
Type: 'A',
AliasTarget: {
HostedZoneId: 'Z2FDTNDATAQYW2',
DNSName: distribution.DomainName,
EvaluateTargetHealth: false,
},
},
},
],
Comment: `CloudFront distribution for ${cname}`,
},
HostedZoneId: hostedZoneId,
};
await this.provider.request(
'Route53',
'changeResourceRecordSets',
createParams,
);
this.log(`Created alias ${cname}`);
}
/**
* Remove a hosted zone.
* @return {void}
*/
removeHostedZone() {
if (!this.config) {
return this.reportMissingConfig();
}
this.log('Removing...');
this.throwError('The remove feature currently does not exist.');
}
/**
* Remove the alias records.
* @return {void}
*/
removeAliasRecords() {
if (!this.config) {
return this.reportMissingConfig();
}
this.log('Removing...');
this.throwError('The remove feature currently does not exist.');
}
/**
* Print summary
* @return {void}
*/
printSummary() {
if (!this.config) {
return this.reportMissingConfig();
}
this.log('Summary...');
this.throwError('The summary feature currently does not exist.');
}
};