示例#1
0
class TestDataLoader(unittest.TestCase):
    def setUp(self):
        # FIXME: need to add tests that utilize vault_password
        self._loader = DataLoader()

    def tearDown(self):
        pass

    @patch.object(DataLoader, '_get_file_contents')
    def test_parse_json_from_file(self, mock_def):
        mock_def.return_value = ("""{"a": 1, "b": 2, "c": 3}""", True)
        output = self._loader.load_from_file('dummy_json.txt')
        self.assertEqual(output, dict(a=1, b=2, c=3))

    @patch.object(DataLoader, '_get_file_contents')
    def test_parse_yaml_from_file(self, mock_def):
        mock_def.return_value = ("""
        a: 1
        b: 2
        c: 3
        """, True)
        output = self._loader.load_from_file('dummy_yaml.txt')
        self.assertEqual(output, dict(a=1, b=2, c=3))

    @patch.object(DataLoader, '_get_file_contents')
    def test_parse_fail_from_file(self, mock_def):
        mock_def.return_value = ("""
        TEXT:
            ***
               NOT VALID
        """, True)
        self.assertRaises(AnsibleParserError, self._loader.load_from_file,
                          'dummy_yaml_bad.txt')
示例#2
0
class Playbook:
    def __init__(self, loader=None):
        # Entries in the datastructure of a playbook may
        # be either a play or an include statement
        self._entries = []
        self._basedir = '.'

        if loader:
            self._loader = loader
        else:
            self._loader = DataLoader()

    @staticmethod
    def load(file_name, loader=None):
        pb = Playbook(loader=loader)
        pb._load_playbook_data(file_name)
        return pb

    def _load_playbook_data(self, file_name):

        # add the base directory of the file to the data loader,
        # so that it knows where to find relatively pathed files
        basedir = os.path.dirname(file_name)
        self._loader.set_basedir(basedir)

        # also add the basedir to the list of module directories
        push_basedir(basedir)

        ds = self._loader.load_from_file(file_name)
        if not isinstance(ds, list):
            raise AnsibleParserError("playbooks must be a list of plays",
                                     obj=ds)

        # Parse the playbook entries. For plays, we simply parse them
        # using the Play() object, and includes are parsed using the
        # PlaybookInclude() object
        for entry in ds:
            if not isinstance(entry, dict):
                raise AnsibleParserError(
                    "playbook entries must be either a valid play or an include statement",
                    obj=entry)

            if 'include' in entry:
                entry_obj = PlaybookInclude.load(entry, loader=self._loader)
            else:
                entry_obj = Play.load(entry, loader=self._loader)

            self._entries.append(entry_obj)

    def get_entries(self):
        return self._entries[:]
示例#3
0
class TestDataLoader(unittest.TestCase):
    def setUp(self):
        # FIXME: need to add tests that utilize vault_password
        self._loader = DataLoader()

    def tearDown(self):
        pass

    @patch.object(DataLoader, "_get_file_contents")
    def test_parse_json_from_file(self, mock_def):
        mock_def.return_value = ("""{"a": 1, "b": 2, "c": 3}""", True)
        output = self._loader.load_from_file("dummy_json.txt")
        self.assertEqual(output, dict(a=1, b=2, c=3))

    @patch.object(DataLoader, "_get_file_contents")
    def test_parse_yaml_from_file(self, mock_def):
        mock_def.return_value = (
            """
        a: 1
        b: 2
        c: 3
        """,
            True,
        )
        output = self._loader.load_from_file("dummy_yaml.txt")
        self.assertEqual(output, dict(a=1, b=2, c=3))

    @patch.object(DataLoader, "_get_file_contents")
    def test_parse_fail_from_file(self, mock_def):
        mock_def.return_value = (
            """
        TEXT:
            ***
               NOT VALID
        """,
            True,
        )
        self.assertRaises(AnsibleParserError, self._loader.load_from_file, "dummy_yaml_bad.txt")
示例#4
0
class Playbook:

    def __init__(self, loader=None):
        # Entries in the datastructure of a playbook may
        # be either a play or an include statement
        self._entries = []
        self._basedir = '.'

        if loader:
            self._loader = loader
        else:
            self._loader = DataLoader()

    @staticmethod
    def load(file_name, loader=None):
        pb = Playbook(loader=loader)
        pb._load_playbook_data(file_name)
        return pb

    def _load_playbook_data(self, file_name):

        # add the base directory of the file to the data loader,
        # so that it knows where to find relatively pathed files
        basedir = os.path.dirname(file_name)
        self._loader.set_basedir(basedir)

        # also add the basedir to the list of module directories
        push_basedir(basedir)

        ds = self._loader.load_from_file(file_name)
        if not isinstance(ds, list):
            raise AnsibleParserError("playbooks must be a list of plays", obj=ds)

        # Parse the playbook entries. For plays, we simply parse them
        # using the Play() object, and includes are parsed using the
        # PlaybookInclude() object
        for entry in ds:
            if not isinstance(entry, dict):
                raise AnsibleParserError("playbook entries must be either a valid play or an include statement", obj=entry)

            if 'include' in entry:
                entry_obj = PlaybookInclude.load(entry, loader=self._loader)
            else:
                entry_obj = Play.load(entry, loader=self._loader)

            self._entries.append(entry_obj)

    def get_entries(self):
        return self._entries[:]
示例#5
0
class VariableManager:
    def __init__(self, inventory_path=None, loader=None):

        self._fact_cache = FactCache()
        self._vars_cache = defaultdict(dict)
        self._extra_vars = defaultdict(dict)
        self._host_vars_files = defaultdict(dict)
        self._group_vars_files = defaultdict(dict)

        if not loader:
            self._loader = DataLoader()
        else:
            self._loader = loader

    @property
    def extra_vars(self):
        ''' ensures a clean copy of the extra_vars are made '''
        return self._extra_vars.copy()

    def set_extra_vars(self, value):
        ''' ensures a clean copy of the extra_vars are used to set the value '''
        assert isinstance(value, dict)
        self._extra_vars = value.copy()

    def _merge_dicts(self, a, b):
        '''
        Recursively merges dict b into a, so that keys
        from b take precedence over keys from a.
        '''

        result = dict()

        # FIXME: do we need this from utils, or should it just
        #        be merged into this definition?
        #_validate_both_dicts(a, b)

        for dicts in a, b:
            # next, iterate over b keys and values
            for k, v in dicts.iteritems():
                # if there's already such key in a
                # and that key contains dict
                if k in result and isinstance(result[k], dict):
                    # merge those dicts recursively
                    result[k] = self._merge_dicts(a[k], v)
                else:
                    # otherwise, just copy a value from b to a
                    result[k] = v

        return result

    def get_vars(self, play=None, host=None, task=None):
        '''
        Returns the variables, with optional "context" given via the parameters
        for the play, host, and task (which could possibly result in different
        sets of variables being returned due to the additional context).

        The order of precedence is:
        - play->roles->get_default_vars (if there is a play context)
        - group_vars_files[host] (if there is a host context)
        - host_vars_files[host] (if there is a host context)
        - host->get_vars (if there is a host context)
        - fact_cache[host] (if there is a host context)
        - vars_cache[host] (if there is a host context)
        - play vars (if there is a play context)
        - play vars_files (if there's no host context, ignore
          file names that cannot be templated)
        - task->get_vars (if there is a task context)
        - extra vars
        '''

        vars = defaultdict(dict)

        if play:
            # first we compile any vars specified in defaults/main.yml
            # for all roles within the specified play
            for role in play.get_roles():
                vars = self._merge_dicts(vars, role.get_default_vars())

        if host:
            # next, if a host is specified, we load any vars from group_vars
            # files and then any vars from host_vars files which may apply to
            # this host or the groups it belongs to
            for group in host.get_groups():
                if group in self._group_vars_files:
                    vars = self._merge_dicts(vars,
                                             self._group_vars_files[group])

            host_name = host.get_name()
            if host_name in self._host_vars_files:
                vars = self._merge_dicts(vars,
                                         self._host_vars_files[host_name])

            # then we merge in vars specified for this host
            vars = self._merge_dicts(vars, host.get_vars())

            # next comes the facts cache and the vars cache, respectively
            vars = self._merge_dicts(
                vars, self._fact_cache.get(host.get_name(), dict()))
            vars = self._merge_dicts(
                vars, self._vars_cache.get(host.get_name(), dict()))

        if play:
            vars = self._merge_dicts(vars, play.get_vars())
            for vars_file in play.get_vars_files():
                # Try templating the vars_file. If an unknown var error is raised,
                # ignore it - unless a host is specified
                # TODO ...

                data = self._loader.load_from_file(vars_file)
                vars = self._merge_dicts(vars, data)

        if task:
            vars = self._merge_dicts(vars, task.get_vars())

        vars = self._merge_dicts(vars, self._extra_vars)

        return vars

    def _get_inventory_basename(self, path):
        '''
        Returns the bsaename minus the extension of the given path, so the
        bare filename can be matched against host/group names later
        '''

        (name, ext) = os.path.splitext(os.path.basename(path))
        return name

    def _load_inventory_file(self, path):
        '''
        helper function, which loads the file and gets the
        basename of the file without the extension
        '''

        data = self._loader.load_from_file(path)
        name = self._get_inventory_basename(path)
        return (name, data)

    def add_host_vars_file(self, path):
        '''
        Loads and caches a host_vars file in the _host_vars_files dict,
        where the key to that dictionary is the basename of the file, minus
        the extension, for matching against a given inventory host name
        '''

        (name, data) = self._load_inventory_file(path)
        self._host_vars_files[name] = data

    def add_group_vars_file(self, path):
        '''
        Loads and caches a host_vars file in the _host_vars_files dict,
        where the key to that dictionary is the basename of the file, minus
        the extension, for matching against a given inventory host name
        '''

        (name, data) = self._load_inventory_file(path)
        self._group_vars_files[name] = data
示例#6
0
class VariableManager:

    def __init__(self, inventory_path=None, loader=None):

        self._fact_cache       = FactCache()
        self._vars_cache       = defaultdict(dict)
        self._extra_vars       = defaultdict(dict)
        self._host_vars_files  = defaultdict(dict)
        self._group_vars_files = defaultdict(dict)

        if not loader:
            self._loader = DataLoader()
        else:
            self._loader = loader

    @property
    def extra_vars(self):
        ''' ensures a clean copy of the extra_vars are made '''
        return self._extra_vars.copy()

    def set_extra_vars(self, value):
        ''' ensures a clean copy of the extra_vars are used to set the value '''
        assert isinstance(value, dict)
        self._extra_vars = value.copy()

    def _merge_dicts(self, a, b):
        '''
        Recursively merges dict b into a, so that keys
        from b take precedence over keys from a.
        '''

        result = dict()

        # FIXME: do we need this from utils, or should it just
        #        be merged into this definition?
        #_validate_both_dicts(a, b)

        for dicts in a, b:
            # next, iterate over b keys and values
            for k, v in dicts.iteritems():
                # if there's already such key in a
                # and that key contains dict
                if k in result and isinstance(result[k], dict):
                    # merge those dicts recursively
                    result[k] = self._merge_dicts(a[k], v)
                else:
                    # otherwise, just copy a value from b to a
                    result[k] = v

        return result

    def get_vars(self, play=None, host=None, task=None):
        '''
        Returns the variables, with optional "context" given via the parameters
        for the play, host, and task (which could possibly result in different
        sets of variables being returned due to the additional context).

        The order of precedence is:
        - play->roles->get_default_vars (if there is a play context)
        - group_vars_files[host] (if there is a host context)
        - host_vars_files[host] (if there is a host context)
        - host->get_vars (if there is a host context)
        - fact_cache[host] (if there is a host context)
        - vars_cache[host] (if there is a host context)
        - play vars (if there is a play context)
        - play vars_files (if there's no host context, ignore
          file names that cannot be templated)
        - task->get_vars (if there is a task context)
        - extra vars
        '''

        vars = defaultdict(dict)

        if play:
            # first we compile any vars specified in defaults/main.yml
            # for all roles within the specified play
            for role in play.get_roles():
                vars = self._merge_dicts(vars, role.get_default_vars())

        if host:
            # next, if a host is specified, we load any vars from group_vars
            # files and then any vars from host_vars files which may apply to
            # this host or the groups it belongs to
            for group in host.get_groups():
                if group in self._group_vars_files:
                    vars = self._merge_dicts(vars, self._group_vars_files[group])

            host_name = host.get_name()
            if host_name in self._host_vars_files:
                vars = self._merge_dicts(vars, self._host_vars_files[host_name])

            # then we merge in vars specified for this host
            vars = self._merge_dicts(vars, host.get_vars())

            # next comes the facts cache and the vars cache, respectively
            vars = self._merge_dicts(vars, self._fact_cache.get(host.get_name(), dict()))
            vars = self._merge_dicts(vars, self._vars_cache.get(host.get_name(), dict()))

        if play:
            vars = self._merge_dicts(vars, play.get_vars())
            for vars_file in play.get_vars_files():
                # Try templating the vars_file. If an unknown var error is raised,
                # ignore it - unless a host is specified
                # TODO ...

                data = self._loader.load_from_file(vars_file)
                vars = self._merge_dicts(vars, data)

        if task:
            vars = self._merge_dicts(vars, task.get_vars())

        vars = self._merge_dicts(vars, self._extra_vars)

        return vars

    def _get_inventory_basename(self, path):
        '''
        Returns the bsaename minus the extension of the given path, so the
        bare filename can be matched against host/group names later
        '''

        (name, ext) = os.path.splitext(os.path.basename(path))
        return name

    def _load_inventory_file(self, path):
        '''
        helper function, which loads the file and gets the
        basename of the file without the extension
        '''

        data = self._loader.load_from_file(path)
        name = self._get_inventory_basename(path)
        return (name, data)

    def add_host_vars_file(self, path):
        '''
        Loads and caches a host_vars file in the _host_vars_files dict,
        where the key to that dictionary is the basename of the file, minus
        the extension, for matching against a given inventory host name
        '''

        (name, data) = self._load_inventory_file(path)
        self._host_vars_files[name] = data

    def add_group_vars_file(self, path):
        '''
        Loads and caches a host_vars file in the _host_vars_files dict,
        where the key to that dictionary is the basename of the file, minus
        the extension, for matching against a given inventory host name
        '''

        (name, data) = self._load_inventory_file(path)
        self._group_vars_files[name] = data