Last active
November 18, 2020 12:33
-
-
Save abhishekjiitr/88a57661609996755c19a9e3dc931022 to your computer and use it in GitHub Desktop.
Python script to read a given Kubernetes Secret and export all the keys present in it into separate files, base64 decoding values appropriately
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Python script to read a given Kubernetes Secret and export all the keys present | |
in it into separate files, base64 decoding if necessary | |
Needs one command line argument, the secret name to read | |
""" | |
import base64 | |
import pathlib | |
import os | |
import subprocess | |
import sys | |
import yaml | |
ROOT_DIR = 'decoded_secrets' | |
def write_secret(name, key, val): | |
curr_secret_dir = os.path.join(ROOT_DIR, name) | |
pathlib.Path(curr_secret_dir).mkdir(parents=True, exist_ok=True) | |
filepath = os.path.join(curr_secret_dir, key) | |
with open(filepath, 'w+b') as f: | |
print(f'Writing Secret Key "{key}" To File: {filepath}') | |
f.write(val) | |
def process_secret(name): | |
print(f'Processing Secret named {name}') | |
command = ['kubectl', 'get', 'secret', name, '-oyaml'] | |
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
stdout, stderr = process.communicate() | |
stdout, stderr = stdout.decode(), stderr.decode() | |
if process.poll() != 0: | |
raise RuntimeError(stderr) | |
secret = yaml.safe_load(stdout) | |
if 'data' not in secret: | |
raise KeyError('data') | |
data = secret['data'] | |
for key, val in data.items(): | |
decoded_value = base64.b64decode(val) | |
write_secret(name, key, decoded_value) | |
if __name__ == '__main__': | |
if len(sys.argv) <= 1: | |
raise RuntimeError('Need to pass the secret name to process!') | |
secret_name = sys.argv[1] | |
process_secret(secret_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment