Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kubernetes secrets generator from env vars (secrets.yml content and env vars for deployment.yml). Original code here: https://github.com/TelluIoT/kubernetes-env-to-secrets/blob/master/README.md
# required python 3
# command: python <location_of_the_file>/secrets_generator.py --env <path_to_env_var_file> --name <secrets_name>
#sample: python ./secrets_generator.py --env .env --name my_secrets
import copy
import argparse
import sys
import configparser
import itertools
import base64
from string import Template
parser = argparse.ArgumentParser(description='Convert environment files to kubernetes secrets')
parser.add_argument('--name', metavar='name', nargs='?', type=str, default='my-secrets', help='Name of the secret store')
parser.add_argument('--env', metavar='.env', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help='Environment input file, stdin by default')
parser.add_argument('--secrets', metavar='.yaml', nargs='?', type=argparse.FileType('w'), default=sys.stdout, help='Secrets output file, stdout by default')
args = parser.parse_args()
config = configparser.ConfigParser()
config.read_file(itertools.chain(['[global]'], args.env), source="env")
secrets = config.items('global')
args.env.close()
def loadFiles(secret):
if (secret[1].startswith('filecontent=')):
with open(secret[1][12:], 'r') as secretfile:
data = secretfile.read()
return [secret[0], data]
return secret
secrets = map(loadFiles, secrets)
secrets2 = copy.deepcopy(secrets)
encodedSecrets = [' {0}: {1}'.format(
secret[0],
base64.b64encode(secret[1].encode('utf-8')).decode('utf-8')
) for secret in secrets]
importSecrets = [' - name: {0}\n\t valueFrom:\n\t\t secretKeyRef:\n\t\t\t name: {1}\n\t\t\t key: {2}'.format(
secret[0].upper(),
args.name,
secret[0]
) for secret in secrets2]
yamlTemplate = Template("""apiVersion: v1
kind: Secret
metadata:
name: $name
type: Opaque
data:
$encodedSecrets
--------------------import secrets------------------------------
$importSecrets
""")
yamlOutput = yamlTemplate.substitute(name=args.name, encodedSecrets='\n'.join(encodedSecrets), importSecrets='\n'.join(importSecrets))
args.secrets.write(yamlOutput)
args.secrets.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment