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)
Exemple #2
0
    def api(self, method, *args):
        '''
            Convenience RPC wrapper
        '''
        if self.server is None:
            if self.hostname != 'rhn.redhat.com':
                url = "https://%s/rpc/api" % self.hostname
            else:
                url = "https://xmlrpc.%s/rpc/api" % self.hostname
            self.server = xmlrpc_client.ServerProxy(url)
            self.session = self.server.auth.login(self.username, self.password)

        func = getattr(self.server, method)
        return func(self.session, *args)
Exemple #3
0
def main():

    module = AnsibleModule(argument_spec=dict(
        name=dict(type='str', required=True),
        url=dict(type='str', required=True),
        user=dict(type='str', required=True),
        password=dict(type='str', required=True, no_log=True),
        upgradable=dict(type='bool', required=False, default=False),
        extra=dict(type='bool', required=False, default=False),
    ))

    result = {}
    result['system'] = system = module.params['name']
    result['url'] = url = module.params['url']
    result['user'] = user = module.params['user']
    password = module.params['password']
    result['upgradable'] = upgradable = module.params['upgradable']
    result['extra'] = extra = module.params['extra']

    # Initialize connection
    client = xmlrpc_client.ServerProxy(url)
    try:
        session = client.auth.login(user, password)
    except Exception as e:
        module.fail_json(msg="Cannot connect to spacewalk server: %s " %
                         to_text(e))

    if not session:
        module.fail_json(msg="Cannot connect to spacewalk server.")

    # Get system list
    try:
        systemId = get_system_id(client, session, system)
        if upgradable:
            package_list = get_upgradable_packages(client, session, systemId)
        elif extra:
            package_list = get_extra_packages(client, session, systemId)
        else:
            package_list = get_packages(client, session, systemId)
        result['packages'] = package_list
        result['changed'] = True
        result['count'] = len(package_list)
        module.exit_json(**result)
    except Exception as e:
        result['changed'] = False
        result['msg'] = str(e)
        module.fail_json(**result)
    finally:
        client.auth.logout(session)
Exemple #4
0
def main():

    module = AnsibleModule(argument_spec=dict(
        url=dict(type='str', required=True),
        user=dict(type='str', required=True),
        password=dict(type='str', required=True, no_log=True),
        out_of_date=dict(type='bool', required=False, default=False),
        physical=dict(type='bool', required=False, default=False),
    ))

    result = {}
    result['url'] = url = module.params['url']
    result['user'] = user = module.params['user']
    result['out_of_date'] = out_of_date = module.params['out_of_date']
    result['physical'] = physical = module.params['physical']
    password = module.params['password']

    # Initialize connection
    client = xmlrpc_client.ServerProxy(url)
    try:
        session = client.auth.login(user, password)
    except Exception as e:
        module.fail_json(msg="Cannot connect to spacewalk server: %s " %
                         to_text(e))

    if not session:
        module.fail_json(msg="Cannot connect to spacewalk server.")

    # Get system list
    try:
        if out_of_date:
            system_list = get_ood_system_list(client, session)
        elif physical:
            system_list = get_phys_system_list(client, session)
        else:
            system_list = get_system_list(client, session)
        result['changed'] = True
        result['msg'] = "System list successful."
        result['systems'] = system_list
        result['count'] = len(system_list)
        module.exit_json(**result)
    except Exception as e:
        result['changed'] = False
        result['msg'] = str(e)
        module.exit_json(**result)
    finally:
        client.auth.logout(session)
Exemple #5
0
EXAMPLES = '''
  - name: Create a test app
    community.general.webfaction_app:
      name: "my_wsgi_app1"
      state: present
      type: mod_wsgi35-python27
      login_name: "{{webfaction_user}}"
      login_password: "******"
      machine: "{{webfaction_machine}}"
'''

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves import xmlrpc_client

webfaction = xmlrpc_client.ServerProxy('https://api.webfaction.com/')


def main():

    module = AnsibleModule(argument_spec=dict(
        name=dict(required=True),
        state=dict(required=False,
                   choices=['present', 'absent'],
                   default='present'),
        type=dict(required=True),
        autostart=dict(required=False, type='bool', default=False),
        extra_info=dict(required=False, default=""),
        port_open=dict(required=False, type='bool', default=False),
        login_name=dict(required=True),
        login_password=dict(required=True, no_log=True),
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.ServerProxy(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)
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 #8
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)