I have some simple Python, the goal of which is to deploy a hosts file. The hosts file is intended to look like this:
[master1]
*hostname*
[master2]
*hostname
I'm using Python to try and achieve this, first I retrieve the hostnames from my VMware build and put them into a file called tfhosts, it follows the format of /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
The Python code looks like this:
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()
When I run my Python against tfhosts, it simply produces either the whole set of hosts as one array slice or if I attempt to limit the scope by using [0:]
Or if I use servers[0] | servers[1] in the code:
[master1]
d
[master2]
c
I get the first letter d (of the hostname) only and for master 2 c.
Can anyone spot the issue and offer some guidance?
Thanks in advance.