1# Copyright (c) 2019 Ansible Project
2# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4from __future__ import (absolute_import, division, print_function)
5__metaclass__ = type
6
7DOCUMENTATION = '''
8    name: test
9    plugin_type: inventory
10    short_description: test inventory source
11    extends_documentation_fragment:
12        - inventory_cache
13'''
14
15from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
16
17
18class InventoryModule(BaseInventoryPlugin, Cacheable):
19
20    NAME = 'test'
21
22    def populate(self, hosts):
23        for host in list(hosts.keys()):
24            self.inventory.add_host(host, group='all')
25            for hostvar, hostval in hosts[host].items():
26                self.inventory.set_variable(host, hostvar, hostval)
27
28    def get_hosts(self):
29        return {'host1': {'one': 'two'}, 'host2': {'three': 'four'}}
30
31    def parse(self, inventory, loader, path, cache=True):
32        super(InventoryModule, self).parse(inventory, loader, path)
33
34        self.load_cache_plugin()
35
36        cache_key = self.get_cache_key(path)
37
38        # cache may be True or False at this point to indicate if the inventory is being refreshed
39        # get the user's cache option
40        cache_setting = self.get_option('cache')
41
42        attempt_to_read_cache = cache_setting and cache
43        cache_needs_update = cache_setting and not cache
44
45        # attempt to read the cache if inventory isn't being refreshed and the user has caching enabled
46        if attempt_to_read_cache:
47            try:
48                results = self._cache[cache_key]
49            except KeyError:
50                # This occurs if the cache_key is not in the cache or if the cache_key expired, so the cache needs to be updated
51                cache_needs_update = True
52
53        if cache_needs_update:
54            results = self.get_hosts()
55
56            # set the cache
57            self._cache[cache_key] = results
58
59        self.populate(results)
60