From 54f452616079824e804885c43f97d63fe06a1aba Mon Sep 17 00:00:00 2001 From: Jeroen Hoekx Date: Sat, 14 Apr 2012 13:12:32 +0200 Subject: [PATCH] Export SSH port number as host variable. --- lib/ansible/inventory.py | 14 ++++++++++++++ test/TestInventory.py | 6 ++++++ 2 files changed, 20 insertions(+) diff --git a/lib/ansible/inventory.py b/lib/ansible/inventory.py index 429b4c95d9..3f97460e51 100644 --- a/lib/ansible/inventory.py +++ b/lib/ansible/inventory.py @@ -35,6 +35,7 @@ class Inventory(object): def __init__(self, host_list=C.DEFAULT_HOST_LIST, extra_vars=None): self._restriction = None + self._variables = {} if type(host_list) == list: self.host_list = host_list @@ -80,6 +81,9 @@ class Inventory(object): def get_variables(self, host, extra_vars=None): """ Return the variables associated with this host. """ + if host in self._variables: + return self._variables[host] + if not self._is_script: return {} @@ -108,6 +112,11 @@ class Inventory(object): if ":" in item: # a port was specified item, port = item.split(":") + try: + port = int(port) + except ValueError: + raise errors.AnsibleError("SSH port for %s in inventory (%s) should be numerical."%(item, port)) + self._set_variable(item, "ansible_ssh_port", port) groups[group_name].append(item) if not item in results: results.append(item) @@ -170,6 +179,11 @@ class Inventory(object): )) return variables + def _set_variable(self, host, key, value): + if not host in self._variables: + self._variables[host] = {} + self._variables[host][key] = value + def _matches(self, host_name, pattern): ''' returns if a hostname is matched by the pattern ''' diff --git a/test/TestInventory.py b/test/TestInventory.py index ba89bdc3a9..2f86f50728 100644 --- a/test/TestInventory.py +++ b/test/TestInventory.py @@ -82,6 +82,12 @@ class TestInventory(unittest.TestCase): assert vars == {} + def test_simple_port(self): + inventory = self.simple_inventory() + vars = inventory.get_variables('hera') + + assert vars == {'ansible_ssh_port': 3000} + ### Inventory API tests def test_script(self):