Skip to content

Instantly share code, notes, and snippets.

@rvelseg
Forked from tdickman/README.md
Last active March 31, 2020 23: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 rvelseg/78b9da3e367637b5f8c3f8c9bbfe9eca to your computer and use it in GitHub Desktop.
Save rvelseg/78b9da3e367637b5f8c3f8c9bbfe9eca to your computer and use it in GitHub Desktop.
Parse YAML file to bash variables

Usage

eval $(python parse_yaml.py example_file.yaml)

In this example the following variables are accessible:

$key1
$key2_nested
key1: 'test'
key2:
nested: 1
#!/usr/bin/python
import sys
import yaml
def parse(obj, base_prefix=None):
for key in obj:
value = obj[key]
prefix = '{}_{}'.format(base_prefix, key) if base_prefix else key
if str(key).find("_") != -1 :
print(
"WARNING: Underscores are used in variable names, and possibly to indicate hierarchy",
file=sys.stderr)
if type(value) == dict:
parse(value, prefix)
elif type(value) == list:
parse(
dict(enumerate(value)),
prefix)
else:
print('export {}="{}"'.format(prefix, value))
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
parse(yaml.load(f))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment