Call the jinja2 template of / templates as shown below, and after rendering, place it under playbooks with the same configuration.
/User/taka
|--main.py
|--templates
| |--inf
| | |--group_vars
| | | |--test001.yml.j2
| | | |--test002.yml.j2
| | |--inventory
| | | |--inv_test001.yml.j2
| | | |--inv_test002.yml.j2
|--playbooks
| |--inf
| | |--group_vars
| | | |--test001.yml.j2
| | | |--test002.yml.j2
| | |--inventory
| | | |--inv_test001.yml.j2
| | | |--inv_test002.yml.j2
I tried to turn the for statement with a list type dictionary as shown below, but of course it is in key-value format, so the next value overwrites the previous value, and test002.yml.j2, inv_test002 is in the playbook directory. Only .yml.j2 was made
self.j2_files = defaultdict(list)
self.j2_files['group_vars'].append("test001.yml.j2")
self.j2_files['group_vars'].append("test002.yml.j2")
self.j2_files['inventory'].append("invt_est001.yml.j2")
self.j2_files['inventory'].append("inv_test002.yml.j2")
env = Environment(trim_blocks = True, loader =
FileSystemLoader(os.path.join("User", "taka", "templates", "inf"))
Even if I googled [multiple values for one key in Python dictionary] in English, I couldn't come up with a plan that I thought, so I got a little stuck.
The result was solved as follows
1 for k in self.j2_files.keys():
2 for v in self.j2_files[k]:
3 tmpl = env.get_template(k + "/" + v)
4 with open(os.path.join(User,taka,inf, k, v), "wb") as f:
5 f.write(tmpl.render(self.test_conf).encode("utf-8"))
1: Store the key of j2_files, that is, group_vars and inventory in k 2: Store the value corresponding to the key of j2_files in v 3: Specify that the location of the template is fetched from the k + "/" + v directory under templates / inf 4: Specify the output destination 5: Generate a jinja file from the specified dictionary
Recommended Posts