diff --git a/changelogs/fragments/55781-fact-cache-first_merge_order.yml b/changelogs/fragments/55781-fact-cache-first_merge_order.yml new file mode 100644 index 00000000000..ccdcb4e0cdd --- /dev/null +++ b/changelogs/fragments/55781-fact-cache-first_merge_order.yml @@ -0,0 +1,2 @@ +bugfixes: + - fact_cache - Define the first_order_merge method for the legacy FactCache.update(key, value). diff --git a/lib/ansible/vars/fact_cache.py b/lib/ansible/vars/fact_cache.py index 25ffe70e491..7b6021a1cbd 100644 --- a/lib/ansible/vars/fact_cache.py +++ b/lib/ansible/vars/fact_cache.py @@ -58,6 +58,19 @@ class FactCache(MutableMapping): """ Flush the fact cache of all keys. """ self._plugin.flush() + def first_order_merge(self, key, value): + host_facts = {key: value} + + try: + host_cache = self._plugin.get(key) + if host_cache: + host_cache.update(value) + host_facts[key] = host_cache + except KeyError: + pass + + super(FactCache, self).update(host_facts) + def update(self, *args): """ Backwards compat shim diff --git a/test/units/plugins/cache/test_cache.py b/test/units/plugins/cache/test_cache.py index d14c1a4845f..8975c27cc84 100644 --- a/test/units/plugins/cache/test_cache.py +++ b/test/units/plugins/cache/test_cache.py @@ -117,6 +117,12 @@ class TestFactCache(unittest.TestCase): "Unable to load the facts cache plugin.*json.*", FactCache) + def test_update_legacy_key_exists(self): + self.cache['cache_key'] = {'key': 'value', 'key2': 'value2'} + self.cache.update('cache_key', {'key': 'updatedvalue'}) + assert self.cache['cache_key']['key'] == 'updatedvalue' + assert self.cache['cache_key']['key2'] == 'value2' + class TestAbstractClass(unittest.TestCase):