import logging


def create_ssh_key(nova_client, keypair_name, replace=False):
    """Create ssh key.

    :param nova_client: Authenticated nova client
    :type nova_client: novaclient.v2.client.Client
    :param keypair_name: Label to apply to keypair in OpenStack.
    :type keypair_name: str
    :param replace: Whether to replace the existing keypair if it already
                    exists.
    :type replace: str
    :returns: The keypair
    :rtype: nova.objects.keypair
    """
    existing_keys = nova_client.keypairs.findall(name=keypair_name)
    if existing_keys:
        if replace:
            logging.info('Deleting key(s) {}'.format(keypair_name))
            for key in existing_keys:
                nova_client.keypairs.delete(key)
        else:
            return existing_keys[0]
    logging.info('Creating key %s' % (keypair_name))
    return nova_client.keypairs.create(name=keypair_name)