-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
integ.eks-cluster.ts
328 lines (273 loc) · 10.2 KB
/
integ.eks-cluster.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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/// !cdk-integ pragma:ignore-assets pragma:disable-update-workflow
import * as path from 'path';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as kms from '@aws-cdk/aws-kms';
import { Asset } from '@aws-cdk/aws-s3-assets';
import { App, CfnOutput, Duration, Token, Fn, Stack, StackProps } from '@aws-cdk/core';
import * as cdk8s from 'cdk8s';
import * as kplus from 'cdk8s-plus-21';
import * as constructs from 'constructs';
import * as hello from './hello-k8s';
import * as eks from '../lib';
class EksClusterStack extends Stack {
private cluster: eks.Cluster;
private vpc: ec2.IVpc;
constructor(scope: App, id: string, props?: StackProps) {
super(scope, id, props);
// allow all account users to assume this role in order to admin the cluster
const mastersRole = new iam.Role(this, 'AdminRole', {
assumedBy: new iam.AccountRootPrincipal(),
});
const secretsEncryptionKey = new kms.Key(this, 'SecretsKey');
// just need one nat gateway to simplify the test
this.vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 3, natGateways: 1 });
// create the cluster with a default nodegroup capacity
this.cluster = new eks.Cluster(this, 'Cluster', {
vpc: this.vpc,
mastersRole,
defaultCapacity: 2,
version: eks.KubernetesVersion.of('1.22'),
secretsEncryptionKey,
tags: {
foo: 'bar',
},
clusterLogging: [
eks.ClusterLoggingTypes.API,
eks.ClusterLoggingTypes.AUTHENTICATOR,
eks.ClusterLoggingTypes.SCHEDULER,
],
});
this.assertFargateProfile();
this.assertCapacityX86();
this.assertCapacityArm();
this.assertBottlerocket();
this.assertSpotCapacity();
this.assertNodeGroupX86();
this.assertNodeGroupSpot();
this.assertNodeGroupArm();
this.assertNodeGroupCustomAmi();
this.assertSimpleManifest();
this.assertManifestWithoutValidation();
this.assertSimpleHelmChart();
this.assertHelmChartAsset();
this.assertSimpleCdk8sChart();
this.assertCreateNamespace();
this.assertServiceAccount();
this.assertExtendedServiceAccount();
new CfnOutput(this, 'ClusterEndpoint', { value: this.cluster.clusterEndpoint });
new CfnOutput(this, 'ClusterArn', { value: this.cluster.clusterArn });
new CfnOutput(this, 'ClusterCertificateAuthorityData', { value: this.cluster.clusterCertificateAuthorityData });
new CfnOutput(this, 'ClusterSecurityGroupId', { value: this.cluster.clusterSecurityGroupId });
new CfnOutput(this, 'ClusterEncryptionConfigKeyArn', { value: this.cluster.clusterEncryptionConfigKeyArn });
new CfnOutput(this, 'ClusterName', { value: this.cluster.clusterName });
}
private assertServiceAccount() {
// add a service account connected to a IAM role
this.cluster.addServiceAccount('MyServiceAccount');
}
private assertExtendedServiceAccount() {
// add a service account connected to a IAM role
this.cluster.addServiceAccount('MyExtendedServiceAccount', {
annotations: {
'eks.amazonaws.com/sts-regional-endpoints': 'false',
},
labels: {
'some-label': 'with-some-value',
},
});
}
private assertCreateNamespace() {
// deploy an nginx ingress in a namespace
const nginxNamespace = this.cluster.addManifest('nginx-namespace', {
apiVersion: 'v1',
kind: 'Namespace',
metadata: {
name: 'nginx',
},
});
const nginxIngress = this.cluster.addHelmChart('nginx-ingress', {
chart: 'nginx-ingress',
repository: 'https://helm.nginx.com/stable',
namespace: 'nginx',
wait: true,
createNamespace: false,
timeout: Duration.minutes(15),
});
// make sure namespace is deployed before the chart
nginxIngress.node.addDependency(nginxNamespace);
}
private assertSimpleCdk8sChart() {
class Chart extends cdk8s.Chart {
constructor(scope: constructs.Construct, ns: string, cluster: eks.ICluster) {
super(scope, ns);
new kplus.ConfigMap(this, 'config-map', {
data: {
clusterName: cluster.clusterName,
},
});
}
}
const app = new cdk8s.App();
const chart = new Chart(app, 'Chart', this.cluster);
this.cluster.addCdk8sChart('cdk8s-chart', chart);
}
private assertSimpleHelmChart() {
// deploy the Kubernetes dashboard through a helm chart
this.cluster.addHelmChart('dashboard', {
chart: 'kubernetes-dashboard',
repository: 'https://kubernetes.github.io/dashboard/',
});
}
private assertHelmChartAsset() {
// get helm chart from Asset
const chartAsset = new Asset(this, 'ChartAsset', {
path: path.join(__dirname, 'test-chart'),
});
this.cluster.addHelmChart('test-chart', {
chartAsset: chartAsset,
});
}
private assertSimpleManifest() {
// apply a kubernetes manifest
this.cluster.addManifest('HelloApp', ...hello.resources);
}
private assertManifestWithoutValidation() {
// apply a kubernetes manifest
new eks.KubernetesManifest(this, 'HelloAppWithoutValidation', {
cluster: this.cluster,
manifest: [{
apiVersion: 'v1',
kind: 'ConfigMap',
data: { hello: 'world' },
metadata: { name: 'config-map' },
unknown: { key: 'value' },
}],
skipValidation: true,
});
}
private assertNodeGroupX86() {
// add a extra nodegroup
this.cluster.addNodegroupCapacity('extra-ng', {
instanceType: new ec2.InstanceType('t3.small'),
minSize: 1,
// reusing the default capacity nodegroup instance role when available
nodeRole: this.cluster.defaultCapacity ? this.cluster.defaultCapacity.role : undefined,
});
}
private assertNodeGroupSpot() {
// add a extra nodegroup
this.cluster.addNodegroupCapacity('extra-ng-spot', {
instanceTypes: [
new ec2.InstanceType('c5.large'),
new ec2.InstanceType('c5a.large'),
new ec2.InstanceType('c5d.large'),
],
minSize: 3,
// reusing the default capacity nodegroup instance role when available
nodeRole: this.cluster.defaultCapacity ? this.cluster.defaultCapacity.role : undefined,
capacityType: eks.CapacityType.SPOT,
});
}
private assertNodeGroupCustomAmi() {
// add a extra nodegroup
const userData = ec2.UserData.forLinux();
userData.addCommands(
'set -o xtrace',
`/etc/eks/bootstrap.sh ${this.cluster.clusterName}`,
);
const lt = new ec2.CfnLaunchTemplate(this, 'LaunchTemplate', {
launchTemplateData: {
imageId: new eks.EksOptimizedImage({
kubernetesVersion: eks.KubernetesVersion.of('1.22').version,
}).getImage(this).imageId,
instanceType: new ec2.InstanceType('t3.small').toString(),
userData: Fn.base64(userData.render()),
},
});
this.cluster.addNodegroupCapacity('extra-ng2', {
minSize: 1,
// reusing the default capacity nodegroup instance role when available
nodeRole: this.cluster.defaultNodegroup?.role || this.cluster.defaultCapacity?.role,
launchTemplateSpec: {
id: lt.ref,
version: lt.attrDefaultVersionNumber,
},
});
}
private assertNodeGroupArm() {
// add a extra nodegroup
this.cluster.addNodegroupCapacity('extra-ng-arm', {
instanceType: new ec2.InstanceType('m6g.medium'),
minSize: 1,
// reusing the default capacity nodegroup instance role when available
nodeRole: this.cluster.defaultCapacity ? this.cluster.defaultCapacity.role : undefined,
});
}
private assertSpotCapacity() {
// spot instances (up to 10)
this.cluster.addAutoScalingGroupCapacity('spot', {
spotPrice: '0.1094',
instanceType: new ec2.InstanceType('t3.large'),
maxCapacity: 10,
bootstrapOptions: {
kubeletExtraArgs: '--node-labels foo=bar,goo=far',
awsApiRetryAttempts: 5,
},
});
}
private assertBottlerocket() {
// add bottlerocket nodes
this.cluster.addAutoScalingGroupCapacity('BottlerocketNodes', {
instanceType: new ec2.InstanceType('t3.small'),
minCapacity: 2,
machineImageType: eks.MachineImageType.BOTTLEROCKET,
});
}
private assertCapacityX86() {
// add some x86_64 capacity to the cluster. The IAM instance role will
// automatically be mapped via aws-auth to allow nodes to join the cluster.
this.cluster.addAutoScalingGroupCapacity('Nodes', {
instanceType: new ec2.InstanceType('t2.medium'),
minCapacity: 3,
});
}
private assertCapacityArm() {
// add some arm64 capacity to the cluster. The IAM instance role will
// automatically be mapped via aws-auth to allow nodes to join the cluster.
this.cluster.addAutoScalingGroupCapacity('NodesArm', {
instanceType: new ec2.InstanceType('m6g.medium'),
minCapacity: 1,
});
}
private assertFargateProfile() {
// fargate profile for resources in the "default" namespace
this.cluster.addFargateProfile('default', {
selectors: [{ namespace: 'default' }],
});
}
}
// this test uses both the bottlerocket image and the inf1 instance, which are only supported in these
// regions. see https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-eks#bottlerocket
// and https://aws.amazon.com/about-aws/whats-new/2019/12/introducing-amazon-ec2-inf1-instances-high-performance-and-the-lowest-cost-machine-learning-inference-in-the-cloud/
const supportedRegions = [
'us-east-1',
'us-west-2',
];
const app = new App();
// since the EKS optimized AMI is hard-coded here based on the region,
// we need to actually pass in a specific region.
const stack = new EksClusterStack(app, 'aws-cdk-eks-cluster-test', {
env: { region: 'us-east-1' },
});
if (process.env.CDK_INTEG_ACCOUNT !== '12345678') {
// only validate if we are about to actually deploy.
// TODO: better way to determine this, right now the 'CDK_INTEG_ACCOUNT' seems like the only way.
if (Token.isUnresolved(stack.region)) {
throw new Error(`region (${stack.region}) cannot be a token and must be configured to one of: ${supportedRegions}`);
}
if (!supportedRegions.includes(stack.region)) {
throw new Error(`region (${stack.region}) must be configured to one of: ${supportedRegions}`);
}
}
app.synth();