-
Notifications
You must be signed in to change notification settings - Fork 1
/
rds_encrypt.py
executable file
·207 lines (162 loc) · 6.17 KB
/
rds_encrypt.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
#!/usr/bin/env python3
""" A tool used for encrypting RDS instances that were previously created in an unencrypted state"""
import time
import random
import sys
import boto3
import argparse
def check_kms(key: str) -> str:
"""Check for the existence of a KMS key."""
check_key = KMS.describe_key(
KeyId=key,
)
return check_key["KeyMetadata"]["KeyId"]
def check_database(database: str) -> str:
"""Check for the existence of the RDS instance."""
check_instance = RDS.describe_db_instances(
DBInstanceIdentifier=database,
)
return check_instance["DBInstances"][0]["DBInstanceIdentifier"]
def remove_db(instance: str) -> None:
"""Removes a DB instance based on identifier"""
RDS.delete_db_instance(
DBInstanceIdentifier=instance,
SkipFinalSnapshot=True,
DeleteAutomatedBackups=False,
)
def check_database_encryption(database: str) -> str:
"""Checks if an RDS instance has encrypted storage."""
check_instance = RDS.describe_db_instances(
DBInstanceIdentifier=database,
)
return check_instance["DBInstances"][0]["StorageEncrypted"]
def check_snapshot(instance: str) -> str:
"""Check for the existence of a database snapshot."""
check_rds = RDS.describe_db_snapshots(
DBInstanceIdentifier=f"{instance}",
DBSnapshotIdentifier=f"snapshot-{instance}",
)
return check_rds
def produce_snapshot(instance: str) -> str:
"""Create a snapshot of a desired RDS instance, name that snapshot."""
check = check_snapshot(instance)
if check["DBSnapshots"] == []:
snapshot = RDS.create_db_snapshot(
DBSnapshotIdentifier=f"snapshot-{instance}",
DBInstanceIdentifier=instance,
)
else:
print(f"Snapshot already exists at 'snapshot-{instance}'")
sys.exit(1)
return snapshot["DBSnapshot"]["DBSnapshotIdentifier"]
def encrypt_snapshot(source_snapshot: str, key: str) -> str:
"""Encrypt an existing RDS snapshot."""
encrypt = RDS.copy_db_snapshot(
SourceDBSnapshotIdentifier=f"{source_snapshot}",
TargetDBSnapshotIdentifier=f"encrypted-{source_snapshot}",
KmsKeyId=key,
)
print(f"Creating encrypted snapshot - encrypted-{source_snapshot}")
return encrypt["DBSnapshot"]["DBSnapshotIdentifier"]
def rename_instance(instance: str) -> str:
"""Will rename your RDS instance to have a prefix of rds-old-xxxx"""
random_prefix_int = random.randint(1000, 9999)
instance_new = f"rds-old-{random_prefix_int}-instance"
print(f"Renaming instance - {instance_new}")
rename = RDS.modify_db_instance(
DBInstanceIdentifier=instance,
NewDBInstanceIdentifier=instance_new,
ApplyImmediately=True,
)
if (
rename["DBInstance"]["PendingModifiedValues"]["DBInstanceIdentifier"]
!= instance_new
):
sys.stderr.write(f"Could not rename RDS instance {instance} to {instance_new}")
update_check = None
while update_check != instance_new:
try:
update_check = check_database(instance_new)
except:
print("\t - Rename not complete")
time.sleep(10)
print("Rename complete")
return instance_new
def restore_from_encrypted_snapshot(snapshot: str, instance_name: str) -> None:
"""Restores an RDS instance from a given snapshot"""
RDS.restore_db_instance_from_db_snapshot(
DBInstanceIdentifier=instance_name,
DBSnapshotIdentifier=snapshot,
)
if __name__ == "__main__":
# Initialize our boto3 endpoints
RDS = boto3.client("rds")
KMS = boto3.client("kms")
# Initialize argparser and arguments
PARSER = argparse.ArgumentParser(description="Encrypt an RDS instance")
PARSER.add_argument(
"--instance",
"-i",
metavar="instance-1",
action="store",
dest="instance",
type=str,
help="Your desired RDS instance",
required=True,
)
PARSER.add_argument(
"--keyid",
"-k",
metavar="key-1",
action="store",
dest="keyid",
type=str,
help="Your desired KMS key",
required=True,
)
ARGS = PARSER.parse_args()
# Check the RDS instance exists
RDS_INSTANCE = ARGS.instance
if RDS_INSTANCE:
RDS_EXISTENCE = check_database(RDS_INSTANCE)
if RDS_EXISTENCE is None:
sys.stderr.write(
"Could not find your selected RDS instance please ensure it exists"
)
sys.exit(1)
# Check the KMS key exists
KMS_KEY = ARGS.keyid
if KMS_KEY:
KEY_EXISTENCE = check_kms(KMS_KEY)
if KEY_EXISTENCE is None:
sys.stderr.write("Could not find your KMS key please ensure it exists")
sys.exit(1)
# Create our initial snapshot
BASE_SNAPSHOT_IDENTIFIER = produce_snapshot(RDS_INSTANCE)
print(f"Creating snapshot - {BASE_SNAPSHOT_IDENTIFIER}")
# Wait for our snapshot to come available
BASE_SNAPSHOT_WAITER = RDS.get_waiter("db_snapshot_available")
BASE_SNAPSHOT_WAITER.wait(
DBInstanceIdentifier=f"{RDS_INSTANCE}",
DBSnapshotIdentifier=f"{BASE_SNAPSHOT_IDENTIFIER}",
WaiterConfig={"Delay": 30, "MaxAttempts": 120},
)
# Encrypt our snapshot by passing in our base snapshot and encryption key
ENCRYPTED_SNAPSHOT_IDENTIFIER = encrypt_snapshot(BASE_SNAPSHOT_IDENTIFIER, KMS_KEY)
# Wait for our encrypted snapshot to be created.
ENCRYPTED_SNAPSHOT_WAITER = RDS.get_waiter("db_snapshot_available")
ENCRYPTED_SNAPSHOT_WAITER.wait(
DBInstanceIdentifier=f"{RDS_INSTANCE}",
DBSnapshotIdentifier=f"{ENCRYPTED_SNAPSHOT_IDENTIFIER}",
WaiterConfig={"Delay": 30, "MaxAttempts": 120},
)
# Renames the original instance RDS-OLD
OLD_INSTANCE = rename_instance(RDS_INSTANCE)
# Create a new DB instance from our snapshot
restore_from_encrypted_snapshot(ENCRYPTED_SNAPSHOT_IDENTIFIER, RDS_INSTANCE)
# Check we now have a new encrypted instance running under the original identifier
if check_database_encryption(RDS_INSTANCE):
print(f"Instance {RDS_INSTANCE} is now encrypted")
# Remove the old database instance
remove_db(OLD_INSTANCE)
sys.exit(0)