Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Created March 30, 2025 16:45
Show Gist options
  • Save bbengfort/8e0c6f7402e1588a6b2e5bcd9443c3ca to your computer and use it in GitHub Desktop.
Save bbengfort/8e0c6f7402e1588a6b2e5bcd9443c3ca to your computer and use it in GitHub Desktop.
Helper functions to manage k8s secrets more easily
#!/usr/bin/env python3
# Helper functions to manage k8s secrets more easily
import os
import yaml
import base64
import argparse
template = """apiVersion: v1
kind: Secret
metadata:
name: {name}
namespace: {namespace}
type: Opaque
data:
{secrets}
"""
def encode(args):
config = {
"name": args.name,
"namespace": args.namespace,
}
secrets = {}
for path in args.files:
key = os.path.basename(path)
with open(path, "rb") as f:
secrets[key] = base64.b64encode(f.read()).decode("ascii")
config["secrets"] = "\n ".join([f"{key}: {val}" for key, val in secrets.items()]) # noqa
with open(args.out, "w") as f:
f.write(template.format(**config))
def decode(args):
for path in args.secrets:
with open(path, 'r') as f:
data = yaml.safe_load(f)['data']
if args.key:
if args.key in data:
if args.print:
val = base64.b64decode(data[args.key]).decode("utf-8")
print(f"{args.key}: {val}")
else:
with open(os.path.join(args.out, "wb")) as f:
f.write(base64.b64decode(data[args.key]))
else:
# Handle data
for key in data:
if args.print:
val = base64.b64decode(data[key]).decode("utf-8")
print(f"{key}: {val}")
else:
with open(os.path.join(args.out, key), "wb") as f:
f.write(base64.b64decode(data[key]))
if __name__ == "__main__":
cmds = {
"encode": {
"help": "encode specified files as k8s secrets object in yaml format", # noqa
"func": encode,
"args": {
"files": {
"nargs": "+",
"help": "file(s) to encode into secret objects (keys will be basename)" # noqa
},
("-o", "--out"): {
"type": str, "default": "secret.yaml",
"help": "path to write the secret YAML to",
},
("-n", "--name"): {
"type": str, "default": "my-secret",
"help": "the name of the k8s secret to add to the metadata", # noqa
},
("-N", "--namespace"): {
"type": str, "default": "default",
"help": "the namespace of the k8s secret to add to the metadata", # noqa
},
}
},
"decode": {
"help": "decode secrets from a k8s secrets object in yaml format",
"func": decode,
"args": {
"secrets": {
"nargs": "+",
"help": "path to the secrets file(s) to decode",
},
("-o", "--out"): {
"type": str, "default": ".",
"help": "directory to write the secret files out to"
},
("-k", "--key"): {
"type": str, "default": None,
"help": "specify the key of the secret to extract",
},
("-p", "--print"): {
"action": "store_true", "default": False,
"help": "instead of writing secret files, just print key/value pairs (useful for username/passwords)" # noqa
},
}
},
}
# Create the CLI parser
parser = argparse.ArgumentParser(
description="Helper functions to manage k8s secrets more easily"
)
subparsers = parser.add_subparsers(title="actions", description="secrets commands") # noqa
for cmd, cargs in cmds.items():
cmdparser = subparsers.add_parser(cmd, help=cargs.get('help'))
cmdparser.set_defaults(func=cargs.get('func'))
for pargs, kwargs in cargs.get("args", {}).items():
if isinstance(pargs, str):
pargs = (pargs,)
cmdparser.add_argument(*pargs, **kwargs)
# Execute the command
args = parser.parse_args()
if hasattr(args, "func"):
try:
args.func(args)
except Exception as e:
parser.error(e)
else:
parser.print_help()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment