Created
June 1, 2017 20:59
-
-
Save sivel/ae23b4cdd93b6b766a40d77bb9f9657d to your computer and use it in GitHub Desktop.
Ansible constants to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
import json | |
import os | |
import sys | |
import ansible.constants as C | |
things = {} | |
op_map = { | |
ast.Add: '+', | |
ast.Sub: '-', | |
ast.Mult: '*', | |
ast.Div: '/', | |
} | |
def get_values(values): | |
if not isinstance(values, list): | |
return get_value(values) | |
ret = [] | |
for value in values: | |
ret.append(get_value(value)) | |
return ret | |
def get_value(value): | |
if hasattr(value, 'id'): | |
ret = value.id | |
elif hasattr(value, 's'): | |
ret = value.s | |
elif hasattr(value, 'n'): | |
ret = value.n | |
elif hasattr(value, 'left'): | |
operator = op_map[type(value.op)] | |
left = get_values(value.left) | |
right = get_values(value.right) | |
return '%s %s %s' % (left, operator, right) | |
elif hasattr(value, 'value'): | |
ret = value.value | |
elif hasattr(value, 'elts'): | |
ret = get_values(value.elts) | |
elif isinstance(value, ast.Call): | |
func, args, kwargs = get_call(value) | |
args[:] = [repr(arg) for arg in args] | |
for k, v in kwargs.items(): | |
args.append('%s=%s' % (k, repr(v))) | |
return '%s(%s)' % (func, ', '.join(args)) | |
else: | |
return value | |
return get_value(ret) | |
def get_call(value): | |
args = [] | |
for arg in value.args: | |
v = get_value(arg) | |
try: | |
v = getattr(C, v, v) | |
except: | |
pass | |
args.append(v) | |
kwargs = {} | |
for keyword in value.keywords: | |
v = get_value(keyword.value) | |
try: | |
v = getattr(C, v, v) | |
except: | |
pass | |
kwargs[keyword.arg] = v | |
func = get_value(value.func) | |
try: | |
attr = '.%s' % value.func.attr | |
except: | |
attr = '' | |
return '%s%s' % (func, attr), args, kwargs | |
with open(C.__file__.rstrip('co')) as f: | |
tree = ast.parse(f.read()) | |
for item in tree.body: | |
if hasattr(item, 'value') and isinstance(item.value, ast.Call): | |
try: | |
if item.value.func.id != 'get_config': | |
continue | |
except AttributeError: | |
continue | |
_, args, kwargs = get_call(item.value) | |
section = args[1].lower() | |
config = args[2] | |
if section not in things: | |
things[section] = {} | |
things[section][config] = { | |
'env_var': args[3], | |
'default': args[4] if len(args) == 5 else 'UNKNOWN' | |
} | |
things[section][config].update(kwargs) | |
print(json.dumps(things, indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment