diff --git a/lib/ansible/inventory/ini.py b/lib/ansible/inventory/ini.py index c50fae61164..024eb9a9a0e 100644 --- a/lib/ansible/inventory/ini.py +++ b/lib/ansible/inventory/ini.py @@ -23,6 +23,7 @@ from ansible.inventory.group import Group from ansible.inventory.expand_hosts import detect_range from ansible.inventory.expand_hosts import expand_hostname_range from ansible import errors +from ansible import utils import shlex import re import ast @@ -65,7 +66,7 @@ class InventoryParser(object): active_group_name = 'ungrouped' for line in self.lines: - line = line.split("#")[0].strip() + line = utils.before_comment(line).strip() if line.startswith("[") and line.endswith("]"): active_group_name = line.replace("[","").replace("]","") if line.find(":vars") != -1 or line.find(":children") != -1: diff --git a/lib/ansible/utils/__init__.py b/lib/ansible/utils/__init__.py index 02148faff0c..c3e777e4d65 100644 --- a/lib/ansible/utils/__init__.py +++ b/lib/ansible/utils/__init__.py @@ -1071,3 +1071,12 @@ def random_password(length=20, chars=C.DEFAULT_PASSWORD_CHARS): password.append(new_char) return ''.join(password) + +def before_comment(msg): + ''' what's the part of a string before a comment? ''' + msg = msg.replace("\#","**NOT_A_COMMENT**") + msg = msg.split("#")[0] + msg = msg.replace("**NOT_A_COMMENT**","#") + return msg + + diff --git a/test/units/TestUtils.py b/test/units/TestUtils.py index 4bddb4748ba..28e0dfc0cd2 100644 --- a/test/units/TestUtils.py +++ b/test/units/TestUtils.py @@ -16,6 +16,29 @@ sys.setdefaultencoding("utf8") class TestUtils(unittest.TestCase): + def test_before_comment(self): + ''' see if we can detect the part of a string before a comment. Used by INI parser in inventory ''' + + input = "before # comment" + expected = "before " + actual = ansible.utils.before_comment(input) + assert expected == actual + + input = "before \# not a comment" + expected = "before # not a comment" + actual = ansible.utils.before_comment(input) + assert expected == actual + + input = "" + expected = "" + actual = ansible.utils.before_comment(input) + assert expected == actual + + input = "#" + expected = "" + actual = ansible.utils.before_comment(input) + assert expected == actual + ##################################### ### check_conditional tests