使用带有Jinja模板的Python循环

时间:2015-10-04 17:28:01

标签: python loops jinja2

我有一些简单的Python,其目标是部署主机文件。 hosts文件看起来像这样:

[master1]
*hostname*

[master2]
*hostname

我使用Python尝试实现这一点,首先我从VMware构建中检索主机名并将其放入名为 tfhosts 的文件中,它遵循/ etc / hosts的格式:

tfhosts

192.168.100.21 dc01-control-01
192.168.100.22 dc01-control-02
192.168.100.23 dc01-control-03
192.168.100.31 dc01-worker-01
192.168.100.32 dc01-worker-02

Python代码如下所示:

hostname.py

import jinja2
from tempfile import NamedTemporaryFile

def return_hosts():
        hosts = open('./tfhosts','r')
        x = ""
        for line in hosts:
                x = x + str(line.split()[1:]).strip('[]').strip("''") + '\n'
        return [x][0:]

inventory = """
[master1]
{{ host_master01 }}
[master2]
{{ host_master02 }}
"""

gethosts = return_hosts()

inventory_template = jinja2.Template(inventory)

for servers in (gethosts):
        rendered_inventory = inventory_template.render({
                'host_master01': servers[0],
                'host_master02': servers[1],
        })

hosts = NamedTemporaryFile(delete=False)
hosts.write(rendered_inventory)
hosts.close()

当我针对tfhosts运行我的Python时,它只是将整个主机集生成为一个数组切片,或者如果我尝试使用[0:]

来限制范围

或者如果我使用 servers [0] |代码中的服务器[1]

[master1]
d
[master2]
c

我只获得第一个字母 d (主机名),而主人2 c

有人能发现问题并提供一些指导吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我修改了它,你可以进一步修改它。如果它不起作用,请告诉我。

import jinja2
from tempfile import NamedTemporaryFile

def return_hosts():
    'return a list of host names'
    with open('./tfhosts') as hosts:
        return [host.split()[1].strip() for host in hosts]

inventory = """
[master1]
{{ host_master01 }}
[master2]
{{ host_master02 }}
"""

gethosts = return_hosts()

inventory_template = jinja2.Template(inventory)

rendered_inventory = inventory_template.render({ 
    'host_master01': gethosts[0], 
    'host_master02': gethosts[1], 
  })

hosts = NamedTemporaryFile(delete=False)
hosts.write(rendered_inventory)
hosts.close()