Skip to content

Instantly share code, notes, and snippets.

@tobert
Created February 6, 2018 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobert/63b4c7f1cbed29dbe716182ada48b9a6 to your computer and use it in GitHub Desktop.
Save tobert/63b4c7f1cbed29dbe716182ada48b9a6 to your computer and use it in GitHub Desktop.
a quick & dirty yaml path printer for embedding in shell scripts
#!/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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment