Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
Size: Mime:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import shutil
import socket
import subprocess
import traceback
import tvault_configurator
from ansible.module_utils.basic import AnsibleModule

import configparser

DOCUMENTATION = '''
---

module: generate_ssl_keys
short_description: Generate ssl keys in case the host name is changed or keys were never generated
options:
   None

requirements: []

author: Murali Balcha
'''

EXAMPLES = '''
examples:
- name: Generate ssl keys for triliovault configurator
  generate_ssl_keys:

'''


def create_ssl_certificates():

    if not os.path.exists('/etc/tvault-config/'):
        os.makedirs('/etc/tvault-config')

    if not os.path.exists('/etc/tvault/ssl/'):
        os.makedirs('/etc/tvault/ssl')

    # SSL regeneration
    common_hostname = 'server'
    prev_hostname = None
    ssl_crts_created = False
    Config = configparser.RawConfigParser()
    try:
        Config.read('/etc/tvault-config/tvault-config.conf')
        config_data = dict(Config._defaults)
        prev_hostname = config_data.get('hostname', None)
        ssl_crts_created = config_data.get('ssl_crts_created', 'False').lower() == 'true'
    except Exception as exception:
        prev_hostname = None

    if prev_hostname == socket.gethostname() and \
        ssl_crts_created and \
        os.path.exists("/etc/tvault/ssl/%s.crt" % prev_hostname) and \
        os.path.exists("/etc/tvault/ssl/%s.key" % prev_hostname):
        return {'changed': False}

    #LOG.debug("Either the service is starting for the first time or "
              #"the host name changes since last time the "
              #"daemon configured. Recreating SSL certificates")

    if os.path.exists("/etc/tvault/ssl/%s.crt" % prev_hostname):
        shutil.move("/etc/tvault/ssl/%s.crt" % prev_hostname,
                    "/etc/tvault/ssl/%s_bak.crt" % prev_hostname)
    if os.path.exists("/etc/tvault/ssl/%s.key" % prev_hostname):
        shutil.move("/etc/tvault/ssl/%s.key" % prev_hostname,
                    "/etc/tvault/ssl/%s_bak.key" % prev_hostname)
    shutil.copy2(os.path.join(tvault_configurator.__path__[0], "etc", "gen-cer"),
                 "/etc/tvault/ssl/")
    os.chmod('/etc/tvault/ssl/gen-cer', 0o554)
    command = ['sudo', 'sh', 'gen-cer', socket.gethostname()]
    subprocess.call(command, shell=False, cwd="/etc/tvault/ssl")
    command = ['sudo', 'rm', '-rf',
               os.path.join("/etc/tvault/ssl/",
                            socket.gethostname() + ".csr")]
    subprocess.call(command, shell=False, cwd="/etc/tvault/ssl")
    Config.set(None, 'hostname', socket.gethostname())

    # create soft links to common_hostname
    command = ['sudo', 'ln', '-snf', socket.gethostname() + ".key",
                common_hostname + ".key"]
    subprocess.call(command, shell=False, cwd="/etc/tvault/ssl")
    command = ['sudo', 'ln', '-snf', socket.gethostname() + ".crt",
                common_hostname + ".crt"]
    subprocess.call(command, shell=False, cwd="/etc/tvault/ssl")
    command = ['sudo', 'ln', '-snf', socket.gethostname() + ".pem",
                common_hostname + ".pem"]
    subprocess.call(command, shell=False, cwd="/etc/tvault/ssl")


     # create hostkeys
    command = ['sudo', 'rm', "/etc/ssh/ssh_host_rsa_key"]
    subprocess.call(command, shell=False)
    command = ['sudo', 'ssh-keygen', '-f',
               "/etc/ssh/ssh_host_rsa_key", '-b', '4096', '-t',
               'rsa', '-q', '-N', ""]
    subprocess.call(command, shell=False)

    Config.set(None, 'ssl_crts_created', True)
    with open('/etc/tvault-config/tvault-config.conf',
              'w') as configfile:
        Config.write(configfile)
 
    return dict(changed=True)


def main():

    module = AnsibleModule(
        argument_spec=dict(
        ),
    )

    try:
        d = create_ssl_certificates()
    except Exception:
        module.fail_json(msg=traceback.format_exc())
    else:
        module.exit_json(**d)


# this is magic, see lib/ansible/module_common.py
# <<INCLUDE_ANSIBLE_MODULE_COMMON>>
if __name__ == '__main__':
    main()