iof-tools / gen-ssh-config.py @ 8581329c
History | View | Annotate | Download (1.54 KB)
1 |
#!/usr/bin/env python
|
---|---|
2 |
import xml.etree.ElementTree as ET |
3 |
from argparse import ArgumentParser |
4 |
import sys |
5 |
from ssh_config_template import SSHConfig |
6 |
|
7 |
from const import COMPONENT_ID, NODE, SSH_CONFIG_TEMPLATE, \ |
8 |
HOST_CONFIG_TEMPLATE, IDENTITY_FILE, NODE_NAME |
9 |
|
10 |
parser = ArgumentParser() |
11 |
parser.add_argument("-r", "--rspec", dest="rspec", |
12 |
default="", action="store", metavar="FILENAME", |
13 |
help="Rspec file to be parsed")
|
14 |
parser.add_argument("-s", "--ssh-config", dest="ssh_config", |
15 |
default="ssh-config", action="store", metavar="FILENAME", |
16 |
help="Output file onto which the SSH configuration is "
|
17 |
"written")
|
18 |
args = parser.parse_args() |
19 |
|
20 |
if not args.rspec: |
21 |
print("You must specify an Rspec input file")
|
22 |
sys.exit(1)
|
23 |
|
24 |
rspec_file = args.rspec |
25 |
ssh_config_file = args.ssh_config |
26 |
|
27 |
config_file = open(ssh_config_file, "w") |
28 |
|
29 |
ssh_config = SSHConfig(SSH_CONFIG_TEMPLATE, HOST_CONFIG_TEMPLATE, IDENTITY_FILE) |
30 |
|
31 |
xml_file = ET.iterparse(rspec_file) |
32 |
for _, el in xml_file: |
33 |
el.tag = el.tag.split('}', 1)[1] # strip all namespaces |
34 |
|
35 |
n = 0
|
36 |
root = xml_file.root |
37 |
nodes = root.findall(NODE) |
38 |
n_nodes = len(nodes)
|
39 |
name_template = NODE_NAME.format(len(str(n_nodes))) |
40 |
for node in nodes: |
41 |
component_id = node.get(COMPONENT_ID) |
42 |
components = component_id.split("+")
|
43 |
domain = components[1]
|
44 |
name = components[3]
|
45 |
hostname = "{}.{}".format(name, domain)
|
46 |
ssh_config.add_host(name_template.format(n), hostname) |
47 |
n += 1
|
48 |
|
49 |
config_file.write(str(ssh_config))
|
50 |
config_file.close() |