예제 #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
    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()
예제 #3
0
    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
예제 #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
파일: __init__.py 프로젝트: jinnko/ansible
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[:]
예제 #6
0
파일: __init__.py 프로젝트: jinnko/ansible
    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()
예제 #7
0
    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
예제 #8
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")
예제 #9
0
    def load_data(self, ds, loader=None):
        ''' walk the input datastructure and assign any values '''

        assert ds is not None

        # the data loader class is used to parse data from strings and files
        if loader is not None:
            self._loader = loader
        else:
            self._loader = DataLoader()

        if isinstance(ds, string_types) or isinstance(ds, FileIO):
            ds = self._loader.load(ds)

        # call the munge() function to massage the data into something
        # we can more easily parse, and then call the validation function
        # on it to ensure there are no incorrect key values
        ds = self.munge(ds)
        self._validate_attributes(ds)

        # Walk all attributes in the class.
        #
        # FIXME: we currently don't do anything with private attributes but
        #        may later decide to filter them out of 'ds' here.

        for (name, attribute) in iteritems(self._get_base_attributes()):
            # copy the value over unless a _load_field method is defined
            if name in ds:
                method = getattr(self, '_load_%s' % name, None)
                if method:
                    self._attributes[name] = method(name, ds[name])
                else:
                    self._attributes[name] = ds[name]

        # return the constructed object
        self.validate()
        return self
예제 #10
0
파일: base.py 프로젝트: jinnko/ansible
    def load_data(self, ds, loader=None):
        ''' walk the input datastructure and assign any values '''

        assert ds is not None

        # the data loader class is used to parse data from strings and files
        if loader is not None:
            self._loader = loader
        else:
            self._loader = DataLoader()

        if isinstance(ds, string_types) or isinstance(ds, FileIO):
            ds = self._loader.load(ds)

        # call the munge() function to massage the data into something
        # we can more easily parse, and then call the validation function
        # on it to ensure there are no incorrect key values
        ds = self.munge(ds)
        self._validate_attributes(ds)

        # Walk all attributes in the class.
        #
        # FIXME: we currently don't do anything with private attributes but
        #        may later decide to filter them out of 'ds' here.

        for (name, attribute) in iteritems(self._get_base_attributes()):
            # copy the value over unless a _load_field method is defined
            if name in ds:
                method = getattr(self, '_load_%s' % name, None)
                if method:
                    self._attributes[name] = method(name, ds[name])
                else:
                    self._attributes[name] = ds[name]

        # return the constructed object
        self.validate()
        return self
예제 #11
0
파일: base.py 프로젝트: jinnko/ansible
class Base:

    def __init__(self):

        # initialize the data loader, this will be provided later
        # when the object is actually loaded
        self._loader = None

        # each class knows attributes set upon it, see Task.py for example
        self._attributes = dict()

        for (name, value) in iteritems(self._get_base_attributes()):
            self._attributes[name] = value.default

    def _get_base_attributes(self):
        '''
        Returns the list of attributes for this class (or any subclass thereof).
        If the attribute name starts with an underscore, it is removed
        '''
        base_attributes = dict()
        for (name, value) in getmembers(self.__class__):
            if isinstance(value, Attribute):
               if name.startswith('_'):
                   name = name[1:]
               base_attributes[name] = value
        return base_attributes

    def munge(self, ds):
        ''' infrequently used method to do some pre-processing of legacy terms '''

        return ds

    def load_data(self, ds, loader=None):
        ''' walk the input datastructure and assign any values '''

        assert ds is not None

        # the data loader class is used to parse data from strings and files
        if loader is not None:
            self._loader = loader
        else:
            self._loader = DataLoader()

        if isinstance(ds, string_types) or isinstance(ds, FileIO):
            ds = self._loader.load(ds)

        # call the munge() function to massage the data into something
        # we can more easily parse, and then call the validation function
        # on it to ensure there are no incorrect key values
        ds = self.munge(ds)
        self._validate_attributes(ds)

        # Walk all attributes in the class.
        #
        # FIXME: we currently don't do anything with private attributes but
        #        may later decide to filter them out of 'ds' here.

        for (name, attribute) in iteritems(self._get_base_attributes()):
            # copy the value over unless a _load_field method is defined
            if name in ds:
                method = getattr(self, '_load_%s' % name, None)
                if method:
                    self._attributes[name] = method(name, ds[name])
                else:
                    self._attributes[name] = ds[name]

        # return the constructed object
        self.validate()
        return self

    def get_loader(self):
        return self._loader

    def _validate_attributes(self, ds):
        '''
        Ensures that there are no keys in the datastructure which do
        not map to attributes for this object.
        '''

        valid_attrs = [name for (name, attribute) in iteritems(self._get_base_attributes())]
        for key in ds:
            if key not in valid_attrs:
                raise AnsibleParserError("'%s' is not a valid attribute for a %s" % (key, self.__class__.__name__), obj=ds)

    def validate(self):
        ''' validation that is done at parse time, not load time '''

        # walk all fields in the object
        for (name, attribute) in iteritems(self._get_base_attributes()):

            # run validator only if present
            method = getattr(self, '_validate_%s' % name, None)
            if method:
                method(self, attribute)

    def post_validate(self, runner_context):
        '''
        we can't tell that everything is of the right type until we have
        all the variables.  Run basic types (from isa) as well as
        any _post_validate_<foo> functions.
        '''

        raise exception.NotImplementedError

    def __getattr__(self, needle):

        # return any attribute names as if they were real
        # optionally allowing masking by accessors

        if not needle.startswith("_"):
            method = "get_%s" % needle
            if method in self.__dict__:
                return method(self)

        if needle in self._attributes:
            return self._attributes[needle]

        raise AttributeError("attribute not found: %s" % needle)
예제 #12
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
예제 #13
0
 def setUp(self):
     # FIXME: need to add tests that utilize vault_password
     self._loader = DataLoader()
예제 #14
0
class Base:
    def __init__(self):

        # initialize the data loader, this will be provided later
        # when the object is actually loaded
        self._loader = None

        # each class knows attributes set upon it, see Task.py for example
        self._attributes = dict()

        for (name, value) in iteritems(self._get_base_attributes()):
            self._attributes[name] = value.default

    def _get_base_attributes(self):
        '''
        Returns the list of attributes for this class (or any subclass thereof).
        If the attribute name starts with an underscore, it is removed
        '''
        base_attributes = dict()
        for (name, value) in getmembers(self.__class__):
            if isinstance(value, Attribute):
                if name.startswith('_'):
                    name = name[1:]
                base_attributes[name] = value
        return base_attributes

    def munge(self, ds):
        ''' infrequently used method to do some pre-processing of legacy terms '''

        return ds

    def load_data(self, ds, loader=None):
        ''' walk the input datastructure and assign any values '''

        assert ds is not None

        # the data loader class is used to parse data from strings and files
        if loader is not None:
            self._loader = loader
        else:
            self._loader = DataLoader()

        if isinstance(ds, string_types) or isinstance(ds, FileIO):
            ds = self._loader.load(ds)

        # call the munge() function to massage the data into something
        # we can more easily parse, and then call the validation function
        # on it to ensure there are no incorrect key values
        ds = self.munge(ds)
        self._validate_attributes(ds)

        # Walk all attributes in the class.
        #
        # FIXME: we currently don't do anything with private attributes but
        #        may later decide to filter them out of 'ds' here.

        for (name, attribute) in iteritems(self._get_base_attributes()):
            # copy the value over unless a _load_field method is defined
            if name in ds:
                method = getattr(self, '_load_%s' % name, None)
                if method:
                    self._attributes[name] = method(name, ds[name])
                else:
                    self._attributes[name] = ds[name]

        # return the constructed object
        self.validate()
        return self

    def get_loader(self):
        return self._loader

    def _validate_attributes(self, ds):
        '''
        Ensures that there are no keys in the datastructure which do
        not map to attributes for this object.
        '''

        valid_attrs = [
            name
            for (name, attribute) in iteritems(self._get_base_attributes())
        ]
        for key in ds:
            if key not in valid_attrs:
                raise AnsibleParserError(
                    "'%s' is not a valid attribute for a %s" %
                    (key, self.__class__.__name__),
                    obj=ds)

    def validate(self):
        ''' validation that is done at parse time, not load time '''

        # walk all fields in the object
        for (name, attribute) in iteritems(self._get_base_attributes()):

            # run validator only if present
            method = getattr(self, '_validate_%s' % name, None)
            if method:
                method(self, attribute)

    def post_validate(self, runner_context):
        '''
        we can't tell that everything is of the right type until we have
        all the variables.  Run basic types (from isa) as well as
        any _post_validate_<foo> functions.
        '''

        raise exception.NotImplementedError

    def __getattr__(self, needle):

        # return any attribute names as if they were real
        # optionally allowing masking by accessors

        if not needle.startswith("_"):
            method = "get_%s" % needle
            if method in self.__dict__:
                return method(self)

        if needle in self._attributes:
            return self._attributes[needle]

        raise AttributeError("attribute not found: %s" % needle)
예제 #15
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
예제 #16
0
 def setUp(self):
     # FIXME: need to add tests that utilize vault_password
     self._loader = DataLoader()