Skip to content

Instantly share code, notes, and snippets.

@cpaulbond
Created May 7, 2016 16:47
Show Gist options
  • Save cpaulbond/a13c86af258fdd6c2f13b8be0eb630b8 to your computer and use it in GitHub Desktop.
Save cpaulbond/a13c86af258fdd6c2f13b8be0eb630b8 to your computer and use it in GitHub Desktop.
Dump all etcd key/values under <path> as json. All values are converted to json if possible.
#!/usr/bin/env python3
#>> Dump all etcd key/values under <path> as json. All values are converted to json if possible.
# Example:
# $ etcdctl set /config/a 'String for a'
# String for a
# $ etcdctl set /config/b true
# true
# $ etcdctl set /config/c 100
# 100
# $ etcdctl set /config/d '{"d1":1,"d2":2}'
# {"d1":1,"d2":2}
# $ etcdctl set /config/e/f '{"f1":"one","d2":false}'
# {"f1":"one","d2":false}
# $ etcd-dump /config
# {
# "a": "String for a",
# "b": true,
# "c": 100,
# "d": {
# "d1": 1,
# "d2": 2
# },
# "e": {
# "f": {
# "d2": false,
# "f1": "one"
# }
# }
# }
import etcd # https://github.com/coreos/etcd
import json
import os
import sys
import argparse
def get_etcd(c, base):
rtn = {}
for i in c.read(base, recursive=True, sorted=True).children:
path = i.key[len(base):].split('/')
rec, key = get_branch(rtn, path[1:])
if i.value == None:
sys.stderr.write("ERROR: key '%s' missing value\n" % i.key)
rec[key] = cvt(i.value)
return rtn
def get_branch(data, path):
for i in path[:-1]:
if i not in data:
data[i] = {}
data = data[i]
return data, path[-1]
def cvt(s):
if s == None:
return None
try:
return json.loads(s)
except ValueError:
return s
def connect(peers):
peer = peers.split(',')[0].split(':')
if len(peer) == 1:
h, p = peer[0], 2379
else:
h, p = peer[0], int(peer[1])
return etcd.Client(host=h, port=p)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--peers', '-C', default='localhost:2379')
parser.add_argument('path')
args = parser.parse_args()
c = connect(args.peers)
data = get_etcd(c, args.path)
json.dump(data, sys.stdout, sort_keys=True, indent=4, separators=(',', ': '))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment