2 ##############################################################################
3 # Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may #
6 # not use this file except in compliance with the License. #
8 # You may obtain a copy of the License at #
9 # http://www.apache.org/licenses/LICENSE-2.0 #
11 # Unless required by applicable law or agreed to in writing, software #
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT #
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
14 # See the License for the specific language governing permissions and #
15 # limitations under the License. #
16 ##############################################################################
18 # jcopy.py - Copy a file or files to a target directory, making
19 # substitutions as needed from the values contained in a YAML file.
20 # compatibile with python and python3
22 # usage: jcopy.py <yaml_input> <template_dir_or_file> <out_dir>
30 def cidr_netmask(value):
32 v = netaddr.IPNetwork(value)
38 def cidr_subnet(value):
40 v = netaddr.IPNetwork(value)
49 print( 'usage: jcopy.py <yaml> <template_dir_or_file> <out_dir>' )
52 def expand_template( t, output_fname, fill=60 ):
53 print( '### {0: <{fill}} ==> {1}'.format(t.filename, output_fname, fill=fill) )
54 if not os.path.exists(os.path.dirname(output_fname)):
55 os.makedirs(os.path.dirname(output_fname))
56 t.stream(yaml=siteyaml).dump(output_fname)
58 if len(sys.argv) != 4:
59 usage('incorrect number of arguments')
61 yaml_input=sys.argv[1]
65 if not os.path.isfile(yaml_input):
66 usage('input yaml file {} does not exist'.format(yaml_input))
68 with open(yaml_input) as f:
69 siteyaml = yaml.safe_load(f)
71 if os.path.isfile(j2in_name):
72 j2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(j2in_name)), trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True, undefined=jinja2.make_logging_undefined())
73 j2_env.filters['cidr_netmask'] = cidr_netmask
74 j2_env.filters['cidr_subnet'] = cidr_subnet
75 expand_template(j2_env.get_template(name=os.path.basename(j2in_name)),yaml_out,len(j2in_name))
77 j2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(j2in_name), trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True, undefined=jinja2.make_logging_undefined())
78 j2_env.filters['cidr_netmask'] = cidr_netmask
79 j2_env.filters['cidr_subnet'] = cidr_subnet
80 templates=j2_env.list_templates(extensions=('j2'))
81 fill=len(max(templates,key=len))+len(j2in_name)
83 expand_template(j2_env.get_template(name=f), yaml_out+'/'+f.replace('.j2','.yaml'), fill)
84 print('%d files processed.' % len(templates))
88 # sudo apt-get install python-jinja2 python-yaml
89 # sudo apt-get install python3-jinja2 python3-yaml