-
Notifications
You must be signed in to change notification settings - Fork 100
/
__main__.py
551 lines (489 loc) · 25.1 KB
/
__main__.py
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import base64
import os
from typing import Mapping
import pulumi
import pulumi_kubernetes as k8s
from pulumi_kubernetes.helm.v3 import Release, ReleaseArgs, RepositoryOptsArgs
from pulumi_kubernetes.core.v1 import Secret
from Crypto.PublicKey import RSA
from pulumi_kubernetes.yaml import ConfigFile
from pulumi_kubernetes.yaml import ConfigGroup
from kic_util import pulumi_config
# Removes the status field from the Nginx Ingress Helm Chart, so that i#t is
# compatible with the Pulumi Chart implementation.
def remove_status_field(obj):
if obj['kind'] == 'CustomResourceDefinition' and 'status' in obj:
del obj['status']
def project_name_from_infrastructure_dir():
script_dir = os.path.dirname(os.path.abspath(__file__))
eks_project_path = os.path.join(
script_dir, '..', '..', '..', 'infrastructure', 'kubeconfig')
return pulumi_config.get_pulumi_project_name(eks_project_path)
def project_name_from_kubernetes_dir(dirname: str):
script_dir = os.path.dirname(os.path.abspath(__file__))
project_path = os.path.join(script_dir, '..', '..', dirname)
return pulumi_config.get_pulumi_project_name(project_path)
#
# This is just used for the kubernetes config deploy....
#
def pulumi_repo_ingress_project_name():
script_dir = os.path.dirname(os.path.abspath(__file__))
ingress_project_path = os.path.join(
script_dir, '..', '..', 'nginx', 'ingress-controller-repo-only')
return pulumi_config.get_pulumi_project_name(ingress_project_path)
def pulumi_ingress_project_name():
script_dir = os.path.dirname(os.path.abspath(__file__))
ingress_project_path = os.path.join(
script_dir, '..', '..', 'nginx', 'ingress-controller')
return pulumi_config.get_pulumi_project_name(ingress_project_path)
def sirius_manifests_location():
script_dir = os.path.dirname(os.path.abspath(__file__))
sirius_manifests_path = os.path.join(
script_dir, 'src', 'kubernetes-manifests', '*.yaml')
return sirius_manifests_path
def extract_password_from_k8s_secrets(secrets: Mapping[str, str], secret_name: str) -> str:
if secret_name not in secrets:
raise f'Secret [{secret_name}] not found in Kubernetes secret store'
base64_string = secrets[secret_name]
byte_data = base64.b64decode(base64_string)
password = str(byte_data, 'utf-8')
return password
#
# We will only want to be deploying one type of certificate issuer
# as part of this application; this can (and should) be changed as
# needed. For example, if the user is taking advantage of ACME let's encrypt
# in order to generate certs.
#
def k8_manifest_location():
script_dir = os.path.dirname(os.path.abspath(__file__))
k8_manifest_path = os.path.join(script_dir, 'cert', 'self-sign.yaml')
return k8_manifest_path
#
# The database password is a secret, and in order to use it in a string concat
# we need to decrypt the password with Output.unsecret() before we use it.
# This function provides the logic to accomplish this, while still using the
# pulumi secrets for the resulting string:
#
def create_pg_uri(password_object):
user = str(accounts_admin)
password = str(password_object)
database = str(accounts_db)
uri = f'postgresql://{user}:{password}@accounts-db:5432/{database}'
return pulumi.Output.secret(uri)
def add_namespace(obj):
obj['metadata']['namespace'] = 'bos'
stack_name = pulumi.get_stack()
project_name = pulumi.get_project()
k8_project_name = project_name_from_infrastructure_dir()
pulumi_user = pulumi_config.get_pulumi_user()
k8_stack_ref_id = f"{pulumi_user}/{k8_project_name}/{stack_name}"
k8_stack_ref = pulumi.StackReference(k8_stack_ref_id)
kubeconfig = k8_stack_ref.get_output('kubeconfig').apply(lambda c: str(c))
k8_stack_ref.get_output('cluster_name').apply(
lambda s: pulumi.log.info(f'Cluster name: {s}'))
secrets_project_name = project_name_from_kubernetes_dir('secrets')
secrets_stack_ref_id = f"{pulumi_user}/{secrets_project_name}/{stack_name}"
secrets_stack_ref = pulumi.StackReference(secrets_stack_ref_id)
pulumi_secrets = secrets_stack_ref.require_output('pulumi_secrets')
k8s_provider = k8s.Provider(resource_name='ingress-controller')
#
# This logic is used to manage the kubeconfig deployments, since that uses a
# slightly # different logic path than the mainline. This will be removed once
# the kubeconfig deploys are moved to the Pulumi Automation API.
#
config = pulumi.Config('kubernetes')
infra_type = config.require('infra_type')
if infra_type == 'kubeconfig':
#
# Logic to extract the FQDN of the load balancer for Ingress
#
ingress_project_name = pulumi_repo_ingress_project_name()
ingress_stack_ref_id = f"{pulumi_user}/{ingress_project_name}/{stack_name}"
ingress_stack_ref = pulumi.StackReference(ingress_stack_ref_id)
lb_ingress_hostname = ingress_stack_ref.get_output('lb_ingress_hostname')
#
# Set back to kubernetes
#
config = pulumi.Config('kubernetes')
lb_ingress_ip = ingress_stack_ref.get_output('lb_ingress_ip')
sirius_host = lb_ingress_hostname
else:
#
# We use the hostname to set the value for our FQDN, which drives the cert
# process as well.
#
ingress_project_name = pulumi_ingress_project_name()
ingress_stack_ref_id = f"{pulumi_user}/{ingress_project_name}/{stack_name}"
ingress_stack_ref = pulumi.StackReference(ingress_stack_ref_id)
lb_ingress_hostname = ingress_stack_ref.get_output('lb_ingress_hostname')
sirius_host = lb_ingress_hostname
#
# Create the namespace for Bank of Sirius
#
ns = k8s.core.v1.Namespace(resource_name='bos',
metadata={'name': 'bos'},
opts=pulumi.ResourceOptions(provider=k8s_provider))
#
# Add Config Maps for Bank of Sirius; these are built in Pulumi in order to
# manage secrets and provide the option for users to override defaults in the
# configuration file. Configuration values that are required use the `require`
# method. Those that are optional use the `get` method, and have additional
# logic to set defaults if no value is set by the user.
#
# Note that the Pulumi code will exit with an error message if a required
# variable is not defined in the configuration file.
#
# Configuration Values are stored in the "secrets" project
#
config = pulumi.Config('sirius')
sirius_secrets = Secret.get(resource_name='pulumi-secret-sirius',
id=pulumi_secrets['sirius'],
opts=pulumi.ResourceOptions(provider=k8s_provider)).data
accounts_pwd = pulumi.Output.unsecret(sirius_secrets).apply(
lambda secrets: extract_password_from_k8s_secrets(secrets, 'accounts_pwd'))
ledger_pwd = pulumi.Output.unsecret(sirius_secrets).apply(
lambda secrets: extract_password_from_k8s_secrets(secrets, 'ledger_pwd'))
demo_login_user = pulumi.Output.unsecret(sirius_secrets).apply(
lambda secrets: extract_password_from_k8s_secrets(secrets, 'demo_login_user'))
demo_login_pwd = pulumi.Output.unsecret(sirius_secrets).apply(
lambda secrets: extract_password_from_k8s_secrets(secrets, 'demo_login_pwd'))
accounts_admin = config.get('accounts_admin')
if not accounts_admin:
accounts_admin = 'admin'
accounts_db = config.get('accounts_db')
if not accounts_db:
accounts_db = 'postgresdb'
accounts_db_uri = pulumi.Output.unsecret(accounts_pwd).apply(create_pg_uri)
accounts_db_config_config_map = k8s.core.v1.ConfigMap("accounts_db_configConfigMap",
opts=pulumi.ResourceOptions(
depends_on=[ns]),
api_version="v1",
kind="ConfigMap",
metadata=k8s.meta.v1.ObjectMetaArgs(
name="accounts-db-config",
namespace=ns,
labels={
"app": "accounts_db",
},
),
data={
"POSTGRES_DB": accounts_db,
"POSTGRES_USER": accounts_admin,
"POSTGRES_PASSWORD": accounts_pwd,
"ACCOUNTS_DB_URI": accounts_db_uri
})
environment_config_config_map = k8s.core.v1.ConfigMap("environment_configConfigMap",
opts=pulumi.ResourceOptions(
depends_on=[ns]),
api_version="v1",
kind="ConfigMap",
metadata=k8s.meta.v1.ObjectMetaArgs(
name="environment-config",
namespace=ns
),
data={
"LOCAL_ROUTING_NUM": "883745000",
"PUB_KEY_PATH": "/root/.ssh/publickey"
})
tracing_config_config_map = k8s.core.v1.ConfigMap("tracing_configConfigMap",
opts=pulumi.ResourceOptions(
depends_on=[ns]),
api_version="v1",
kind="ConfigMap",
metadata=k8s.meta.v1.ObjectMetaArgs(
name="tracing-config",
namespace=ns
),
data={
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://simplest-collector.observability.svc.cluster.local:9978",
"ENABLE_TRACING": "true",
"ENABLE_METRICS": "true"
})
service_api_config_config_map = k8s.core.v1.ConfigMap("service_api_configConfigMap",
opts=pulumi.ResourceOptions(
depends_on=[ns]),
api_version="v1",
kind="ConfigMap",
metadata=k8s.meta.v1.ObjectMetaArgs(
name="service-api-config",
namespace=ns
),
data={
"TRANSACTIONS_API_ADDR": "ledgerwriter:8080",
"BALANCES_API_ADDR": "balancereader:8080",
"HISTORY_API_ADDR": "transactionhistory:8080",
"CONTACTS_API_ADDR": "contacts:8080",
"USERSERVICE_API_ADDR": "userservice:8080",
})
#
# Demo data is hardcoded in the current incarnation of the bank of
# sirius project, so we go along with that for now.
#
demo_data_config_config_map = k8s.core.v1.ConfigMap("demo_data_configConfigMap",
opts=pulumi.ResourceOptions(
depends_on=[ns]),
api_version="v1",
kind="ConfigMap",
metadata=k8s.meta.v1.ObjectMetaArgs(
name="demo-data-config",
namespace=ns
),
data={
"USE_DEMO_DATA": "True",
"DEMO_LOGIN_USERNAME": demo_login_user,
"DEMO_LOGIN_PASSWORD": demo_login_pwd
})
ledger_admin = config.get('ledger_admin')
if not ledger_admin:
ledger_admin = 'admin'
ledger_db = config.get('ledger_db')
if not ledger_db:
ledger_db = 'postgresdb'
spring_url = 'jdbc:postgresql://ledger-db:5432/' + str(ledger_db)
ledger_db_config_config_map = k8s.core.v1.ConfigMap("ledger_db_configConfigMap",
opts=pulumi.ResourceOptions(
depends_on=[ns]),
api_version="v1",
kind="ConfigMap",
metadata=k8s.meta.v1.ObjectMetaArgs(
name="ledger-db-config",
namespace=ns,
labels={
"app": "postgres",
},
),
data={
"POSTGRES_DB": ledger_db,
"POSTGRES_USER": ledger_admin,
"POSTGRES_PASSWORD": ledger_pwd,
"SPRING_DATASOURCE_URL": spring_url,
"SPRING_DATASOURCE_USERNAME": ledger_admin,
"SPRING_DATASOURCE_PASSWORD": ledger_pwd
})
key = RSA.generate(2048)
private_key = key.export_key()
private_key.decode()
encode_private = base64.b64encode(private_key)
public_key = key.publickey().export_key()
public_key.decode()
encode_public = base64.b64encode(public_key)
jwt_key_secret = k8s.core.v1.Secret("jwt_keySecret",
api_version="v1",
opts=pulumi.ResourceOptions(
depends_on=[ns]),
kind="Secret",
metadata=k8s.meta.v1.ObjectMetaArgs(
name="jwt-key",
namespace=ns
),
type="Opaque",
data={
"jwtRS256.key": str(encode_private, "utf-8"),
"jwtRS256.key.pub": str(encode_public, "utf-8")
})
#
# Create resources for the Bank of Sirius using the Kubernetes YAML manifests
# which have been pulled from the google repository.
#
# Note that these have been lightly edited to remove dependencies on GCP where
# necessary. Additionally, the `frontend` service has been updated to use a
# ClusterIP rather than the external load balancer, as that interaction
# is now handled by the NGNIX Ingress Controller
#
sirius_manifests = sirius_manifests_location()
bos = ConfigGroup(
'bos',
files=[sirius_manifests],
transformations=[add_namespace],
opts=pulumi.ResourceOptions(depends_on=[tracing_config_config_map])
)
#
# We need to create an issuer for the cert-manager (which is installed in a
# separate project directory). This can (and should) be adjusted as required,
# as the default issuer is self-signed.
#
k8_manifest = k8_manifest_location()
selfissuer = ConfigFile(
"selfissuer",
transformations=[add_namespace],
file=k8_manifest)
#
# Add the Ingress controller for the Bank of Sirius application. This uses the
# NGINX IC that is installed as part of this Pulumi stack.
#
#
# This block is responsible for creating the Ingress object for the
# application. This object is deployed into the same namespace as the
# application and requires that an IngressClass # and Ingress controller be
# installed (which is done in an earlier step, deploying the KIC).
#
bosingress = k8s.networking.v1.Ingress("bosingress",
api_version="networking.k8s.io/v1",
kind="Ingress",
metadata=k8s.meta.v1.ObjectMetaArgs(
name="bosingress",
namespace=ns,
# This annotation is used to request a certificate from the cert
# manager. The manager watches for ingress objects with this
# annotation and handles certificate generation.
#
# It is possible to use different cert issuers with cert-manager,
# but in the current deployment we only have a self-signed issuer
# configured.
annotations={
"cert-manager.io/cluster-issuer": "selfsigned-issuer",
},
),
spec=k8s.networking.v1.IngressSpecArgs(
ingress_class_name="nginx",
# The block below sets up the TLS configuration for the Ingress
# controller. The secret defined here will be used by the issuer
# to store the generated certificate.
tls=[k8s.networking.v1.IngressTLSArgs(
hosts=[sirius_host],
secret_name="sirius-secret", # pragma: allowlist secret
)],
# The block below defines the rules for traffic coming into the KIC.
# In the example below, we take any traffic on the host for path /
# and direct it to the frontend server on port 80. Additional routes
# could be added if desired. Also, different hostnames could be defined
# if desired. For example, an additional CNAME could be added to point
# to this same KIC along with a separate tls and host rule to direct
# traffic to a different backend.
rules=[k8s.networking.v1.IngressRuleArgs(
host=sirius_host,
http=k8s.networking.v1.HTTPIngressRuleValueArgs(
paths=[k8s.networking.v1.HTTPIngressPathArgs(
path="/",
path_type="Prefix",
backend=k8s.networking.v1.IngressBackendArgs(
service=k8s.networking.v1.IngressServiceBackendArgs(
name="frontend",
port=k8s.networking.v1.ServiceBackendPortArgs(
number=80,
),
),
),
)],
),
)],
))
#
# Get the hostname for our connect URL; this logic will be collapsed once the
# kubeconfig # deployments are moved over to the automation api. Until then,
# we have to use a different process.
#
config = pulumi.Config('kubernetes')
infra_type = config.require('infra_type')
if infra_type == 'kubeconfig':
pulumi.export('hostname', lb_ingress_hostname)
pulumi.export('ipaddress', lb_ingress_ip)
application_url = sirius_host.apply(lambda host: f'https://{host}')
else:
application_url = sirius_host.apply(lambda host: f'https://{host}')
pulumi.export('application_url', application_url)
#
# Get the chart values for both monitoring charts, switch back to the Sirius
# namespace.
#
config = pulumi.Config('sirius')
chart = config.get('chart')
if not chart:
chart = 'prometheus-postgres-exporter'
chart_version = config.get('chart_version')
if not chart_version:
chart_version = '2.3.5'
helm_repo_name = config.get('helm_repo_name')
if not helm_repo_name:
helm_repo_name = 'prometheus-community'
helm_repo_url = config.get('helm_repo_url')
if not helm_repo_url:
helm_repo_url = 'https://prometheus-community.github.io/helm-charts'
# Monitoring for Databases: Accounts DB
accountsdb_release_args = ReleaseArgs(
chart=chart,
repository_opts=RepositoryOptsArgs(
repo=helm_repo_url
),
version=chart_version,
namespace=ns,
# Values from Chart's parameters specified hierarchically,
values={
"serviceMonitor": {
"enabled": True,
"namespace": "prometheus"
},
"config": {
"datasource": {
"host": "accounts-db",
"user": accounts_admin,
"password": accounts_pwd,
"passwordSecret": {},
"port": "5432",
"database": accounts_db,
"sslmode": "disable"
}
},
"annotations": {
"prometheus.io/scrape": "true",
"prometheus.io/port": "9187"}
},
# By default Release resource will wait till all created resources
# are available. Set this to true to skip waiting on resources being
# available.
skip_await=False,
# If we fail, clean up
cleanup_on_fail=True,
# Provide a name for our release
name="accountsdbmon",
# Lint the chart before installing
# lint=True,
# Force update if required
force_update=True)
accountsdb_release = Release("accountsdbmon", args=accountsdb_release_args)
accountsdb_status = accountsdb_release.status
# Monitoring for Databases: Ledger DB
ledgerdb_release_args = ReleaseArgs(
chart=chart,
repository_opts=RepositoryOptsArgs(
repo=helm_repo_url
),
version=chart_version,
namespace=ns,
# Values from Chart's parameters specified hierarchically,
values={
"serviceMonitor": {
"enabled": True,
"namespace": "prometheus"
},
"config": {
"datasource": {
"host": "ledger-db",
"user": ledger_admin,
"password": ledger_pwd,
"passwordSecret": {},
"port": "5432",
"database": ledger_db,
"sslmode": "disable"
}
},
"annotations": {
"prometheus.io/scrape": "true",
"prometheus.io/port": "9187"}
},
# By default Release resource will wait till all created resources
# are available. Set this to true to skip waiting on resources being
# available.
skip_await=False,
# If we fail, clean up
cleanup_on_fail=True,
# Provide a name for our release
name="ledgerdbmon",
# Lint the chart before installing
lint=True,
# Force update if required
force_update=True)
ledgerdb_release = Release("ledgerdb", args=ledgerdb_release_args)
ledgerdb_status = ledgerdb_release.status
pulumi.export("ledgerdbmon_status", accountsdb_status)
pulumi.export("accountsdbmon_status", ledgerdb_status)