| 1 |
# This file is part of Ansible |
| 2 |
# |
| 3 |
# Ansible is free software: you can redistribute it and/or modify |
| 4 |
# it under the terms of the GNU General Public License as published by |
| 5 |
# the Free Software Foundation, either version 3 of the License, or |
| 6 |
# (at your option) any later version. |
| 7 |
# |
| 8 |
# Ansible is distributed in the hope that it will be useful, |
| 9 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 |
# GNU General Public License for more details. |
| 12 |
# |
| 13 |
# You should have received a copy of the GNU General Public License |
| 14 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 15 |
|
| 16 |
from __future__ import annotations |
| 17 |
|
| 18 |
import json |
| 19 |
import typing as t |
| 20 |
|
| 21 |
from ansible.module_utils.facts.namespace import PrefixFactNamespace |
| 22 |
|
| 23 |
from ansible.module_utils.facts.collector import BaseFactCollector |
| 24 |
|
| 25 |
|
| 26 |
class OhaiFactCollector(BaseFactCollector): |
| 27 |
"""This is a subclass of Facts for including information gathered from Ohai.""" |
| 28 |
name = 'ohai' |
| 29 |
_fact_ids = set() # type: t.Set[str] |
| 30 |
|
| 31 |
def __init__(self, collectors=None, namespace=None): |
| 32 |
namespace = PrefixFactNamespace(namespace_name='ohai', |
| 33 |
prefix='ohai_') |
| 34 |
super(OhaiFactCollector, self).__init__(collectors=collectors, |
| 35 |
namespace=namespace) |
| 36 |
|
| 37 |
def find_ohai(self, module): |
| 38 |
return module.get_bin_path( |
| 39 |
'ohai' |
| 40 |
) |
| 41 |
|
| 42 |
def run_ohai(self, module, ohai_path): |
| 43 |
rc, out, err = module.run_command(ohai_path) |
| 44 |
return rc, out, err |
| 45 |
|
| 46 |
def get_ohai_output(self, module): |
| 47 |
ohai_path = self.find_ohai(module) |
| 48 |
if not ohai_path: |
| 49 |
return None |
| 50 |
|
| 51 |
rc, out, err = self.run_ohai(module, ohai_path) |
| 52 |
if rc != 0: |
| 53 |
return None |
| 54 |
|
| 55 |
return out |
| 56 |
|
| 57 |
def collect(self, module=None, collected_facts=None): |
| 58 |
ohai_facts = {} |
| 59 |
if not module: |
| 60 |
return ohai_facts |
| 61 |
|
| 62 |
ohai_output = self.get_ohai_output(module) |
| 63 |
|
| 64 |
if ohai_output is None: |
| 65 |
return ohai_facts |
| 66 |
|
| 67 |
try: |
| 68 |
ohai_facts = json.loads(ohai_output) |
| 69 |
except Exception: |
| 70 |
module.warn("Failed to gather ohai facts") |
| 71 |
|
| 72 |
return ohai_facts |