python通过jinja2模板生成openstack heat模板

由于openstack heat模板并没有for循环的方法,因此想通过heat批量创建资源,如创建N多路由器,则需要先通过python将jinja2的模板,生成一个heat模板,shaker中采用的就是这个方法:

用于生成heat模板的jinja2模板如下:

heat_template_version: 2013-05-23

description:
  create some net and router

parameters:

resources:
{% for x in xlist %}
  {{ x }}_private_net:
    type: OS::Neutron::Net
    properties:
      name: heat1_net

  {{ x }}_private_subnet:
    type: OS::Neutron::Subnet
    properties:
      network_id: { get_resource: {{ x }}_private_net }
      cidr: 11.0.0.0/8

  {{ x }}_router:
    type: OS::Neutron::Router
    properties:
      external_gateway_info:
        network: 5048-ext-net 

  {{ x }}_router_interface:
    type: OS::Neutron::RouterInterface
    properties:
      router_id: { get_resource: {{ x }}_router }
      subnet_id: { get_resource: {{ x }}_private_subnet }
{% endfor %}

转换的python代码:

import jinja2
import sys
f = open(sys.argv[1])
heat_template = f.read()
xlist = [x for x in range(250)]
print heat_template
print "============================="
compiled_template = jinja2.Template(heat_template)
print compiled_template
rendered_template = compiled_template.render({"xlist": xlist})
tmp_file = file("tmp.hot", mode="w")
tmp_file.write(rendered_template)
tmp_file.close

 

posted @ 2017-09-19 11:08  sunln  阅读(246)  评论(0编辑  收藏  举报