forked from lucianopf/domain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverless.js
More file actions
293 lines (257 loc) · 10.3 KB
/
serverless.js
File metadata and controls
293 lines (257 loc) · 10.3 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
292
293
const { Component } = require('@serverless/core')
const {
getClients,
prepareSubdomains,
getDomainHostedZoneId,
describeCertificateByArn,
getCertificateArnByDomain,
createCertificate,
validateCertificate,
createCloudfrontDistribution,
updateCloudfrontDistribution,
getCloudFrontDistributionByDomain,
invalidateCloudfrontDistribution,
deployApiDomain,
removeApiDomain,
removeApiDomainDnsRecords,
configureDnsForCloudFrontDistribution,
getApiDomainName,
removeCloudFrontDomainDnsRecords,
addDomainToCloudfrontDistribution,
removeDomainFromCloudFrontDistribution,
waitForDistributionDeployed,
addLambdaTrigger
} = require('./utils')
class Domain extends Component {
/**
* Remove
*/
async default(inputs = {}) {
this.context.status('Deploying')
this.context.debug(`Starting Domain component deployment.`)
this.context.debug(`Validating inputs.`)
inputs.region = inputs.region || 'us-east-1'
inputs.privateZone = inputs.privateZone || false
if (!inputs.domain) {
throw Error(`"domain" is a required input.`)
}
// TODO: Check if domain has changed.
// On domain change, call remove for all previous state.
// Get AWS SDK Clients
const clients = getClients(this.context.credentials.aws, inputs.region)
this.context.debug(`Formatting domains and identifying cloud services being used.`)
const subdomains = prepareSubdomains(inputs)
this.state.region = inputs.region
this.state.privateZone = JSON.parse(inputs.privateZone)
this.state.domain = inputs.domain
this.state.subdomains = subdomains
await this.save()
this.context.debug(`Getting the Hosted Zone ID for the domain ${inputs.domain}.`)
const domainHostedZoneId = await getDomainHostedZoneId(
clients.route53,
inputs.domain,
inputs.privateZone
)
this.context.debug(
`Searching for an AWS ACM Certificate based on the domain: ${inputs.domain}.`
)
let certificateArn = await getCertificateArnByDomain(clients.acm, inputs.domain)
if (!certificateArn) {
this.context.debug(`No existing AWS ACM Certificates found for the domain: ${inputs.domain}.`)
this.context.debug(`Creating a new AWS ACM Certificate for the domain: ${inputs.domain}.`)
certificateArn = await createCertificate(clients.acm, inputs.domain)
}
this.context.debug(`Checking the status of AWS ACM Certificate.`)
const certificate = await describeCertificateByArn(clients.acm, certificateArn)
if (certificate.Status === 'PENDING_VALIDATION') {
this.context.debug(`AWS ACM Certificate Validation Status is "PENDING_VALIDATION".`)
this.context.debug(`Validating AWS ACM Certificate via Route53 "DNS" method.`)
await validateCertificate(
clients.acm,
clients.route53,
certificate,
inputs.domain,
domainHostedZoneId
)
this.context.log(
'Your AWS ACM Certificate has been created and is being validated via DNS. This could take up to 30 minutes since it depends on DNS propagation. Continuining deployment, but you may have to wait for DNS propagation.'
)
}
if (certificate.Status !== 'ISSUED' && certificate.Status !== 'PENDING_VALIDATION') {
// TODO: Should we auto-create a new one in this scenario?
throw new Error(
`Your AWS ACM Certificate for the domain "${inputs.domain}" has an unsupported status of: "${certificate.Status}". Please remove it manually and deploy again.`
)
}
// Setting up domains for different services
for (const subdomain of subdomains) {
const lambda = await this.load('@ublend-npm/aws-lambda')
this.context.debug(
subdomain.triggers ? 'Adding lambda triggers' : 'No lambda triggers to configure'
)
const triggers =
subdomain.triggers || subdomain.customLambdaAssociations
? await addLambdaTrigger(lambda, subdomain)
: []
if (subdomain.type === 'awsS3Website') {
this.context.debug(`Configuring domain "${subdomain.domain}" for S3 Bucket Website`)
this.context.debug(`Checking CloudFront distribution for domain "${subdomain.domain}"`)
let distribution = await getCloudFrontDistributionByDomain(clients.cf, subdomain.domain)
if (!distribution) {
this.context.debug(
`CloudFront distribution for domain "${subdomain.domain}" not found. Creating...`
)
distribution = await createCloudfrontDistribution(
clients.cf,
subdomain,
certificate.CertificateArn,
inputs.region,
triggers
)
if (subdomain.waitForCreateDistribution) {
this.context.debug(`Waiting for create cloudfront distribution complete ....`)
await waitForDistributionDeployed(clients.cf, distribution.id)
}
} else if (
!distribution.origins.includes(`${subdomain.s3BucketName}.s3.amazonaws.com`) ||
!distribution.errorPages
) {
this.context.debug(`Updating distribution "${distribution.url}".`)
distribution = await updateCloudfrontDistribution(
clients.cf,
subdomain,
distribution.id,
inputs.region,
triggers,
certificateArn
)
if (subdomain.waitForUpdateDistribution) {
this.context.debug(`Waiting for update cloudfront distribution complete ....`)
await waitForDistributionDeployed(clients.cf, distribution.id)
}
}
this.context.debug(`Configuring DNS for distribution "${distribution.url}".`)
await configureDnsForCloudFrontDistribution(
clients.route53,
subdomain,
domainHostedZoneId,
distribution.url
)
this.context.debug(`Invalidating CloudFront distribution ${distribution.url}`)
await invalidateCloudfrontDistribution(clients.cf, distribution.id)
this.context.debug(`Using AWS Cloudfront Distribution with URL: "${subdomain.domain}"`)
} else if (subdomain.type === 'awsApiGateway') {
// Map APIG domain to API ID and recursively retry
// if APIG domain need to be created first, or TooManyRequests error is thrown
await deployApiDomain(
clients.apig,
clients.route53,
subdomain,
certificate.CertificateArn,
domainHostedZoneId,
this // passing instance for helpful logs during the process
)
} else if (subdomain.type === 'awsCloudFront') {
this.context.debug(
`Adding ${subdomain.domain} domain to CloudFront distribution with URL "${subdomain.url}"`
)
await addDomainToCloudfrontDistribution(clients.cf, subdomain, certificate.CertificateArn)
this.context.debug(`Configuring DNS for distribution "${subdomain.url}".`)
await configureDnsForCloudFrontDistribution(
clients.route53,
subdomain,
domainHostedZoneId,
subdomain.url.replace('https://', '')
)
}
// TODO: Remove unused domains that are kept in state
}
const outputs = {}
let hasRoot = false
outputs.domains = subdomains.map((subdomain) => {
if (subdomain.domain.startsWith('www')) {
hasRoot = true
}
return `https://${subdomain.domain}`
})
if (hasRoot) {
outputs.domains.unshift(`https://${inputs.domain.replace('www.', '')}`)
}
return outputs
}
/**
* Remove
*/
async remove() {
this.context.status('Deploying')
if (!this.state.domain) {
return
}
this.context.debug(`Starting Domain component removal.`)
// Get AWS SDK Clients
const clients = getClients(this.context.credentials.aws, this.state.region)
this.context.debug(`Getting the Hosted Zone ID for the domain ${this.state.domain}.`)
const domainHostedZoneId = await getDomainHostedZoneId(
clients.route53,
this.state.domain,
this.state.privateZone
)
for (const subdomain in this.state.subdomains) {
const domainState = this.state.subdomains[subdomain]
if (domainState.type === 'awsS3Website') {
this.context.debug(
`Fetching CloudFront distribution info for removal for domain ${domainState.domain}.`
)
const distribution = await getCloudFrontDistributionByDomain(clients.cf, domainState.domain)
if (distribution) {
this.context.debug(`Removing DNS records for website domain ${domainState.domain}.`)
await removeCloudFrontDomainDnsRecords(
clients.route53,
domainState.domain,
domainHostedZoneId,
distribution.url
)
if (domainState.domain.startsWith('www')) {
await removeCloudFrontDomainDnsRecords(
clients.route53,
domainState.domain.replace('www.', ''), // it'll move on if it doesn't exist
domainHostedZoneId,
distribution.url
)
}
}
} else if (domainState.type === 'awsApiGateway') {
this.context.debug(
`Fetching API Gateway domain ${domainState.domain} information for removal.`
)
const domainRes = await getApiDomainName(clients.apig, domainState.domain)
if (domainRes) {
this.context.debug(`Removing API Gateway domain ${domainState.domain}.`)
await removeApiDomain(clients.apig, domainState.domain)
this.context.debug(`Removing DNS records for API Gateway domain ${domainState.domain}.`)
await removeApiDomainDnsRecords(
clients.route53,
domainState.domain,
domainHostedZoneId,
domainRes.distributionHostedZoneId,
domainRes.distributionDomainName
)
}
} else if (domainState.type === 'awsCloudFront') {
this.context.debug(`Removing domain ${domainState.domain} from CloudFront.`)
await removeDomainFromCloudFrontDistribution(clients.cf, domainState)
this.context.debug(`Removing CloudFront DNS records for domain ${domainState.domain}`)
await removeCloudFrontDomainDnsRecords(
clients.route53,
domainState.domain,
domainHostedZoneId,
domainState.url.replace('https://', '')
)
}
}
this.state = {}
await this.save()
return {}
}
}
module.exports = Domain