-
Notifications
You must be signed in to change notification settings - Fork 8
/
ca_key.py
90 lines (74 loc) · 2.63 KB
/
ca_key.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
import json
import boto3
from botocore.exceptions import ClientError
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.exceptions import UnsupportedAlgorithm
SECRETS_CLIENT = boto3.client('secretsmanager')
def add_ca_key(event, context):
"""Add and associate a K8s cluster's CA key, except key in pem format"""
"""
"body":
{
"cluster_name": "cloud-infra.cloud",
"ca_key": "'-----BEGIN RSA PRIVATE KEY-----\n
PUT REAL KEY HERE
\n-----END RSA PRIVATE KEY-----\n'"
}
"""
cluster_name = event['body']['cluster_name']
# Load CA key from event body
try:
ca_key = str.encode(event['body']['ca_key'])
except AttributeError:
print(
f'Error encoding {event["body"]["ca_key"]} must be string format')
# Validate key by loading it in cryptography lib
try:
validate_key = load_pem_private_key(ca_key,
password=None,
backend=default_backend())
print(f'Key validated with size: {validate_key.key_size}')
except ValueError as err:
print(f'ValueError: {err}')
except TypeError as err:
print(f'TypeError: {err}')
except UnsupportedAlgorithm as err:
print(f'UnsupportedAlgorithm: {err}')
print(f'Saving hyper-kube-config-{cluster_name}-ca-key...')
try:
SECRETS_CLIENT.create_secret(
Name=f'hyper-kube-config-{cluster_name}-ca-key',
SecretString=ca_key,
Tags=[
{
'Key': 'cluster_name',
'Value': cluster_name
}
]
)
except ClientError as err:
if err.response['Error']['Code'] == 'EntityAlreadyExists':
print(f'CA key already exists in AWS Secrets Manager: {err}')
def remove_ca_key(event, context):
"""Remove specified CA key"""
cluster_name = event['body']['cluster_name']
try:
msg = f'Deleted hyper-kube-config-{cluster_name}-ca-key'
print(msg)
SECRETS_CLIENT.delete_secret(
SecretId=f'hyper-kube-config-{cluster_name}-ca-key',
ForceDeleteWithoutRecovery=True
)
return {
"statusCode": 200,
"body": {"message": msg}
}
except ClientError as e:
err_msg = f'Failed to get ca key associated to {cluster_name}: {e}'
return {
"statusCode": 503,
"body": json.dumps(
{"message": err_msg}
)
}