Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/env python3
- #
- # this is NOT a human-facing tool
- #
- # This is to replace the legacy data files being used to populate
- # variables in a shell script and instead get them from the vars
- # files even though that still feels weird.
- #
- # Example:
- # azs=$(yamlpath.py roles/cassandra/vars/clusters.yml clusters/multitenant-us-east-1/availability_zones)
- # echo $azs
- # us-east-1b us-east-1c us-east-1a
- import yaml
- import sys
- import os.path
- # no fancy arg parsing, only simple checking because
- # I expect the caller (my script) to get things right
- yamlfile=sys.argv[1]
- yamlpath=sys.argv[2]
- if not os.path.isfile(yamlfile):
- sys.exit("the first arg must be a filename, got: '{}'".format(yamlfile))
- if len(yamlpath) < 1:
- sys.exit("you must provide a yaml path to emit, got: '{}'".format(yamlpath))
- def extract_path(yamlpath, data):
- parts = yamlpath.split("/")
- cursor = data
- for part in parts:
- if type(cursor) is list and part.isdigit():
- cursor = cursor[int(part)]
- elif type(cursor) is dict:
- cursor = cursor[part]
- if type(cursor) in (str,int,float):
- print(cursor)
- elif type(cursor) is list:
- print(" ".join(cursor))
- elif type(cursor) is dict:
- print(" ".join(cursor.keys()))
- else:
- sys.exit("cannot print node type '{}'".format(type(cursor)))
- with open(yamlfile, 'r') as stream:
- try:
- data = yaml.load(stream)
- extract_path(yamlpath, data)
- except yaml.YAMLError as e:
- sys.exit("YAML parsing failed: {}".format(e))
Add Comment
Please, Sign In to add comment