sonic-buildimage/src/sonic-config-engine/sonic-cfggen

89 lines
2.5 KiB
Plaintext
Raw Normal View History

#!/usr/bin/env python
import sys
import os.path
import argparse
import yaml
import jinja2
import netaddr
import json
from minigraph import parse_xml
def is_ipv4(value):
if not value:
return False
if isinstance(value, netaddr.IPAddress):
addr = value
else:
try:
addr = netaddr.IPAddress(str(value))
except:
return False
return addr.version == 4
def is_ipv6(value):
if not value:
return False
if isinstance(value, netaddr.IPAddress):
addr = value
else:
try:
addr = netaddr.IPAddress(str(value))
except:
return False
return addr.version == 6
def main():
parser=argparse.ArgumentParser(description="Render configuration file from minigraph data and jinja2 template.")
parser.add_argument("-m", "--minigraph", help="minigraph xml file")
parser.add_argument("-y", "--yaml", help="yaml file that contains addtional variables")
parser.add_argument("-a", "--additional-data", help="addition data, in json string")
group = parser.add_mutually_exclusive_group()
group.add_argument("-t", "--template", help="render the data with the template file")
group.add_argument("-v", "--var", help="print the value of a variable")
group.add_argument("--var-json", help="print the value of a variable, in json format")
group.add_argument("--var-keys", help="print all keys of a map variable")
group.add_argument("--print-data", help="print all data", action='store_true')
args = parser.parse_args()
data = {}
if args.minigraph != None:
minigraph = args.minigraph
data.update(parse_xml(minigraph))
if args.yaml != None:
with open(args.yaml, 'r') as stream:
additional_data = yaml.load(stream)
data.update(additional_data)
if args.additional_data != None:
data.update(json.loads(args.additional_data))
if args.template != None:
template_file = os.path.abspath(args.template)
env = jinja2.Environment(loader=jinja2.FileSystemLoader('/'), trim_blocks=True)
env.filters['ipv4'] = is_ipv4
env.filters['ipv6'] = is_ipv6
template = env.get_template(template_file)
print template.render(data)
if args.var != None:
print data[args.var]
if args.var_json != None:
print json.dumps(data[args.var_json])
if args.var_keys != None:
for key in data[args.var_keys].keys():
print key
if args.print_data:
print data
if __name__ == "__main__":
main()