2 # Licensed under the Apache License, Version 2.0 (the "License"); you may
3 # not use this file except in compliance with the License. You may obtain
4 # a copy of the License at
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 # License for the specific language governing permissions and limitations
22 __tht_root_dir = os.path.dirname(os.path.dirname(__file__))
26 parser = argparse.ArgumentParser(
27 description='Configure host network interfaces using a JSON'
28 ' config file format.')
29 parser.add_argument('-p', '--base_path', metavar='BASE_PATH',
30 help="""base path of templates to process.""",
32 parser.add_argument('-r', '--roles-data', metavar='ROLES_DATA',
33 help="""relative path to the roles_data.yaml file.""",
34 default='roles_data.yaml')
35 parser.add_argument('--safe',
37 help="""Enable safe mode (do not overwrite files).""",
39 parser.add_argument('-o', '--output-dir', metavar='OUTPUT_DIR',
40 help="""Output dir for all the templates""",
42 opts = parser.parse_args(argv[1:])
47 def _j2_render_to_file(j2_template, j2_data, outfile_name=None,
49 yaml_f = outfile_name or j2_template.replace('.j2.yaml', '.yaml')
50 print('rendering j2 template to file: %s' % outfile_name)
52 if not overwrite and os.path.exists(outfile_name):
53 print('ERROR: path already exists for file: %s' % outfile_name)
56 # Search for templates relative to the current template path first
57 template_base = os.path.dirname(yaml_f)
58 j2_loader = jinja2.loaders.FileSystemLoader([template_base, __tht_root_dir])
61 # Render the j2 template
62 template = jinja2.Environment(loader=j2_loader).from_string(
64 r_template = template.render(**j2_data)
65 except jinja2.exceptions.TemplateError as ex:
66 error_msg = ("Error rendering template %s : %s"
67 % (yaml_f, six.text_type(ex)))
69 raise Exception(error_msg)
70 with open(outfile_name, 'w') as out_f:
71 out_f.write(r_template)
74 def process_templates(template_path, role_data_path, output_dir, overwrite):
76 with open(role_data_path) as role_data_file:
77 role_data = yaml.safe_load(role_data_file)
79 j2_excludes_path = os.path.join(template_path, 'j2_excludes.yaml')
80 with open(j2_excludes_path) as role_data_file:
81 j2_excludes = yaml.safe_load(role_data_file)
83 if output_dir and not os.path.isdir(output_dir):
84 if os.path.exists(output_dir):
85 raise RuntimeError('Output dir %s is not a directory' % output_dir)
88 role_names = [r.get('name') for r in role_data]
91 r_map[r.get('name')] = r
92 excl_templates = ['%s/%s' % (template_path, e)
93 for e in j2_excludes.get('name')]
95 if os.path.isdir(template_path):
96 for subdir, dirs, files in os.walk(template_path):
98 # NOTE(flaper87): Ignore hidden dirs as we don't
99 # generate templates for those.
100 # Note the slice assigment for `dirs` is necessary
101 # because we need to modify the *elements* in the
102 # dirs list rather than the reference to the list.
103 # This way we'll make sure os.walk will iterate over
104 # the shrunk list. os.walk doesn't have an API for
105 # filtering dirs at this point.
106 dirs[:] = [d for d in dirs if not d[0] == '.']
107 files = [f for f in files if not f[0] == '.']
109 # NOTE(flaper87): We could have used shutil.copytree
110 # but it requires the dst dir to not be present. This
111 # approach is safer as it doesn't require us to delete
112 # the output_dir in advance and it allows for running
113 # the command multiple times with the same output_dir.
116 out_dir = os.path.join(output_dir, subdir)
117 if not os.path.exists(out_dir):
121 file_path = os.path.join(subdir, f)
122 # We do two templating passes here:
123 # 1. *.role.j2.yaml - we template just the role name
124 # and create multiple files (one per role)
125 # 2. *.j2.yaml - we template with all roles_data,
126 # and create one file common to all roles
127 if f.endswith('.role.j2.yaml'):
128 print("jinja2 rendering role template %s" % f)
129 with open(file_path) as j2_template:
130 template_data = j2_template.read()
131 print("jinja2 rendering roles %s" % ","
133 for role in role_names:
134 j2_data = {'role': role}
135 # (dprince) For the undercloud installer we don't
136 # want to have heat check nova/glance API's
137 if r_map[role].get('disable_constraints', False):
138 j2_data['disable_constraints'] = True
141 os.path.basename(f).replace('.role.j2.yaml',
143 out_f_path = os.path.join(out_dir, out_f)
144 if not (out_f_path in excl_templates):
145 _j2_render_to_file(template_data, j2_data,
146 out_f_path, overwrite)
148 print('skipping rendering of %s' % out_f_path)
149 elif f.endswith('.j2.yaml'):
150 print("jinja2 rendering normal template %s" % f)
151 with open(file_path) as j2_template:
152 template_data = j2_template.read()
153 j2_data = {'roles': role_data}
154 out_f = os.path.basename(f).replace('.j2.yaml', '.yaml')
155 out_f_path = os.path.join(out_dir, out_f)
156 _j2_render_to_file(template_data, j2_data, out_f_path,
159 shutil.copy(os.path.join(subdir, f), out_dir)
162 print('Unexpected argument %s' % template_path)
164 opts = parse_opts(sys.argv)
166 role_data_path = os.path.join(opts.base_path, opts.roles_data)
168 process_templates(opts.base_path, role_data_path, opts.output_dir, (not opts.safe))