Ejemplo n.º 1
0
 def get_network(self, network_id, network_name, limit=-1):
     """
     Search network_name inside Infinity by using rest api
     Network id  or network_name needs to be provided
     return the details of a given with given network_id or name
     """
     if network_name is None and network_id is None:
         self.module.exit_json(
             msg="You must specify  one of the options 'network_name' or 'network_id'.")
     method = "get"
     resource_url = ''
     params = {}
     response = None
     if network_id:
         resource_url = "networks/" + str(network_id)
         response = self._get_api_call_ansible_handler(method, resource_url)
     if network_id is None and network_name:
         method = "get"
         resource_url = "search"
         params = {"query": json.dumps(
             {"name": network_name, "type": "network"})}
         response = self._get_api_call_ansible_handler(
             method, resource_url, payload_data=json.dumps(params))
         if response and isinstance(response, str):
             response = json.loads(response)
         if response and isinstance(response, list) and len(
                 response) > 1 and limit == 1:
             response = response[0]
             response = json.dumps(response)
     return response
Ejemplo n.º 2
0
    def login(self):
        ''' Log in to MSO '''

        # Perform login request
        self.url = urljoin(self.baseuri, 'auth/login')
        payload = {
            'username': self.params.get('username'),
            'password': self.params.get('password')
        }
        resp, auth = fetch_url(self.module,
                               self.url,
                               data=json.dumps(payload),
                               method='POST',
                               headers=self.headers,
                               timeout=self.params.get('timeout'),
                               use_proxy=self.params.get('use_proxy'))

        # Handle MSO response
        if auth.get('status') != 201:
            self.response = auth.get('msg')
            self.status = auth.get('status')
            self.fail_json(msg='Authentication failed: {msg}'.format(**auth))

        payload = json.loads(resp.read())

        self.headers['Authorization'] = 'Bearer {token}'.format(**payload)
Ejemplo n.º 3
0
    def request(self, path, method=None, payload=None):
        """Generic HTTP method for Meraki requests."""
        self.path = path
        self.define_protocol()

        if method is not None:
            self.method = method
        self.url = '{protocol}://{host}/api/v0/{path}'.format(
            path=self.path.lstrip('/'), **self.params)
        resp, info = fetch_url(
            self.module,
            self.url,
            headers=self.headers,
            data=payload,
            method=self.method,
            timeout=self.params['timeout'],
            use_proxy=self.params['use_proxy'],
        )
        self.response = info['msg']
        self.status = info['status']

        try:
            return json.loads(to_native(resp.read()))
        except Exception:
            pass
Ejemplo n.º 4
0
    def release_ip(self, network_id="", ip_address=""):
        """
        Reserve ip address via  Infinity by using rest api
        """
        method = "get"
        resource_url = ''
        response = None
        if ip_address is None or network_id is None:
            self.module.exit_json(
                msg="You must specify  those two options: 'network_id' and 'ip_address'.")

        resource_url = "networks/" + str(network_id) + "/children"
        response = self._get_api_call_ansible_handler(method, resource_url)
        if not response:
            self.module.exit_json(
                msg="There is an error in release ip %s from network  %s." %
                (ip_address, network_id))

        ip_list = json.loads(response)
        ip_idlist = []
        for ip_item in ip_list:
            ip_id = ip_item['id']
            ip_idlist.append(ip_id)
        deleted_ip_id = ''
        for ip_id in ip_idlist:
            ip_response = ''
            resource_url = "ip_addresses/" + str(ip_id)
            ip_response = self._get_api_call_ansible_handler(
                method,
                resource_url,
                stat_codes=[200])
            if ip_response and json.loads(
                    ip_response)['address'] == str(ip_address):
                deleted_ip_id = ip_id
                break
        if deleted_ip_id:
            method = 'delete'
            resource_url = "ip_addresses/" + str(deleted_ip_id)
            response = self._get_api_call_ansible_handler(
                method, resource_url, stat_codes=[204])
        else:
            self.module.exit_json(
                msg=" When release ip, could not find the ip address %r from the given network %r' ." %
                (ip_address, network_id))

        return response
def create_admin(meraki, org_id, name, email):
    payload = dict()
    payload['name'] = name
    payload['email'] = email

    is_admin_existing = find_admin(meraki, get_admins(meraki, org_id), email)

    if meraki.params['org_access'] is not None:
        payload['orgAccess'] = meraki.params['org_access']
    if meraki.params['tags'] is not None:
        payload['tags'] = json.loads(meraki.params['tags'])
    if meraki.params['networks'] is not None:
        nets = meraki.get_nets(org_id=org_id)
        networks = network_factory(meraki, meraki.params['networks'], nets)
        payload['networks'] = networks
    if is_admin_existing is None:  # Create new admin
        if meraki.module.check_mode is True:
            meraki.result['data'] = payload
            meraki.result['changed'] = True
            meraki.exit_json(**meraki.result)
        path = meraki.construct_path('create', function='admin', org_id=org_id)
        r = meraki.request(path, method='POST', payload=json.dumps(payload))
        if meraki.status == 201:
            meraki.result['changed'] = True
            return r
    elif is_admin_existing is not None:  # Update existing admin
        if not meraki.params['tags']:
            payload['tags'] = []
        if not meraki.params['networks']:
            payload['networks'] = []
        if meraki.is_update_required(is_admin_existing, payload) is True:
            if meraki.module.check_mode is True:
                diff = recursive_diff(is_admin_existing, payload)
                is_admin_existing.update(payload)
                meraki.result['diff'] = {
                    'before': diff[0],
                    'after': diff[1],
                }
                meraki.result['changed'] = True
                meraki.result['data'] = payload
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path(
                'update', function='admin',
                org_id=org_id) + is_admin_existing['id']
            r = meraki.request(path, method='PUT', payload=json.dumps(payload))
            if meraki.status == 200:
                meraki.result['changed'] = True
                return r
        else:
            meraki.result['data'] = is_admin_existing
            if meraki.module.check_mode is True:
                meraki.result['data'] = payload
                meraki.exit_json(**meraki.result)
            return -1
def network_factory(meraki, networks, nets):
    networks = json.loads(networks)
    networks_new = []
    for n in networks:
        networks_new.append({
            'id':
            meraki.get_net_id(org_name=meraki.params['org_name'],
                              net_name=n['network'],
                              data=nets),
            'access':
            n['access']
        })
    return networks_new
Ejemplo n.º 7
0
 def get_network_id(self, network_name="", network_type='lan'):
     """
     query network_id from Infinity  via rest api based on given network_name
     """
     method = 'get'
     resource_url = 'search'
     response = None
     if network_name is None:
         self.module.exit_json(
             msg="You must specify the option 'network_name'")
     params = {"query": json.dumps(
         {"name": network_name, "type": "network"})}
     response = self._get_api_call_ansible_handler(
         method, resource_url, payload_data=json.dumps(params))
     network_id = ""
     if response and isinstance(response, str):
         response = json.loads(response)
     if response and isinstance(response, list):
         response = response[0]
         network_id = response['id']
     return network_id
Ejemplo n.º 8
0
    def release_network(
            self,
            network_id="",
            released_network_name="",
            released_network_type='lan'):
        """
        Release the network with name 'released_network_name' from the given  supernet network_id
        """
        method = 'get'
        response = None
        if network_id is None or released_network_name is None:
            self.module.exit_json(
                msg="You must specify those options 'network_id', 'reserved_network_name' and 'reserved_network_size'")
        matched_network_id = ""
        resource_url = "networks/" + str(network_id) + "/children"
        response = self._get_api_call_ansible_handler(method, resource_url)
        if not response:
            self.module.exit_json(
                msg=" there is an error in releasing network %r  from network  %s." %
                (network_id, released_network_name))
        if response:
            response = json.loads(response)
            for child_net in response:
                if child_net['network'] and child_net['network']['network_name'] == released_network_name:
                    matched_network_id = child_net['network']['network_id']
                    break
        response = None
        if matched_network_id:
            method = 'delete'
            resource_url = "networks/" + str(matched_network_id)
            response = self._get_api_call_ansible_handler(
                method, resource_url, stat_codes=[204])
        else:
            self.module.exit_json(
                msg=" When release network , could not find the network   %r from the given superent %r' " %
                (released_network_name, network_id))

        return response
Ejemplo n.º 9
0
 def json(self):
     return json.loads(self.content)
Ejemplo n.º 10
0
    def request(self, path, method=None, data=None, qs=None):
        ''' Generic HTTP method for MSO requests. '''
        self.path = path

        if method is not None:
            self.method = method

        # If we PATCH with empty operations, return
        if method == 'PATCH' and not data:
            return {}

        self.url = urljoin(self.baseuri, path)

        if qs is not None:
            self.url = self.url + update_qs(qs)

        resp, info = fetch_url(
            self.module,
            self.url,
            headers=self.headers,
            data=json.dumps(data),
            method=self.method,
            timeout=self.params.get('timeout'),
            use_proxy=self.params.get('use_proxy'),
        )
        self.response = info.get('msg')
        self.status = info.get('status')

        # self.result['info'] = info

        # Get change status from HTTP headers
        if 'modified' in info:
            self.has_modified = True
            if info.get('modified') == 'false':
                self.result['changed'] = False
            elif info.get('modified') == 'true':
                self.result['changed'] = True

        # 200: OK, 201: Created, 202: Accepted, 204: No Content
        if self.status in (200, 201, 202, 204):
            output = resp.read()
            if output:
                return json.loads(output)

        # 404: Not Found
        elif self.method == 'DELETE' and self.status == 404:
            return {}

        # 400: Bad Request, 401: Unauthorized, 403: Forbidden,
        # 405: Method Not Allowed, 406: Not Acceptable
        # 500: Internal Server Error, 501: Not Implemented
        elif self.status >= 400:
            try:
                output = resp.read()
                payload = json.loads(output)
            except (ValueError, AttributeError):
                try:
                    payload = json.loads(info['body'])
                except Exception:
                    self.fail_json(msg='MSO Error:', data=data, info=info)
            if 'code' in payload:
                self.fail_json(
                    msg='MSO Error {code}: {message}'.format(**payload),
                    data=data,
                    info=info,
                    payload=payload)
            else:
                self.fail_json(msg='MSO Error:'.format(**payload),
                               data=data,
                               info=info,
                               payload=payload)

        return {}