This repository has been archived by the owner on May 30, 2023. It is now read-only.
forked from amplify-education/serverless-vpc-discovery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
175 lines (146 loc) · 5.01 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
'use strict';
const AWS = require('aws-sdk');
const _ = require('underscore');
class VPCPlugin {
constructor(serverless) {
this.serverless = serverless;
/* hooks are the acutal code that will run when called */
this.hooks = {
'before:package:initialize': this.updateVpcConfig.bind(this),
};
}
/**
* Gets the desired vpc with the designated subnets and security groups
* that were set in serverless config file
* @returns {Promise}
*/
updateVpcConfig() {
const awsCreds = this.serverless.providers.aws.getCredentials();
awsCreds.region = this.serverless.providers.aws.getRegion();
AWS.config.update(awsCreds);
AWS.config.update({
maxRetries: 20,
});
this.ec2 = new AWS.EC2();
this.serverless.cli.log('Updating VPC config...');
const { service } = this.serverless;
// Checks if the serverless file is setup correctly
if (service.custom.vpc.vpcName == null || service.custom.vpc.subnetNames == null
|| service.custom.vpc.securityGroupNames == null) {
throw new Error('Serverless file is not configured correctly. Please see README for proper setup.');
}
// Returns the vpc with subnet and security group ids
return this.getVpcId(service.custom.vpc.vpcName).then((vpcId) => {
const promises = [
this.getSubnetIds(vpcId, service.custom.vpc.subnetNames),
this.getSecurityGroupIds(vpcId, service.custom.vpc.securityGroupNames),
];
return (Promise.all(promises).then((values) => {
// Checks to see if either subnets or security gropus returned nothing
if (!values[0].length || !values[1].length) {
throw new Error('Vpc was not set');
}
// Sets the serverless's vpc config
service.provider.vpc = {
subnetIds: values[0],
securityGroupIds: values[1],
};
return service.provider.vpc;
}));
}).catch((err) => {
throw new Error(`Could not set vpc config. Message: ${err}`);
});
}
/**
* Returns the promise that contains the vpc-id
* @param {string} vpcName
* @returns {Promise.<string>}
*/
getVpcId(vpcName) {
const vpcParams = {
Filters: [{
Name: 'tag:Name',
Values: [vpcName],
}],
};
return this.ec2.describeVpcs(vpcParams).promise().then((data) => {
// If it cannot find a vpc, vpc does not exist for that name
if (data.Vpcs.length === 0) {
throw new Error('Invalid vpc name, it does not exist');
}
return data.Vpcs[0].VpcId;
});
}
/**
* Returns the promise that contains the subnet IDs
*
* @param {string} vpcId
* @param {string[]} subnetNames
* @returns {Promise.<string[]>}
*/
getSubnetIds(vpcId, subnetNames) {
const paramsSubnet = {
Filters: [{
Name: 'vpc-id',
Values: [vpcId],
}, {
Name: 'tag:Name',
Values: subnetNames,
}],
};
return this.ec2.describeSubnets(paramsSubnet).promise().then((data) => {
if (data.Subnets.length === 0) {
throw new Error('Invalid subnet name, it does not exist');
}
if (paramsSubnet.Filters[1].Values.length !== data.Subnets.length) {
// Creates a list of the valid subnets
const validSubnets = data.Subnets.reduce((accum, val) => {
const nameTag = val.Tags.find((tag) => tag.Key === 'Name');
if (nameTag) {
accum.push(nameTag.Value);
}
return accum;
}, []);
// Compares the valid subents with ones given to find invalid subnet names
const missingSubnets = _.difference(paramsSubnet.Filters[1].Values, validSubnets);
throw new Error(`Not all subnets were registered: ${missingSubnets}`);
}
return data.Subnets.map((obj) => obj.SubnetId);
});
}
/**
* Returns the promise that contains the security group IDs
* @param {string} vpcId
* @param {string[]} securityGroupNames
* @returns {Promise.<string[]>}
*/
getSecurityGroupIds(vpcId, securityGroupNames) {
const paramsSecurity = {
Filters: [{
Name: 'vpc-id',
Values: [vpcId],
}, {
Name: 'tag:Name',
Values: securityGroupNames,
}],
};
return this.ec2.describeSecurityGroups(paramsSecurity).promise().then((data) => {
if (data.SecurityGroups.length === 0) {
throw new Error('Invalid security group name, it does not exist');
}
if (paramsSecurity.Filters[1].Values.length !== data.SecurityGroups.length) {
const validGroups = data.SecurityGroups.reduce((accum, val) => {
const nameTag = val.Tags.find((tag) => tag.Key === 'Name');
if (nameTag) {
accum.push(nameTag.Value);
}
return accum;
}, []);
const missingGroups = _.difference(paramsSecurity.Filters[1].Values, validGroups);
throw new Error(`Not all security group were registered: ${missingGroups}`);
}
return data.SecurityGroups.map((obj) => obj.GroupId);
});
}
}
module.exports = VPCPlugin;