Create a user. Adds a key file to authorized_keys if given.

def create_user(name, groups=None, key_file=None):
    """Create a user. Adds a key file to authorized_keys if given."""

    groups = groups or []
    if not user_exists(name):
        for group in groups:
            if not group_exists(group):
                sudo(u"addgroup %s" % group)
        groups = groups and u'-G %s' % u','.join(groups) or ''
        sudo(u"useradd -m %s -s /bin/bash %s" % (groups, name))
        sudo(u"passwd -d %s" % name)
    if key_file:
        sudo(u"mkdir -p /home/%s/.ssh" % name)
        put(key_file, u"/home/%s/.ssh/authorized_keys" % name, use_sudo=True)
        sudo(u"chown -R %(name)s:%(name)s /home/%(name)s/.ssh" % {'name': name})