mirror of
https://github.com/ansible-collections/community.general.git
synced 2024-09-14 20:13:21 +02:00
crypto: Build a base object for openssl modules (#26945)
More openssl modules are about to be made, each of them rewriting some pieces of code that can be refactored and used via a common library. This commit aims to create this "base" object and the common functions one might want to reuse in order to avoid duplication.
This commit is contained in:
parent
fd771e580f
commit
70f52e3043
1 changed files with 75 additions and 0 deletions
|
@ -23,7 +23,16 @@ except ImportError:
|
|||
# user know that OpenSSL couldn't be found.
|
||||
pass
|
||||
|
||||
import abc
|
||||
import errno
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
from ansible.module_utils import six
|
||||
|
||||
|
||||
class OpenSSLObjectError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def get_fingerprint(path, passphrase):
|
||||
|
@ -48,3 +57,69 @@ def get_fingerprint(path, passphrase):
|
|||
pass
|
||||
|
||||
return fingerprint
|
||||
|
||||
|
||||
def load_privatekey(path, passphrase=None):
|
||||
"""Load the specified OpenSSL private key."""
|
||||
|
||||
try:
|
||||
privatekey_content = open(path, 'rb').read()
|
||||
privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM,
|
||||
privatekey_content,
|
||||
passphrase)
|
||||
return privatekey
|
||||
except (IOError, OSError) as exc:
|
||||
raise OpenSSLObjectError(exc)
|
||||
|
||||
|
||||
def load_certificate(path):
|
||||
"""Load the specified certificate."""
|
||||
|
||||
try:
|
||||
cert_content = open(path, 'rb').read()
|
||||
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_content)
|
||||
return cert
|
||||
except (IOError, OSError) as exc:
|
||||
raise OpenSSLObjectError(exc)
|
||||
|
||||
|
||||
@six.add_metaclass(abc.ABCMeta)
|
||||
class OpenSSLObject(object):
|
||||
|
||||
def __init__(self, path, state, force, check_mode):
|
||||
self.path = path
|
||||
self.state = state
|
||||
self.force = force
|
||||
self.name = os.path.basename(path)
|
||||
self.changed = False
|
||||
self.check_mode = check_mode
|
||||
|
||||
@abc.abstractmethod
|
||||
def check(self):
|
||||
"""Ensure the resource is in its desired state."""
|
||||
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def dump(self):
|
||||
"""Serialize the object into a dictionary."""
|
||||
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def generate(self):
|
||||
"""Generate the resource."""
|
||||
|
||||
pass
|
||||
|
||||
def remove(self):
|
||||
"""Remove the resource from the filesystem."""
|
||||
|
||||
try:
|
||||
os.remove(self.path)
|
||||
self.changed = True
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.ENOENT:
|
||||
raise OpenSSLObjectError(exc)
|
||||
else:
|
||||
pass
|
||||
|
|
Loading…
Reference in a new issue