| 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 typing as t |
| 19 |
|
| 20 |
from ansible.module_utils.facts.utils import get_file_content |
| 21 |
|
| 22 |
from ansible.module_utils.facts.collector import BaseFactCollector |
| 23 |
|
| 24 |
|
| 25 |
class SshPubKeyFactCollector(BaseFactCollector): |
| 26 |
name = 'ssh_pub_keys' |
| 27 |
_fact_ids = set(['ssh_host_pub_keys', |
| 28 |
'ssh_host_key_dsa_public', |
| 29 |
'ssh_host_key_rsa_public', |
| 30 |
'ssh_host_key_ecdsa_public', |
| 31 |
'ssh_host_key_ed25519_public']) # type: t.Set[str] |
| 32 |
|
| 33 |
def collect(self, module=None, collected_facts=None): |
| 34 |
ssh_pub_key_facts = {} |
| 35 |
algos = ('dsa', 'rsa', 'ecdsa', 'ed25519') |
| 36 |
|
| 37 |
# list of directories to check for ssh keys |
| 38 |
# used in the order listed here, the first one with keys is used |
| 39 |
keydirs = ['/etc/ssh', '/etc/openssh', '/etc'] |
| 40 |
|
| 41 |
for keydir in keydirs: |
| 42 |
for algo in algos: |
| 43 |
factname = 'ssh_host_key_%s_public' % algo |
| 44 |
if factname in ssh_pub_key_facts: |
| 45 |
# a previous keydir was already successful, stop looking |
| 46 |
# for keys |
| 47 |
return ssh_pub_key_facts |
| 48 |
key_filename = '%s/ssh_host_%s_key.pub' % (keydir, algo) |
| 49 |
keydata = get_file_content(key_filename) |
| 50 |
if keydata is not None: |
| 51 |
(keytype, key) = keydata.split()[0:2] |
| 52 |
ssh_pub_key_facts[factname] = key |
| 53 |
ssh_pub_key_facts[factname + '_keytype'] = keytype |
| 54 |
|
| 55 |
return ssh_pub_key_facts |