This repository has been archived by the owner on Dec 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 84
/
create_secrets.py
174 lines (138 loc) · 5.5 KB
/
create_secrets.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
#!/usr/bin/python
"""A script to create the required secrets in one namespace by copying them
from another namespace
"""
import base64
import fire
from google.cloud import storage
from kubernetes import client as k8s_client
from kubernetes import config as k8s_config
from kubernetes.client import rest
import logging
import yaml
import os
import re
import subprocess
DEV_ENVIRONMENT = "dev"
PROD_ENVIRONMENT = "prod"
# The namespace for the dev environment.
DEV_NAMESPACE = "label-bot-dev"
PROD_NAMESPACE = "label-bot-prod"
GCS_REGEX = re.compile("gs://([^/]*)(/.*)?")
def split_gcs_uri(gcs_uri):
"""Split a GCS URI into bucket and path."""
m = GCS_REGEX.match(gcs_uri)
bucket = m.group(1)
path = ""
if m.group(2):
path = m.group(2).lstrip("/")
return bucket, path
def secret_exists(namespace, name, client):
api = k8s_client.CoreV1Api(client)
try:
api.read_namespaced_secret(name, namespace)
return True
except rest.ApiException as e:
if e.status != 404:
raise
return False
def _read_gcs_path(gcs_path):
bucket_name, blob_name = split_gcs_uri(gcs_path)
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
contents = blob.download_as_string().decode()
return contents
class SecretCreator:
@staticmethod
def _secret_from_gcs(secret_name, gcs_path):
bucket_name, blob_name = split_gcs_uri(gcs_path)
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
contents = blob.download_as_string().decode()
file_name = os.path.basename(blob_name)
namespace, name = secret_name.split("/", 1)
subprocess.check_call(["kubectl", "-n", namespace, "create",
"secret", "generic",
name,
f"--from-literal=f{file_name}={contents}"])
@staticmethod
def copy_secret(source, dest):
"""Create the dev version of the secrets.
Args:
source: {namespace}/{secret name}
dest: {namespace}/{secret name}
"""
src_namespace, src_name = source.split("/", 1)
dest_namespace, dest_name = dest.split("/", 1)
data = subprocess.check_output(["kubectl", "-n", src_namespace, "get",
"secrets", src_name, "-o",
"yaml"])
encoded = yaml.load(data)
decoded = {}
for k, v in encoded["data"].items():
decoded[k] = base64.b64decode(v).decode()
command = ["kubectl", "create", "-n", dest_namespace, "secret",
"generic", dest_name]
for k, v in decoded.items():
command.append(f"--from-literal={k}={v}")
subprocess.check_call(command)
@staticmethod
def create(env):
"""Create the secrets for the dev environment.
Args:
env: The environment to create the secrets in.
"""
if env == DEV_ENVIRONMENT:
namespace = DEV_NAMESPACE
github_app_pem_key = ("gs://issue-label-bot-dev_secrets/"
"kf-label-bot-dev.2019-12-30.private-key.pem")
webhook_gcs = ("gs://issue-label-bot-dev_secrets/"
"kf-label-bot-dev.webhook.secret")
elif env == PROD_ENVIRONMENT:
namespace = PROD_NAMESPACE
github_app_pem_key = ("gs://github-probots_secrets/"
"issue-label-bot-github-app.private-key.pem")
webhook_gcs = ("gs://github-probots_secrets/"
"issue-label-bot-prod.webhook.secret")
else:
raise ValueError(f"env={env} is not an allowed value; must be "
f"{DEV_ENVIRONMENT} or {PROD_ENVIRONMENT}")
k8s_config.load_kube_config(persist_config=False)
client = k8s_client.ApiClient()
if secret_exists(namespace, "user-gcp-sa", client):
logging.warning(f"Secret {namespace}/user-gcp-sa already exists; "
f"Not recreating it.")
else:
# We get a GCP secret by copying it from the kubeflow namespace.
SecretCreator.copy_secret("kubeflow/user-gcp-sa",
f"{namespace}/user-gcp-sa")
if secret_exists(namespace, "github-app", client):
logging.warning(f"Secret {namespace}/github-app already exists; "
f"Not recreating it.")
else:
# Create the secret containing the PEM key for the github app
SecretCreator._secret_from_gcs(f"{namespace}/github-app", github_app_pem_key)
# Create the inference secret containing the postgres database with
# postgres secret and the webhook secret
inference_secret = "ml-app-inference-secret"
if secret_exists(namespace, inference_secret, client):
logging.warning(f"Secret {namespace}/{inference_secret} already exists; "
f"Not recreating it.")
else:
postgres = _read_gcs_path("gs://issue-label-bot-dev_secrets/"
"issue-label-bot.postgres")
webhook = _read_gcs_path(webhook_gcs)
subprocess.check_call(["kubectl", "-n", namespace, "create",
"secret", "generic",
inference_secret,
f"--from-literal=DATABASE_URL={postgres}",
f"--from-literal=WEBHOOK_SECRET={webhook}"])
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO,
format=('%(levelname)s|%(asctime)s'
'|%(message)s|%(pathname)s|%(lineno)d|'),
datefmt='%Y-%m-%dT%H:%M:%S',
)
fire.Fire(SecretCreator)