Guest User

Untitled

a guest
Feb 19th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. #!/bin/env python3
  2. #
  3. # this is NOT a human-facing tool
  4. #
  5. # This is to replace the legacy data files being used to populate
  6. # variables in a shell script and instead get them from the vars
  7. # files even though that still feels weird.
  8. #
  9. # Example:
  10. # azs=$(yamlpath.py roles/cassandra/vars/clusters.yml clusters/multitenant-us-east-1/availability_zones)
  11. # echo $azs
  12. # us-east-1b us-east-1c us-east-1a
  13.  
  14. import yaml
  15. import sys
  16. import os.path
  17.  
  18. # no fancy arg parsing, only simple checking because
  19. # I expect the caller (my script) to get things right
  20. yamlfile=sys.argv[1]
  21. yamlpath=sys.argv[2]
  22.  
  23. if not os.path.isfile(yamlfile):
  24. sys.exit("the first arg must be a filename, got: '{}'".format(yamlfile))
  25. if len(yamlpath) < 1:
  26. sys.exit("you must provide a yaml path to emit, got: '{}'".format(yamlpath))
  27.  
  28. def extract_path(yamlpath, data):
  29. parts = yamlpath.split("/")
  30.  
  31. cursor = data
  32. for part in parts:
  33. if type(cursor) is list and part.isdigit():
  34. cursor = cursor[int(part)]
  35. elif type(cursor) is dict:
  36. cursor = cursor[part]
  37.  
  38. if type(cursor) in (str,int,float):
  39. print(cursor)
  40. elif type(cursor) is list:
  41. print(" ".join(cursor))
  42. elif type(cursor) is dict:
  43. print(" ".join(cursor.keys()))
  44. else:
  45. sys.exit("cannot print node type '{}'".format(type(cursor)))
  46.  
  47. with open(yamlfile, 'r') as stream:
  48. try:
  49. data = yaml.load(stream)
  50. extract_path(yamlpath, data)
  51. except yaml.YAMLError as e:
  52. sys.exit("YAML parsing failed: {}".format(e))
Add Comment
Please, Sign In to add comment