Exemple #1
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(type='str', default='127.0.0.1'),
            port=dict(type='int'),
            username=dict(type='str', default='cobbler'),
            password=dict(type='str', no_log=True),
            use_ssl=dict(type='bool', default=True),
            validate_certs=dict(type='bool', default=True),
        ),
        supports_check_mode=True,
    )

    username = module.params['username']
    password = module.params['password']
    port = module.params['port']
    use_ssl = module.params['use_ssl']
    validate_certs = module.params['validate_certs']

    module.params['proto'] = 'https' if use_ssl else 'http'
    if not port:
        module.params['port'] = '443' if use_ssl else '80'

    result = dict(
        changed=True,
    )

    start = datetime.datetime.utcnow()

    ssl_context = None
    if not validate_certs:
        try:  # Python 2.7.9 and newer
            ssl_context = ssl.create_unverified_context()
        except AttributeError:  # Legacy Python that doesn't verify HTTPS certificates by default
            ssl._create_default_context = ssl._create_unverified_context
        else:  # Python 2.7.8 and older
            ssl._create_default_https_context = ssl._create_unverified_https_context

    url = '{proto}://{host}:{port}/cobbler_api'.format(**module.params)
    if ssl_context:
        conn = xmlrpc_client.ServerProxy(url, context=ssl_context)
    else:
        conn = xmlrpc_client.Server(url)

    try:
        token = conn.login(username, password)
    except xmlrpc_client.Fault as e:
        module.fail_json(msg="Failed to log in to Cobbler '{url}' as '{username}'. {error}".format(url=url, error=to_text(e), **module.params))
    except Exception as e:
        module.fail_json(msg="Connection to '{url}' failed. {error}".format(url=url, error=to_text(e)))

    if not module.check_mode:
        try:
            conn.sync(token)
        except Exception as e:
            module.fail_json(msg="Failed to sync Cobbler. {error}".format(error=to_text(e)))

    elapsed = datetime.datetime.utcnow() - start
    module.exit_json(elapsed=elapsed.seconds, **result)
def spacewalk_connect(saturl=None, password=None, user=None):
    sw_conn = dict()
    if password is None or saturl is None or user is None:
        raise AnsibleError('password, saturl and user are required values')
    try:
        sw_conn['client'] = xmlrpc_client.Server(saturl)
        sw_conn['session'] = sw_conn['client'].auth.login(user, password)
    except Exception as e:
        raise AnsibleError(
            'Unable to login to spacwalk/satellite server: {}'.format(str(e)))

    return sw_conn
Exemple #3
0
def main():

    module = AnsibleModule(argument_spec=dict(
        state=dict(
            type='str', default='present', choices=['present', 'absent']),
        name=dict(type='str', required=True),
        sysname=dict(type='str', required=True),
        url=dict(type='str', required=True),
        user=dict(type='str', required=True),
        password=dict(type='str', required=True, aliases=['pwd'], no_log=True),
    ))

    state = module.params['state']
    channelname = module.params['name']
    systname = module.params['sysname']
    saturl = module.params['url']
    user = module.params['user']
    password = module.params['password']

    # initialize connection
    client = xmlrpc_client.Server(saturl)
    session = client.auth.login(user, password)

    # get systemid
    sys_id = get_systemid(client, session, systname)

    # get channels for system
    chans = base_channels(client, session, sys_id)

    try:
        if state == 'present':
            if channelname in chans:
                module.exit_json(changed=False,
                                 msg="Channel %s already exists" % channelname)
            else:
                subscribe_channels(channelname, client, session, systname,
                                   sys_id)
                module.exit_json(changed=True,
                                 msg="Channel %s added" % channelname)

        if state == 'absent':
            if channelname not in chans:
                module.exit_json(changed=False,
                                 msg="Not subscribed to channel %s." %
                                 channelname)
            else:
                unsubscribe_channels(channelname, client, session, systname,
                                     sys_id)
                module.exit_json(changed=True,
                                 msg="Channel %s removed" % channelname)
    finally:
        client.auth.logout(session)
def main():

    module = AnsibleModule(argument_spec=dict(
        state=dict(
            type='str', default='present', choices=['present', 'absent']),
        name=dict(type='str', required=True),
        sysname=dict(type='str', required=True),
        url=dict(type='str', required=True),
        user=dict(type='str', required=True),
        password=dict(type='str', required=True, aliases=['pwd'], no_log=True),
        validate_certs=dict(type='bool', default=True),
    ))

    state = module.params['state']
    channelname = module.params['name']
    systname = module.params['sysname']
    saturl = module.params['url']
    user = module.params['user']
    password = module.params['password']
    validate_certs = module.params['validate_certs']

    ssl_context = None
    if not validate_certs:
        try:  # Python 2.7.9 and newer
            ssl_context = ssl.create_unverified_context()
        except AttributeError:  # Legacy Python that doesn't verify HTTPS certificates by default
            ssl_context = ssl._create_unverified_context()
        else:  # Python 2.7.8 and older
            ssl._create_default_https_context = ssl._create_unverified_https_context

    # initialize connection
    if ssl_context:
        client = xmlrpc_client.ServerProxy(saturl, context=ssl_context)
    else:
        client = xmlrpc_client.Server(saturl)

    try:
        session = client.auth.login(user, password)
    except Exception as e:
        module.fail_json(
            msg="Unable to establish session with Satellite server: %s " %
            to_text(e))

    if not session:
        module.fail_json(
            msg="Failed to establish session with Satellite server.")

    # get systemid
    try:
        sys_id = get_systemid(client, session, systname)
    except Exception as e:
        module.fail_json(msg="Unable to get system id: %s " % to_text(e))

    if not sys_id:
        module.fail_json(msg="Failed to get system id.")

    # get channels for system
    try:
        chans = base_channels(client, session, sys_id)
    except Exception as e:
        module.fail_json(msg="Unable to get channel information: %s " %
                         to_text(e))

    try:
        if state == 'present':
            if channelname in chans:
                module.exit_json(changed=False,
                                 msg="Channel %s already exists" % channelname)
            else:
                subscribe_channels(channelname, client, session, systname,
                                   sys_id)
                module.exit_json(changed=True,
                                 msg="Channel %s added" % channelname)

        if state == 'absent':
            if channelname not in chans:
                module.exit_json(changed=False,
                                 msg="Not subscribed to channel %s." %
                                 channelname)
            else:
                unsubscribe_channels(channelname, client, session, systname,
                                     sys_id)
                module.exit_json(changed=True,
                                 msg="Channel %s removed" % channelname)
    except Exception as e:
        module.fail_json(msg='Unable to %s channel (%s): %s' %
                         ('add' if state == 'present' else 'remove',
                          channelname, to_text(e)))
    finally:
        client.auth.logout(session)
Exemple #5
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(type='str', default='127.0.0.1'),
            port=dict(type='int'),
            username=dict(type='str', default='cobbler'),
            password=dict(type='str', no_log=True),
            use_ssl=dict(type='bool', default=True),
            validate_certs=dict(type='bool', default=True),
            name=dict(type='str'),
            interfaces=dict(type='dict'),
            properties=dict(type='dict'),
            sync=dict(type='bool', default=False),
            state=dict(type='str',
                       default='present',
                       choices=['absent', 'present', 'query']),
        ),
        supports_check_mode=True,
    )

    username = module.params['username']
    password = module.params['password']
    port = module.params['port']
    use_ssl = module.params['use_ssl']
    validate_certs = module.params['validate_certs']

    name = module.params['name']
    state = module.params['state']

    module.params['proto'] = 'https' if use_ssl else 'http'
    if not port:
        module.params['port'] = '443' if use_ssl else '80'

    result = dict(changed=False, )

    start = datetime.datetime.utcnow()

    ssl_context = None
    if not validate_certs:
        try:  # Python 2.7.9 and newer
            ssl_context = ssl.create_unverified_context()
        except AttributeError:  # Legacy Python that doesn't verify HTTPS certificates by default
            ssl._create_default_context = ssl._create_unverified_context
        else:  # Python 2.7.8 and older
            ssl._create_default_https_context = ssl._create_unverified_https_context

    url = '{proto}://{host}:{port}/cobbler_api'.format(**module.params)
    if ssl_context:
        conn = xmlrpc_client.ServerProxy(url, context=ssl_context)
    else:
        conn = xmlrpc_client.Server(url)

    try:
        token = conn.login(username, password)
    except xmlrpc_client.Fault as e:
        module.fail_json(
            msg="Failed to log in to Cobbler '{url}' as '{username}'. {error}".
            format(url=url, error=to_text(e), **module.params))
    except Exception as e:
        module.fail_json(msg="Connection to '{url}' failed. {error}".format(
            url=url, error=to_text(e), **module.params))

    system = getsystem(conn, name, token)
    # result['system'] = system

    if state == 'query':
        if name:
            result['system'] = system
        else:
            # Turn it into a dictionary of dictionaries
            # all_systems = conn.get_systems()
            # result['systems'] = { system['name']: system for system in all_systems }

            # Return a list of dictionaries
            result['systems'] = conn.get_systems()

    elif state == 'present':

        if system:
            # Update existing entry
            system_id = conn.get_system_handle(name, token)

            for key, value in iteritems(module.params['properties']):
                if key not in system:
                    module.warn(
                        "Property '{0}' is not a valid system property.".
                        format(key))
                if system[key] != value:
                    try:
                        conn.modify_system(system_id, key, value, token)
                        result['changed'] = True
                    except Exception as e:
                        module.fail_json(
                            msg="Unable to change '{0}' to '{1}'. {2}".format(
                                key, value, e))

        else:
            # Create a new entry
            system_id = conn.new_system(token)
            conn.modify_system(system_id, 'name', name, token)
            result['changed'] = True

            if module.params['properties']:
                for key, value in iteritems(module.params['properties']):
                    try:
                        conn.modify_system(system_id, key, value, token)
                    except Exception as e:
                        module.fail_json(
                            msg="Unable to change '{0}' to '{1}'. {2}".format(
                                key, value, e))

        # Add interface properties
        interface_properties = dict()
        if module.params['interfaces']:
            for device, values in iteritems(module.params['interfaces']):
                for key, value in iteritems(values):
                    if key == 'name':
                        continue
                    if key not in IFPROPS_MAPPING:
                        module.warn(
                            "Property '{0}' is not a valid system property.".
                            format(key))
                    if not system or system['interfaces'][device][
                            IFPROPS_MAPPING[key]] != value:
                        result['changed'] = True
                    interface_properties['{0}-{1}'.format(key, device)] = value

            if result['changed'] is True:
                conn.modify_system(system_id, "modify_interface",
                                   interface_properties, token)

        # Only save when the entry was changed
        if not module.check_mode and result['changed']:
            conn.save_system(system_id, token)

    elif state == 'absent':

        if system:
            if not module.check_mode:
                conn.remove_system(name, token)
            result['changed'] = True

    if not module.check_mode and module.params['sync'] and result['changed']:
        try:
            conn.sync(token)
        except Exception as e:
            module.fail_json(
                msg="Failed to sync Cobbler. {0}".format(to_text(e)))

    if state in ('absent', 'present'):
        result['system'] = getsystem(conn, name, token)

        if module._diff:
            result['diff'] = dict(before=system, after=result['system'])

    elapsed = datetime.datetime.utcnow() - start
    module.exit_json(elapsed=elapsed.seconds, **result)