diff --git a/lib/ansible/module_utils/crypto.py b/lib/ansible/module_utils/crypto.py index d9526b8026..4f2b770cd4 100644 --- a/lib/ansible/module_utils/crypto.py +++ b/lib/ansible/module_utils/crypto.py @@ -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