Exemplo n.º 1
0
def main():
    module = AnsibleModule(
        argument_spec = dict(
            name                            = dict(required=True,
                                                   type='str'),
            ou                              = dict(required=True,
                                                   type='str'),
            owner                           = dict(type='str',
                                                   default='0'),
            group                           = dict(type='str',
                                                   default='0'),
            path                            = dict(type='path',
                                                   default=None),
            directorymode                   = dict(type='str',
                                                   default='00755'),
            host                            = dict(type='str',
                                                   default=None),
            root_squash                     = dict(type='bool',
                                                   default=True),
            subtree_checking                = dict(type='bool',
                                                   default=True),
            sync                            = dict(type='str',
                                                   default='sync'),
            writeable                       = dict(type='bool',
                                                   default=True),
            sambaBlockSize                  = dict(type='str',
                                                   aliases=['samba_block_size'],
                                                   default=None),
            sambaBlockingLocks              = dict(type='bool',
                                                   aliases=['samba_blocking_locks'],
                                                   default=True),
            sambaBrowseable                 = dict(type='bool',
                                                   aliases=['samba_browsable'],
                                                   default=True),
            sambaCreateMode                 = dict(type='str',
                                                   aliases=['samba_create_mode'],
                                                   default='0744'),
            sambaCscPolicy                  = dict(type='str',
                                                   aliases=['samba_csc_policy'],
                                                   default='manual'),
            sambaCustomSettings             = dict(type='list',
                                                   aliases=['samba_custom_settings'],
                                                   default=[]),
            sambaDirectoryMode              = dict(type='str',
                                                   aliases=['samba_directory_mode'],
                                                   default='0755'),
            sambaDirectorySecurityMode      = dict(type='str',
                                                   aliases=['samba_directory_security_mode'],
                                                   default='0777'),
            sambaDosFilemode                = dict(type='bool',
                                                   aliases=['samba_dos_filemode'],
                                                   default=False),
            sambaFakeOplocks                = dict(type='bool',
                                                   aliases=['samba_fake_oplocks'],
                                                   default=False),
            sambaForceCreateMode            = dict(type='bool',
                                                   aliases=['samba_force_create_mode'],
                                                   default=False),
            sambaForceDirectoryMode         = dict(type='bool',
                                                   aliases=['samba_force_directory_mode'],
                                                   default=False),
            sambaForceDirectorySecurityMode = dict(type='bool',
                                                   aliases=['samba_force_directory_security_mode'],
                                                   default=False),
            sambaForceGroup                 = dict(type='str',
                                                   aliases=['samba_force_group'],
                                                   default=None),
            sambaForceSecurityMode          = dict(type='bool',
                                                   aliases=['samba_force_security_mode'],
                                                   default=False),
            sambaForceUser                  = dict(type='str',
                                                   aliases=['samba_force_user'],
                                                   default=None),
            sambaHideFiles                  = dict(type='str',
                                                   aliases=['samba_hide_files'],
                                                   default=None),
            sambaHideUnreadable             = dict(type='bool',
                                                   aliases=['samba_hide_unreadable'],
                                                   default=False),
            sambaHostsAllow                 = dict(type='list',
                                                   aliases=['samba_hosts_allow'],
                                                   default=[]),
            sambaHostsDeny                  = dict(type='list',
                                                   aliases=['samba_hosts_deny'],
                                                   default=[]),
            sambaInheritAcls                = dict(type='bool',
                                                   aliases=['samba_inherit_acls'],
                                                   default=True),
            sambaInheritOwner               = dict(type='bool',
                                                   aliases=['samba_inherit_owner'],
                                                   default=False),
            sambaInheritPermissions         = dict(type='bool',
                                                   aliases=['samba_inherit_permissions'],
                                                   default=False),
            sambaInvalidUsers               = dict(type='str',
                                                   aliases=['samba_invalid_users'],
                                                   default=None),
            sambaLevel2Oplocks              = dict(type='bool',
                                                   aliases=['samba_level_2_oplocks'],
                                                   default=True),
            sambaLocking                    = dict(type='bool',
                                                   aliases=['samba_locking'],
                                                   default=True),
            sambaMSDFSRoot                  = dict(type='bool',
                                                   aliases=['samba_msdfs_root'],
                                                   default=False),
            sambaName                       = dict(type='str',
                                                   aliases=['samba_name'],
                                                   default=None),
            sambaNtAclSupport               = dict(type='bool',
                                                   aliases=['samba_nt_acl_support'],
                                                   default=True),
            sambaOplocks                    = dict(type='bool',
                                                   aliases=['samba_oplocks'],
                                                   default=True),
            sambaPostexec                   = dict(type='str',
                                                   aliases=['samba_postexec'],
                                                   default=None),
            sambaPreexec                    = dict(type='str',
                                                   aliases=['samba_preexec'],
                                                   default=None),
            sambaPublic                     = dict(type='bool',
                                                   aliases=['samba_public'],
                                                   default=False),
            sambaSecurityMode               = dict(type='str',
                                                   aliases=['samba_security_mode'],
                                                   default='0777'),
            sambaStrictLocking              = dict(type='str',
                                                   aliases=['samba_strict_locking'],
                                                   default='Auto'),
            sambaVFSObjects                 = dict(type='str',
                                                   aliases=['samba_vfs_objects'],
                                                   default=None),
            sambaValidUsers                 = dict(type='str',
                                                   aliases=['samba_valid_users'],
                                                   default=None),
            sambaWriteList                  = dict(type='str',
                                                   aliases=['samba_write_list'],
                                                   default=None),
            sambaWriteable                  = dict(type='bool',
                                                   aliases=['samba_writeable'],
                                                   default=True),
            nfs_hosts                       = dict(type='list',
                                                   default=[]),
            nfsCustomSettings               = dict(type='list',
                                                   aliases=['nfs_custom_settings'],
                                                   default=[]),
            state                           = dict(default='present',
                                                   choices=['present', 'absent'],
                                                   type='str')
        ),
        supports_check_mode=True,
        required_if = ([
            ('state', 'present', ['path', 'host', 'sambaName'])
        ])
    )
    name    = module.params['name']
    state   = module.params['state']
    changed = False

    obj = list(ldap_search(
        '(&(objectClass=univentionShare)(cn={}))'.format(name),
        attr=['cn']
    ))

    exists = bool(len(obj))
    container = 'cn=shares,ou={},{}'.format(module.params['ou'], base_dn())
    dn = 'cn={},{}'.format(name, container)

    if state == 'present':
        try:
            if not exists:
                obj = umc_module_for_add('shares/share', container)
            else:
                obj = umc_module_for_edit('shares/share', dn)

            module.params['printablename'] = '{} ({})'.format(name, module.params['host'])
            for k in obj.keys():
                if module.params[k] is True:
                    module.params[k] = '1'
                elif module.params[k] is False:
                    module.params[k] = '0'
                obj[k] = module.params[k]

            diff = obj.diff()
            if exists:
                for k in obj.keys():
                    if obj.hasChanged(k):
                        changed = True
            else:
                changed = True
            if not module.check_mode:
                if not exists:
                    obj.create()
                elif changed:
                    obj.modify()
        except BaseException as err:
            module.fail_json(
                msg='Creating/editing share {} in {} failed: {}'.format(
                    name,
                    container,
                    err,
                )
            )

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('shares/share', dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except BaseException as err:
            module.fail_json(
                msg='Removing share {} in {} failed: {}'.format(
                    name,
                    container,
                    err,
                )
            )

    module.exit_json(
        changed=changed,
        name=name,
        diff=diff,
        container=container
    )
Exemplo n.º 2
0
def main():
    module = AnsibleModule(
        argument_spec = dict(
            type        = dict(required=True,
                               type='str'),
            zone        = dict(required=True,
                               type='str'),
            name        = dict(required=True,
                               type='str'),
            data        = dict(default=[],
                               type='dict'),
            state       = dict(default='present',
                               choices=['present', 'absent'],
                               type='str')
        ),
        supports_check_mode=True,
        required_if = ([
            ('state', 'present', ['data'])
        ])
    )
    type        = module.params['type']
    zone        = module.params['zone']
    name        = module.params['name']
    data        = module.params['data']
    state       = module.params['state']
    changed     = False

    obj = list(ldap_search(
        '(&(objectClass=dNSZone)(zoneName={})(relativeDomainName={}))'.format(zone, name),
        attr=['dNSZone']
    ))

    exists = bool(len(obj))
    container = 'zoneName={},cn=dns,{}'.format(zone, base_dn())
    dn = 'relativeDomainName={},{}'.format(name, container)

    if state == 'present':
        try:
            if not exists:
                so = forward_zone.lookup(
                    config(),
                    uldap(),
                    '(zone={})'.format(zone),
                    scope='domain',
                ) or reverse_zone.lookup(
                    config(),
                    uldap(),
                    '(zone={})'.format(zone),
                    scope='domain',
                )
                obj = umc_module_for_add('dns/{}'.format(type), container, superordinate=so[0])
            else:
                obj = umc_module_for_edit('dns/{}'.format(type), dn)
            obj['name'] = name
            for k, v in data.items():
                obj[k] = v
            diff = obj.diff()
            changed = obj.diff() != []
            if not module.check_mode:
                if not exists:
                    obj.create()
                else:
                    obj.modify()
        except BaseException as e:
            module.fail_json(
                msg='Creating/editing dns entry {} in {} failed: {}'.format(name, container, e)
            )

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('dns/{}'.format(type), dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except BaseException as e:
            module.fail_json(
                msg='Removing dns entry {} in {} failed: {}'.format(name, container, e)
            )

    module.exit_json(
        changed=changed,
        name=name,
        diff=diff,
        container=container
    )
Exemplo n.º 3
0
def main():
    module = AnsibleModule(
        argument_spec = dict(
            name        = dict(required=True,
                               type='str'),
            description = dict(default=None,
                               type='str'),
            position    = dict(default='',
                               type='str'),
            ou          = dict(default='',
                               type='str'),
            subpath     = dict(default='cn=groups',
                               type='str'),
            state       = dict(default='present',
                               choices=['present', 'absent'],
                               type='str')
        ),
        supports_check_mode=True
    )
    name        = module.params['name']
    description = module.params['description']
    position    = module.params['position']
    ou          = module.params['ou']
    subpath     = module.params['subpath']
    state       = module.params['state']
    changed     = False

    groups = list(ldap_search(
        '(&(objectClass=posixGroup)(cn={}))'.format(name),
        attr=['cn']
    ))
    if position != '':
        container = position
    else:
        if ou != '':
            ou = 'ou={},'.format(ou)
        if subpath != '':
            subpath = '{},'.format(subpath)
        container = '{}{}{}'.format(subpath, ou, base_dn())
    group_dn = 'cn={},{}'.format(name, container)

    exists = bool(len(groups))

    if state == 'present':
        try:
            if not exists:
                grp = umc_module_for_add('groups/group', container)
            else:
                grp = umc_module_for_edit('groups/group', group_dn)
            grp['name']         = name
            grp['description']  = description
            diff = grp.diff()
            changed = grp.diff() != []
            if not module.check_mode:
                if not exists:
                    grp.create()
                else:
                    grp.modify()
        except:
            module.fail_json(
                msg="Creating/editing group {} in {} failed".format(name, container)
            )

    if state == 'absent' and exists:
        try:
            grp = umc_module_for_edit('groups/group', group_dn)
            if not module.check_mode:
                grp.remove()
            changed = True
        except:
            module.fail_json(
                msg="Removing group {} failed".format(name)
            )

    module.exit_json(
        changed=changed,
        name=name,
        diff=diff,
        container=container
    )
Exemplo n.º 4
0
def main():
    module = AnsibleModule(argument_spec=dict(
        name=dict(required=True, type='str'),
        description=dict(default=None, type='str'),
        position=dict(default='', type='str'),
        ou=dict(default='', type='str'),
        subpath=dict(default='cn=groups', type='str'),
        state=dict(default='present',
                   choices=['present', 'absent'],
                   type='str')),
                           supports_check_mode=True)
    name = module.params['name']
    description = module.params['description']
    position = module.params['position']
    ou = module.params['ou']
    subpath = module.params['subpath']
    state = module.params['state']
    changed = False

    groups = list(
        ldap_search('(&(objectClass=posixGroup)(cn={}))'.format(name),
                    attr=['cn']))
    if position != '':
        container = position
    else:
        if ou != '':
            ou = 'ou={},'.format(ou)
        if subpath != '':
            subpath = '{},'.format(subpath)
        container = '{}{}{}'.format(subpath, ou, base_dn())
    group_dn = 'cn={},{}'.format(name, container)

    exists = bool(len(groups))

    if state == 'present':
        try:
            if not exists:
                grp = umc_module_for_add('groups/group', container)
            else:
                grp = umc_module_for_edit('groups/group', group_dn)
            grp['name'] = name
            grp['description'] = description
            diff = grp.diff()
            changed = grp.diff() != []
            if not module.check_mode:
                if not exists:
                    grp.create()
                else:
                    grp.modify()
        except:
            module.fail_json(
                msg="Creating/editing group {} in {} failed".format(
                    name, container))

    if state == 'absent' and exists:
        try:
            grp = umc_module_for_edit('groups/group', group_dn)
            if not module.check_mode:
                grp.remove()
            changed = True
        except:
            module.fail_json(msg="Removing group {} failed".format(name))

    module.exit_json(changed=changed,
                     name=name,
                     diff=diff,
                     container=container)
Exemplo n.º 5
0
def main():
    module = AnsibleModule(
        argument_spec=dict(type=dict(required=True, type='str'),
                           zone=dict(required=True,
                                     aliases=['name'],
                                     type='str'),
                           nameserver=dict(default=[], type='list'),
                           interfaces=dict(default=[], type='list'),
                           refresh=dict(default=3600, type='int'),
                           retry=dict(default=1800, type='int'),
                           expire=dict(default=604800, type='int'),
                           ttl=dict(default=600, type='int'),
                           contact=dict(default='', type='str'),
                           mx=dict(default=[], type='list'),
                           state=dict(default='present',
                                      choices=['present', 'absent'],
                                      type='str')),
        supports_check_mode=True,
        required_if=([('state', 'present', ['nameserver', 'interfaces'])]))
    type = module.params['type']
    zone = module.params['zone']
    nameserver = module.params['nameserver']
    interfaces = module.params['interfaces']
    refresh = module.params['refresh']
    retry = module.params['retry']
    expire = module.params['expire']
    ttl = module.params['ttl']
    contact = module.params['contact']
    mx = module.params['mx']
    state = module.params['state']
    changed = False

    obj = list(
        ldap_search('(&(objectClass=dNSZone)(zoneName={}))'.format(zone),
                    attr=['dNSZone']))

    exists = bool(len(obj))
    container = 'cn=dns,{}'.format(base_dn())
    dn = 'zoneName={},{}'.format(zone, container)
    if contact == '':
        contact = 'root@{}.'.format(zone)

    if state == 'present':
        try:
            if not exists:
                obj = umc_module_for_add('dns/{}'.format(type), container)
            else:
                obj = umc_module_for_edit('dns/{}'.format(type), dn)
            obj['zone'] = zone
            obj['nameserver'] = nameserver
            obj['a'] = interfaces
            obj['refresh'] = convert_time(refresh)
            obj['retry'] = convert_time(retry)
            obj['expire'] = convert_time(expire)
            obj['ttl'] = convert_time(ttl)
            obj['contact'] = contact
            obj['mx'] = mx
            diff = obj.diff()
            if exists:
                for k in obj.keys():
                    if obj.hasChanged(k):
                        changed = True
            else:
                changed = True
            if not module.check_mode:
                if not exists:
                    obj.create()
                elif changed:
                    obj.modify()
        except Exception as e:
            module.fail_json(
                msg='Creating/editing dns zone {} failed: {}'.format(zone, e))

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('dns/{}'.format(type), dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except Exception as e:
            module.fail_json(
                msg='Removing dns zone {} failed: {}'.format(zone, e))

    module.exit_json(changed=changed, diff=diff, zone=zone)
Exemplo n.º 6
0
def main():
    module = AnsibleModule(
        argument_spec = dict(
            type        = dict(required=True,
                               type='str'),
            zone        = dict(required=True,
                               aliases=['name'],
                               type='str'),
            nameserver  = dict(default=[],
                               type='list'),
            interfaces  = dict(default=[],
                               type='list'),
            refresh     = dict(default=3600,
                               type='int'),
            retry       = dict(default=1800,
                               type='int'),
            expire      = dict(default=604800,
                               type='int'),
            ttl         = dict(default=600,
                               type='int'),
            contact     = dict(default='',
                               type='str'),
            mx          = dict(default=[],
                               type='list'),
            state       = dict(default='present',
                               choices=['present', 'absent'],
                               type='str')
        ),
        supports_check_mode=True,
        required_if = ([
            ('state', 'present', ['nameserver', 'interfaces'])
        ])
    )
    type        = module.params['type']
    zone        = module.params['zone']
    nameserver  = module.params['nameserver']
    interfaces  = module.params['interfaces']
    refresh     = module.params['refresh']
    retry       = module.params['retry']
    expire      = module.params['expire']
    ttl         = module.params['ttl']
    contact     = module.params['contact']
    mx          = module.params['mx']
    state       = module.params['state']
    changed     = False

    obj = list(ldap_search(
        '(&(objectClass=dNSZone)(zoneName={}))'.format(zone),
        attr=['dNSZone']
    ))

    exists = bool(len(obj))
    container = 'cn=dns,{}'.format(base_dn())
    dn = 'zoneName={},{}'.format(zone, container)
    if contact == '':
        contact = 'root@{}.'.format(zone)

    if state == 'present':
        try:
            if not exists:
                obj = umc_module_for_add('dns/{}'.format(type), container)
            else:
                obj = umc_module_for_edit('dns/{}'.format(type), dn)
            obj['zone']         = zone
            obj['nameserver']   = nameserver
            obj['a']            = interfaces
            obj['refresh']      = convert_time(refresh)
            obj['retry']        = convert_time(retry)
            obj['expire']       = convert_time(expire)
            obj['ttl']          = convert_time(ttl)
            obj['contact']      = contact
            obj['mx']           = mx
            diff = obj.diff()
            if exists:
                for k in obj.keys():
                    if obj.hasChanged(k):
                        changed = True
            else:
                changed = True
            if not module.check_mode:
                if not exists:
                    obj.create()
                elif changed:
                    obj.modify()
        except Exception as e:
            module.fail_json(
                msg='Creating/editing dns zone {} failed: {}'.format(zone, e)
            )

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('dns/{}'.format(type), dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except Exception as e:
            module.fail_json(
                msg='Removing dns zone {} failed: {}'.format(zone, e)
            )

    module.exit_json(
        changed=changed,
        diff=diff,
        zone=zone
    )
def main():
    module = AnsibleModule(argument_spec=dict(
        type=dict(required=True, type='str'),
        zone=dict(required=True, type='str'),
        name=dict(required=True, type='str'),
        data=dict(default=[], type='dict'),
        state=dict(default='present',
                   choices=['present', 'absent'],
                   type='str')),
                           supports_check_mode=True,
                           required_if=([('state', 'present', ['data'])]))

    if not HAVE_UNIVENTION:
        module.fail_json(msg="This module requires univention python bindings")

    type = module.params['type']
    zone = module.params['zone']
    name = module.params['name']
    data = module.params['data']
    state = module.params['state']
    changed = False

    obj = list(
        ldap_search(
            '(&(objectClass=dNSZone)(zoneName={})(relativeDomainName={}))'.
            format(zone, name),
            attr=['dNSZone']))

    exists = bool(len(obj))
    container = 'zoneName={},cn=dns,{}'.format(zone, base_dn())
    dn = 'relativeDomainName={},{}'.format(name, container)

    if state == 'present':
        try:
            if not exists:
                so = forward_zone.lookup(
                    config(),
                    uldap(),
                    '(zone={})'.format(zone),
                    scope='domain',
                ) or reverse_zone.lookup(
                    config(),
                    uldap(),
                    '(zone={})'.format(zone),
                    scope='domain',
                )
                obj = umc_module_for_add('dns/{}'.format(type),
                                         container,
                                         superordinate=so[0])
            else:
                obj = umc_module_for_edit('dns/{}'.format(type), dn)
            obj['name'] = name
            for k, v in data.items():
                obj[k] = v
            diff = obj.diff()
            changed = obj.diff() != []
            if not module.check_mode:
                if not exists:
                    obj.create()
                else:
                    obj.modify()
        except BaseException as e:
            module.fail_json(
                msg='Creating/editing dns entry {} in {} failed: {}'.format(
                    name, container, e))

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('dns/{}'.format(type), dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except BaseException as e:
            module.fail_json(
                msg='Removing dns entry {} in {} failed: {}'.format(
                    name, container, e))

    module.exit_json(changed=changed,
                     name=name,
                     diff=diff,
                     container=container)
Exemplo n.º 8
0
def main():
    expiry = date.strftime(date.today() + timedelta(days=365), "%Y-%m-%d")
    module = AnsibleModule(
        argument_spec=dict(
            birthday=dict(default=None,
                          type='str'),
            city=dict(default=None,
                      type='str'),
            country=dict(default=None,
                         type='str'),
            department_number=dict(default=None,
                                   type='str',
                                   aliases=['departmentNumber']),
            description=dict(default=None,
                             type='str'),
            display_name=dict(default=None,
                              type='str',
                              aliases=['displayName']),
            email=dict(default=[''],
                       type='list'),
            employee_number=dict(default=None,
                                 type='str',
                                 aliases=['employeeNumber']),
            employee_type=dict(default=None,
                               type='str',
                               aliases=['employeeType']),
            firstname=dict(default=None,
                           type='str'),
            gecos=dict(default=None,
                       type='str'),
            groups=dict(default=[],
                        type='list'),
            home_share=dict(default=None,
                            type='str',
                            aliases=['homeShare']),
            home_share_path=dict(default=None,
                                 type='str',
                                 aliases=['homeSharePath']),
            home_telephone_number=dict(default=[],
                                       type='list',
                                       aliases=['homeTelephoneNumber']),
            homedrive=dict(default=None,
                           type='str'),
            lastname=dict(default=None,
                          type='str'),
            mail_alternative_address=dict(default=[],
                                          type='list',
                                          aliases=['mailAlternativeAddress']),
            mail_home_server=dict(default=None,
                                  type='str',
                                  aliases=['mailHomeServer']),
            mail_primary_address=dict(default=None,
                                      type='str',
                                      aliases=['mailPrimaryAddress']),
            mobile_telephone_number=dict(default=[],
                                         type='list',
                                         aliases=['mobileTelephoneNumber']),
            organisation=dict(default=None,
                              type='str',
                              aliases=['organization']),
            overridePWHistory=dict(default=False,
                                   type='bool',
                                   aliases=['override_pw_history']),
            overridePWLength=dict(default=False,
                                  type='bool',
                                  aliases=['override_pw_length']),
            pager_telephonenumber=dict(default=[],
                                       type='list',
                                       aliases=['pagerTelephonenumber']),
            password=dict(default=None,
                          type='str',
                          no_log=True),
            phone=dict(default=[],
                       type='list'),
            postcode=dict(default=None,
                          type='str'),
            primary_group=dict(default=None,
                               type='str',
                               aliases=['primaryGroup']),
            profilepath=dict(default=None,
                             type='str'),
            pwd_change_next_login=dict(default=None,
                                       type='str',
                                       choices=['0', '1'],
                                       aliases=['pwdChangeNextLogin']),
            room_number=dict(default=None,
                             type='str',
                             aliases=['roomNumber']),
            samba_privileges=dict(default=[],
                                  type='list',
                                  aliases=['sambaPrivileges']),
            samba_user_workstations=dict(default=[],
                                         type='list',
                                         aliases=['sambaUserWorkstations']),
            sambahome=dict(default=None,
                           type='str'),
            scriptpath=dict(default=None,
                            type='str'),
            secretary=dict(default=[],
                           type='list'),
            serviceprovider=dict(default=[''],
                                 type='list'),
            shell=dict(default='/bin/bash',
                       type='str'),
            street=dict(default=None,
                        type='str'),
            title=dict(default=None,
                       type='str'),
            unixhome=dict(default=None,
                          type='str'),
            userexpiry=dict(default=expiry,
                            type='str'),
            username=dict(required=True,
                          aliases=['name'],
                          type='str'),
            position=dict(default='',
                          type='str'),
            update_password=dict(default='always',
                                 choices=['always', 'on_create'],
                                 type='str'),
            ou=dict(default='',
                    type='str'),
            subpath=dict(default='cn=users',
                         type='str'),
            state=dict(default='present',
                       choices=['present', 'absent'],
                       type='str')
        ),
        supports_check_mode=True,
        required_if=([
            ('state', 'present', ['firstname', 'lastname', 'password'])
        ])
    )
    username = module.params['username']
    position = module.params['position']
    ou = module.params['ou']
    subpath = module.params['subpath']
    state = module.params['state']
    changed = False

    users = list(ldap_search(
        '(&(objectClass=posixAccount)(uid={}))'.format(username),
        attr=['uid']
    ))
    if position != '':
        container = position
    else:
        if ou != '':
            ou = 'ou={},'.format(ou)
        if subpath != '':
            subpath = '{},'.format(subpath)
        container = '{}{}{}'.format(subpath, ou, base_dn())
    user_dn = 'uid={},{}'.format(username, container)

    exists = bool(len(users))

    if state == 'present':
        try:
            if not exists:
                obj = umc_module_for_add('users/user', container)
            else:
                obj = umc_module_for_edit('users/user', user_dn)

            if module.params['displayName'] is None:
                module.params['displayName'] = '{} {}'.format(
                    module.params['firstname'],
                    module.params['lastname']
                )
            if module.params['unixhome'] is None:
                module.params['unixhome'] = '/home/{}'.format(
                    module.params['username']
                )
            for k in obj.keys():
                if (k != 'password' and
                        k != 'groups' and
                        k != 'overridePWHistory' and
                        k in module.params and
                        module.params[k] is not None):
                    obj[k] = module.params[k]
            # handle some special values
            obj['e-mail'] = module.params['email']
            password = module.params['password']
            if obj['password'] is None:
                obj['password'] = password
            if module.params['update_password'] == 'always':
                old_password = obj['password'].split('}', 2)[1]
                if crypt.crypt(password, old_password) != old_password:
                    obj['overridePWHistory'] = module.params['overridePWHistory']
                    obj['overridePWLength'] = module.params['overridePWLength']
                    obj['password'] = password

            diff = obj.diff()
            if exists:
                for k in obj.keys():
                    if obj.hasChanged(k):
                        changed = True
            else:
                changed = True
            if not module.check_mode:
                if not exists:
                    obj.create()
                elif changed:
                    obj.modify()
        except Exception:
            module.fail_json(
                msg="Creating/editing user {} in {} failed".format(
                    username,
                    container
                )
            )
        try:
            groups = module.params['groups']
            if groups:
                filter = '(&(objectClass=posixGroup)(|(cn={})))'.format(
                    ')(cn='.join(groups)
                )
                group_dns = list(ldap_search(filter, attr=['dn']))
                for dn in group_dns:
                    grp = umc_module_for_edit('groups/group', dn[0])
                    if user_dn not in grp['users']:
                        grp['users'].append(user_dn)
                        if not module.check_mode:
                            grp.modify()
                        changed = True
        except Exception:
            module.fail_json(
                msg="Adding groups to user {} failed".format(username)
            )

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('users/user', user_dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except Exception:
            module.fail_json(
                msg="Removing user {} failed".format(username)
            )

    module.exit_json(
        changed=changed,
        username=username,
        diff=diff,
        container=container
    )
Exemplo n.º 9
0
def main():
    module = AnsibleModule(argument_spec=dict(
        name=dict(required=True, type='str'),
        ou=dict(required=True, type='str'),
        owner=dict(type='str', default='0'),
        group=dict(type='str', default='0'),
        path=dict(type='path', default=None),
        directorymode=dict(type='str', default='00755'),
        host=dict(type='str', default=None),
        root_squash=dict(type='bool', default=True),
        subtree_checking=dict(type='bool', default=True),
        sync=dict(type='str', default='sync'),
        writeable=dict(type='bool', default=True),
        sambaBlockSize=dict(type='str',
                            aliases=['samba_block_size'],
                            default=None),
        sambaBlockingLocks=dict(type='bool',
                                aliases=['samba_blocking_locks'],
                                default=True),
        sambaBrowseable=dict(type='bool',
                             aliases=['samba_browsable'],
                             default=True),
        sambaCreateMode=dict(type='str',
                             aliases=['samba_create_mode'],
                             default='0744'),
        sambaCscPolicy=dict(type='str',
                            aliases=['samba_csc_policy'],
                            default='manual'),
        sambaCustomSettings=dict(type='list',
                                 aliases=['samba_custom_settings'],
                                 default=[]),
        sambaDirectoryMode=dict(type='str',
                                aliases=['samba_directory_mode'],
                                default='0755'),
        sambaDirectorySecurityMode=dict(
            type='str',
            aliases=['samba_directory_security_mode'],
            default='0777'),
        sambaDosFilemode=dict(type='bool',
                              aliases=['samba_dos_filemode'],
                              default=False),
        sambaFakeOplocks=dict(type='bool',
                              aliases=['samba_fake_oplocks'],
                              default=False),
        sambaForceCreateMode=dict(type='bool',
                                  aliases=['samba_force_create_mode'],
                                  default=False),
        sambaForceDirectoryMode=dict(type='bool',
                                     aliases=['samba_force_directory_mode'],
                                     default=False),
        sambaForceDirectorySecurityMode=dict(
            type='bool',
            aliases=['samba_force_directory_security_mode'],
            default=False),
        sambaForceGroup=dict(type='str',
                             aliases=['samba_force_group'],
                             default=None),
        sambaForceSecurityMode=dict(type='bool',
                                    aliases=['samba_force_security_mode'],
                                    default=False),
        sambaForceUser=dict(type='str',
                            aliases=['samba_force_user'],
                            default=None),
        sambaHideFiles=dict(type='str',
                            aliases=['samba_hide_files'],
                            default=None),
        sambaHideUnreadable=dict(type='bool',
                                 aliases=['samba_hide_unreadable'],
                                 default=False),
        sambaHostsAllow=dict(type='list',
                             aliases=['samba_hosts_allow'],
                             default=[]),
        sambaHostsDeny=dict(type='list',
                            aliases=['samba_hosts_deny'],
                            default=[]),
        sambaInheritAcls=dict(type='bool',
                              aliases=['samba_inherit_acls'],
                              default=True),
        sambaInheritOwner=dict(type='bool',
                               aliases=['samba_inherit_owner'],
                               default=False),
        sambaInheritPermissions=dict(type='bool',
                                     aliases=['samba_inherit_permissions'],
                                     default=False),
        sambaInvalidUsers=dict(type='str',
                               aliases=['samba_invalid_users'],
                               default=None),
        sambaLevel2Oplocks=dict(type='bool',
                                aliases=['samba_level_2_oplocks'],
                                default=True),
        sambaLocking=dict(type='bool', aliases=['samba_locking'],
                          default=True),
        sambaMSDFSRoot=dict(type='bool',
                            aliases=['samba_msdfs_root'],
                            default=False),
        sambaName=dict(type='str', aliases=['samba_name'], default=None),
        sambaNtAclSupport=dict(type='bool',
                               aliases=['samba_nt_acl_support'],
                               default=True),
        sambaOplocks=dict(type='bool', aliases=['samba_oplocks'],
                          default=True),
        sambaPostexec=dict(type='str',
                           aliases=['samba_postexec'],
                           default=None),
        sambaPreexec=dict(type='str', aliases=['samba_preexec'], default=None),
        sambaPublic=dict(type='bool', aliases=['samba_public'], default=False),
        sambaSecurityMode=dict(type='str',
                               aliases=['samba_security_mode'],
                               default='0777'),
        sambaStrictLocking=dict(type='str',
                                aliases=['samba_strict_locking'],
                                default='Auto'),
        sambaVFSObjects=dict(type='str',
                             aliases=['samba_vfs_objects'],
                             default=None),
        sambaValidUsers=dict(type='str',
                             aliases=['samba_valid_users'],
                             default=None),
        sambaWriteList=dict(type='str',
                            aliases=['samba_write_list'],
                            default=None),
        sambaWriteable=dict(type='bool',
                            aliases=['samba_writeable'],
                            default=True),
        nfs_hosts=dict(type='list', default=[]),
        nfsCustomSettings=dict(type='list',
                               aliases=['nfs_custom_settings'],
                               default=[]),
        state=dict(default='present',
                   choices=['present', 'absent'],
                   type='str')),
                           supports_check_mode=True,
                           required_if=([('state', 'present',
                                          ['path', 'host', 'sambaName'])]))
    name = module.params['name']
    state = module.params['state']
    changed = False

    obj = list(
        ldap_search('(&(objectClass=univentionShare)(cn={0}))'.format(name),
                    attr=['cn']))

    exists = bool(len(obj))
    container = 'cn=shares,ou={0},{1}'.format(module.params['ou'], base_dn())
    dn = 'cn={0},{1}'.format(name, container)

    if state == 'present':
        try:
            if not exists:
                obj = umc_module_for_add('shares/share', container)
            else:
                obj = umc_module_for_edit('shares/share', dn)

            module.params['printablename'] = '{0} ({1})'.format(
                name, module.params['host'])
            for k in obj.keys():
                if module.params[k] is True:
                    module.params[k] = '1'
                elif module.params[k] is False:
                    module.params[k] = '0'
                obj[k] = module.params[k]

            diff = obj.diff()
            if exists:
                for k in obj.keys():
                    if obj.hasChanged(k):
                        changed = True
            else:
                changed = True
            if not module.check_mode:
                if not exists:
                    obj.create()
                elif changed:
                    obj.modify()
        except Exception as err:
            module.fail_json(
                msg='Creating/editing share {0} in {1} failed: {2}'.format(
                    name,
                    container,
                    err,
                ))

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('shares/share', dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except Exception as err:
            module.fail_json(
                msg='Removing share {0} in {1} failed: {2}'.format(
                    name,
                    container,
                    err,
                ))

    module.exit_json(changed=changed,
                     name=name,
                     diff=diff,
                     container=container)
Exemplo n.º 10
0
def main():
    expiry = date.strftime(date.today() + timedelta(days=365), "%Y-%m-%d")
    module = AnsibleModule(
        argument_spec=dict(
            birthday=dict(default=None,
                          type='str'),
            city=dict(default=None,
                      type='str'),
            country=dict(default=None,
                         type='str'),
            department_number=dict(default=None,
                                   type='str',
                                   aliases=['departmentNumber']),
            description=dict(default=None,
                             type='str'),
            display_name=dict(default=None,
                              type='str',
                              aliases=['displayName']),
            email=dict(default=[''],
                       type='list'),
            employee_number=dict(default=None,
                                 type='str',
                                 aliases=['employeeNumber']),
            employee_type=dict(default=None,
                               type='str',
                               aliases=['employeeType']),
            firstname=dict(default=None,
                           type='str'),
            gecos=dict(default=None,
                       type='str'),
            groups=dict(default=[],
                        type='list'),
            home_share=dict(default=None,
                            type='str',
                            aliases=['homeShare']),
            home_share_path=dict(default=None,
                                 type='str',
                                 aliases=['homeSharePath']),
            home_telephone_number=dict(default=[],
                                       type='list',
                                       aliases=['homeTelephoneNumber']),
            homedrive=dict(default=None,
                           type='str'),
            lastname=dict(default=None,
                          type='str'),
            mail_alternative_address=dict(default=[],
                                          type='list',
                                          aliases=['mailAlternativeAddress']),
            mail_home_server=dict(default=None,
                                  type='str',
                                  aliases=['mailHomeServer']),
            mail_primary_address=dict(default=None,
                                      type='str',
                                      aliases=['mailPrimaryAddress']),
            mobile_telephone_number=dict(default=[],
                                         type='list',
                                         aliases=['mobileTelephoneNumber']),
            organisation=dict(default=None,
                              type='str'),
            overridePWHistory=dict(default=False,
                                   type='bool',
                                   aliases=['override_pw_history']),
            overridePWLength=dict(default=False,
                                  type='bool',
                                  aliases=['override_pw_length']),
            pager_telephonenumber=dict(default=[],
                                       type='list',
                                       aliases=['pagerTelephonenumber']),
            password=dict(default=None,
                          type='str',
                          no_log=True),
            phone=dict(default=[],
                       type='list'),
            postcode=dict(default=None,
                          type='str'),
            primary_group=dict(default=None,
                               type='str',
                               aliases=['primaryGroup']),
            profilepath=dict(default=None,
                             type='str'),
            pwd_change_next_login=dict(default=None,
                                       type='str',
                                       choices=['0', '1'],
                                       aliases=['pwdChangeNextLogin']),
            room_number=dict(default=None,
                             type='str',
                             aliases=['roomNumber']),
            samba_privileges=dict(default=[],
                                  type='list',
                                  aliases=['sambaPrivileges']),
            samba_user_workstations=dict(default=[],
                                         type='list',
                                         aliases=['sambaUserWorkstations']),
            sambahome=dict(default=None,
                           type='str'),
            scriptpath=dict(default=None,
                            type='str'),
            secretary=dict(default=[],
                           type='list'),
            serviceprovider=dict(default=[''],
                                 type='list'),
            shell=dict(default='/bin/bash',
                       type='str'),
            street=dict(default=None,
                        type='str'),
            title=dict(default=None,
                       type='str'),
            unixhome=dict(default=None,
                          type='str'),
            userexpiry=dict(default=expiry,
                            type='str'),
            username=dict(required=True,
                          aliases=['name'],
                          type='str'),
            position=dict(default='',
                          type='str'),
            update_password=dict(default='always',
                                 choices=['always', 'on_create'],
                                 type='str'),
            ou=dict(default='',
                    type='str'),
            subpath=dict(default='cn=users',
                         type='str'),
            state=dict(default='present',
                       choices=['present', 'absent'],
                       type='str')
        ),
        supports_check_mode=True,
        required_if=([
            ('state', 'present', ['firstname', 'lastname', 'password'])
        ])
    )
    username = module.params['username']
    position = module.params['position']
    ou = module.params['ou']
    subpath = module.params['subpath']
    state = module.params['state']
    changed = False

    users = list(ldap_search(
        '(&(objectClass=posixAccount)(uid={}))'.format(username),
        attr=['uid']
    ))
    if position != '':
        container = position
    else:
        if ou != '':
            ou = 'ou={},'.format(ou)
        if subpath != '':
            subpath = '{},'.format(subpath)
        container = '{}{}{}'.format(subpath, ou, base_dn())
    user_dn = 'uid={},{}'.format(username, container)

    exists = bool(len(users))

    if state == 'present':
        try:
            if not exists:
                obj = umc_module_for_add('users/user', container)
            else:
                obj = umc_module_for_edit('users/user', user_dn)

            if module.params['displayName'] is None:
                module.params['displayName'] = '{} {}'.format(
                    module.params['firstname'],
                    module.params['lastname']
                )
            if module.params['unixhome'] is None:
                module.params['unixhome'] = '/home/{}'.format(
                    module.params['username']
                )
            for k in obj.keys():
                if (k != 'password' and
                        k != 'groups' and
                        k != 'overridePWHistory' and
                        k in module.params and
                        module.params[k] is not None):
                    obj[k] = module.params[k]
            # handle some special values
            obj['e-mail'] = module.params['email']
            password = module.params['password']
            if obj['password'] is None:
                obj['password'] = password
            if module.params['update_password'] == 'always':
                old_password = obj['password'].split('}', 2)[1]
                if crypt.crypt(password, old_password) != old_password:
                    obj['overridePWHistory'] = module.params['overridePWHistory']
                    obj['overridePWLength'] = module.params['overridePWLength']
                    obj['password'] = password

            diff = obj.diff()
            if exists:
                for k in obj.keys():
                    if obj.hasChanged(k):
                        changed = True
            else:
                changed = True
            if not module.check_mode:
                if not exists:
                    obj.create()
                elif changed:
                    obj.modify()
        except:
            module.fail_json(
                msg="Creating/editing user {} in {} failed".format(
                    username,
                    container
                )
            )
        try:
            groups = module.params['groups']
            if groups:
                filter = '(&(objectClass=posixGroup)(|(cn={})))'.format(
                    ')(cn='.join(groups)
                )
                group_dns = list(ldap_search(filter, attr=['dn']))
                for dn in group_dns:
                    grp = umc_module_for_edit('groups/group', dn[0])
                    if user_dn not in grp['users']:
                        grp['users'].append(user_dn)
                        if not module.check_mode:
                            grp.modify()
                        changed = True
        except:
            module.fail_json(
                msg="Adding groups to user {} failed".format(username)
            )

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('users/user', user_dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except:
            module.fail_json(
                msg="Removing user {} failed".format(username)
            )

    module.exit_json(
        changed=changed,
        username=username,
        diff=diff,
        container=container
    )