Debian Codegraph @

lib/ansible/module_utils/facts/other/facter.py

raw
1 # Copyright (c) 2023 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 import json
7 import typing as t
8
9 from ansible.module_utils.facts.namespace import PrefixFactNamespace
10 from ansible.module_utils.facts.collector import BaseFactCollector
11
12
13 class FacterFactCollector(BaseFactCollector):
14 name = 'facter'
15 _fact_ids = set(['facter']) # type: t.Set[str]
16
17 def __init__(self, collectors=None, namespace=None):
18 namespace = PrefixFactNamespace(namespace_name='facter',
19 prefix='facter_')
20 super(FacterFactCollector, self).__init__(collectors=collectors,
21 namespace=namespace)
22
23 def find_facter(self, module):
24 facter_path = module.get_bin_path(
25 'facter',
26 opt_dirs=['/opt/puppetlabs/bin']
27 )
28 cfacter_path = module.get_bin_path(
29 'cfacter',
30 opt_dirs=['/opt/puppetlabs/bin']
31 )
32
33 # Prefer to use cfacter if available
34 if cfacter_path is not None:
35 facter_path = cfacter_path
36
37 return facter_path
38
39 def run_facter(self, module, facter_path):
40 # if facter is installed, and we can use --json because
41 # ruby-json is ALSO installed, include facter data in the JSON
42 rc, out, err = module.run_command(facter_path + " --puppet --json")
43
44 # for some versions of facter, --puppet returns an error if puppet is not present,
45 # try again w/o it, other errors should still appear and be sent back
46 if rc != 0:
47 rc, out, err = module.run_command(facter_path + " --json")
48
49 return rc, out, err
50
51 def get_facter_output(self, module):
52 facter_path = self.find_facter(module)
53 if not facter_path:
54 return None
55
56 rc, out, err = self.run_facter(module, facter_path)
57
58 if rc != 0:
59 return None
60
61 return out
62
63 def collect(self, module=None, collected_facts=None):
64 # Note that this mirrors previous facter behavior, where there isn't
65 # a 'ansible_facter' key in the main fact dict, but instead, 'facter_whatever'
66 # items are added to the main dict.
67 facter_dict = {}
68
69 if not module:
70 return facter_dict
71
72 facter_output = self.get_facter_output(module)
73
74 # TODO: if we fail, should we add a empty facter key or nothing?
75 if facter_output is None:
76 return facter_dict
77
78 try:
79 facter_dict = json.loads(facter_output)
80 except Exception:
81 module.warn("Failed to parse facter facts")
82
83 return facter_dict