Skip to content

Instantly share code, notes, and snippets.

@megalucio
Created November 24, 2022 11:27
Show Gist options
  • Save megalucio/51d7b280ebd52bceb82246eadb86d02a to your computer and use it in GitHub Desktop.
Save megalucio/51d7b280ebd52bceb82246eadb86d02a to your computer and use it in GitHub Desktop.
Python script to read Kubernetes Secrets and export them into Hashicorp Vault.
#!/usr/bin/env python3
"""
Python script to read Kubernetes Secrets and export them into
Hashicorp Vault. The following environment variables need to be defined:
VAULT_ADDR: Address of the vault
VAULT_SECRETS_PATH: Root path where secrets will be stored
SECRET_NAMES: Names of the secrets that will be exported. This filed is OPTIONAL, if not provided, all secrets will be exported.
"""
import yaml
import os
import sys
import hvac
from subprocess import check_output
def readFromK18s():
filterByName = ""
if os.getenv("SECRET_NAMES") is not None:
for name in os.environ['SECRET_NAMES'].split(','):
filterByName += '"%s",' % (name)
filterByName=filterByName[:-1]
shell_command = "kubectl get secret --all-namespaces -o json | jq '[.items[] | select( .metadata.name as $i | [%s] | index($i) ) |{(.metadata.name): (.data)}]' | yq eval - -P | cut -c2-" %(filterByName)
output = check_output(shell_command, shell=True)
return yaml.safe_load(output)
def writeInVault(data):
try:
client = hvac.Client(url=os.environ['VAULT_ADDR'], verify='true')
except Exception as e:
print('Error connecting to vault: %s' % e)
sys.exit(1)
for path, kv in data.items():
try:
client.secrets.kv.v2.create_or_update_secret(
path=os.environ['VAULT_SECRETS_PATH'] + path,
secret=kv)
except Exception as e:
print('Error writing to vault: %s' % e)
sys.exit(1)
if __name__ == '__main__':
data = readFromK18s()
writeInVault(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment