-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy patheks-service.ts
228 lines (213 loc) · 9.3 KB
/
eks-service.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
#!/usr/bin/env node
import * as cdk from '@aws-cdk/core';
import {Certificate} from '@aws-cdk/aws-certificatemanager';
import {Vpc} from '@aws-cdk/aws-ec2';
import {Repository} from '@aws-cdk/aws-ecr';
import {FargateCluster, KubernetesManifest, KubernetesVersion} from '@aws-cdk/aws-eks';
import {ContainerImage} from '@aws-cdk/aws-ecs';
import {AccountRootPrincipal, Effect, FederatedPrincipal, ManagedPolicy, PolicyStatement, Role} from '@aws-cdk/aws-iam';
import {StringParameter} from '@aws-cdk/aws-ssm';
import {ReinventTriviaResource} from './eks/kubernetes-resources/reinvent-trivia';
import {AlbIngressControllerPolicy} from './eks/alb-ingress-controller-policy';
import {HostedZone} from '@aws-cdk/aws-route53';
interface TriviaBackendStackProps extends cdk.StackProps {
domainName: string;
domainZone: string;
oidcProvider?: string;
}
class TriviaBackendStack extends cdk.Stack {
constructor(parent: cdk.App, name: string, props: TriviaBackendStackProps) {
super(parent, name, props);
// Network infrastructure
const vpc = new Vpc(this, 'VPC', {maxAzs: 2});
// Initial creation of the cluster
const cluster = new FargateCluster(this, 'FargateCluster', {
clusterName: props.domainName.replace(/\./g, '-'),
defaultProfile: {
fargateProfileName: 'reinvent-trivia',
selectors: [
{namespace: 'default'},
{namespace: 'kube-system'},
{namespace: 'reinvent-trivia'},
],
subnetSelection: {subnets: vpc.privateSubnets},
},
mastersRole: new Role(this, 'ClusterAdminRole', {
assumedBy: new AccountRootPrincipal(),
}),
outputClusterName: true,
outputConfigCommand: true,
outputMastersRoleArn: true,
vpc,
version: KubernetesVersion.V1_17,
});
const fargateProfile = cluster.node.findChild('fargate-profile-reinvent-trivia');
// Configuration parameters
const imageRepo = Repository.fromRepositoryName(this, 'Repo', 'reinvent-trivia-backend');
const tag = (process.env.IMAGE_TAG) ? process.env.IMAGE_TAG : 'latest';
const image = ContainerImage.fromEcrRepository(imageRepo, tag)
// Lookup pre-existing TLS certificate
const certificateArn = StringParameter.fromStringParameterAttributes(this, 'CertArnParameter', {
parameterName: 'CertificateArn-' + props.domainName
}).stringValue;
const certificate = Certificate.fromCertificateArn(this, 'Cert', certificateArn);
// Kubernetes resources for the ReinventTrivia namespace, deployment, service, etc.
const reinventTrivia = new ReinventTriviaResource(this, 'ReinventTrivia', {
cluster, certificate, image, domainName: props.domainName
});
reinventTrivia.node.addDependency(fargateProfile);
const metricsServerChart = cluster.addHelmChart('MetricsServer', {
chart: 'metrics-server',
release: 'metrics-server-rt',
repository: 'https://kubernetes-charts.storage.googleapis.com',
version: '2.9.0',
namespace: 'kube-system'
});
metricsServerChart.node.addDependency(fargateProfile);
// This "new class extends cdk.Construct {" convention wraps the resources created within and allows
// us make all of them dependent on the EKS Cluster's Fargate Profile resource in one fell swoop. This
// will prevent pods from being stuck in a "Pending" state forever after initial creation if Kubernetes
// attempts to schedule them before the Fargate Profile is ready.
new class extends cdk.Construct {
constructor(parent: cdk.Construct, name: string) {
super(parent, name)
// This block creates the ALB Ingress Controller resources, but requires an OIDC provider in order
// to function, which will not exist until the cluster creation is completed. After the initial
// `cdk deploy` is complete, follow the README instructions on how to associate the OIDC provider
// and complete the initial setup.
if (props.oidcProvider) {
const OIDC_PROVIDER = props.oidcProvider;
const albIngressControllerRole = new Role(this, 'AlbIngressControllerRole', {
assumedBy: new FederatedPrincipal(
'arn:aws:iam::' + cdk.Stack.of(this).account + ':oidc-provider/' + props.oidcProvider, {
'StringEquals': {
[`${OIDC_PROVIDER + ':sub'}`]: 'system:serviceaccount:kube-system:aws-alb-ingress-controller'
}
},
'sts:AssumeRoleWithWebIdentity'
),
roleName: 'ReinventTriviaAlbIngressControllerRole',
managedPolicies: [
new AlbIngressControllerPolicy(this, 'AlbIngressControllerPolicy')
]
});
const albIngressChart = cluster.addHelmChart('AlbIngress', {
chart: 'aws-alb-ingress-controller',
release: 'alb-ingress-controller-rt',
repository: 'https://kubernetes-charts-incubator.storage.googleapis.com',
version: '0.1.13',
namespace: 'kube-system',
values: {
awsRegion: cdk.Stack.of(cluster).region,
awsVpcID: cluster.vpc.vpcId,
clusterName: cluster.clusterName,
fullnameOverride: 'aws-alb-ingress-controller',
rbac: {
serviceAccountAnnotations: {
'eks.amazonaws.com/role-arn': albIngressControllerRole.roleArn
}
},
scope: {
singleNamespace: true,
watchNamespace: 'reinvent-trivia',
},
},
});
albIngressChart.node.addDependency(metricsServerChart);
new KubernetesManifest(this, 'HorizontalPodAutoscaler', {
cluster,
manifest: [{
apiVersion: 'autoscaling/v1',
kind: 'HorizontalPodAutoscaler',
metadata: {
name: 'api',
namespace: 'reinvent-trivia',
},
spec: {
scaleTargetRef: {
apiVersion: 'apps/v1',
kind: 'Deployment',
name: 'api',
},
minReplicas: 2,
maxReplicas: 32,
targetCPUUtilizationPercentage: 50,
}
}]
});
if (props.domainZone) {
const hostedZoneId = HostedZone.fromLookup(this, 'ApiDomainHostedZone', {domainName: props.domainZone}).hostedZoneId;
const externalDnsRole = new Role(this, 'ExternalDnsRole', {
assumedBy: new FederatedPrincipal(
'arn:aws:iam::' + cdk.Stack.of(this).account + ':oidc-provider/' + props.oidcProvider, {
'StringEquals': {
[`${OIDC_PROVIDER + ':sub'}`]: 'system:serviceaccount:kube-system:external-dns-rt'
}
},
'sts:AssumeRoleWithWebIdentity'
),
roleName: 'ReinventTriviaExternalDnsRole',
managedPolicies: [
new ManagedPolicy(this, 'ExternalDnsPolicy', {
managedPolicyName: 'ExternalDnsPolicy',
description: 'Used by the ExternalDNS pod to make AWS API calls for updating DNS',
statements: [
new PolicyStatement({
resources: ['arn:aws:route53:::hostedzone/' + hostedZoneId],
effect: Effect.ALLOW,
actions: [
"route53:ChangeResourceRecordSets"
]
}),
new PolicyStatement({
resources: ['*'],
effect: Effect.ALLOW,
actions: [
'route53:ListHostedZones',
'route53:ListResourceRecordSets',
]
})
]
})
]
});
const externalDnsChart = cluster.addHelmChart('ExternalDns', {
chart: 'external-dns',
release: 'external-dns-rt',
repository: 'https://kubernetes-charts.storage.googleapis.com',
version: '2.16.2',
namespace: 'kube-system',
values: {
domainFilters: [props.domainZone],
namespace: 'reinvent-trivia',
provider: 'aws',
rbac: {
serviceAccountAnnotations: {
'eks.amazonaws.com/role-arn': externalDnsRole.roleArn,
}
}
}
});
externalDnsChart.node.addDependency(metricsServerChart);
}
}
}
}(this, 'KubernetesResources').node.addDependency(reinventTrivia);
}
}
const app = new cdk.App();
new TriviaBackendStack(app, 'TriviaBackendProd', {
domainName: 'api.reinvent-trivia.com',
// NOTE: `domainZone` must already exist in Route 53.
domainZone: 'reinvent-trivia.com',
env: {account: process.env['CDK_DEFAULT_ACCOUNT'], region: 'us-east-1'},
tags: {
project: "reinvent-trivia"
},
/*
* NOTE: `oidcProvider` will not be available until after the cluster is deployed for the first
* time. Leave the line below commented out for the initial `cdk deploy`. See README for details.
*/
//oidcProvider: 'oidc.eks.<region>.amazonaws.com/id/<hexadecimal string>',
});
app.synth();