Example #1
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']

        if self.status >= 500:
            self.fail_json(
                msg='Request failed for {url}: {status} - {msg}'.format(
                    **info))
        elif self.status >= 300:
            self.fail_json(
                msg='Request failed for {url}: {status} - {msg}'.format(
                    **info),
                body=json.loads(to_native(info['body'])))
        try:
            return json.loads(to_native(resp.read()))
        except Exception:
            pass
Example #2
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

        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['timeout'],
            use_proxy=self.params['use_proxy'],
        )
        self.response = info['msg']
        self.status = info['status']

        # 200: OK, 201: Created, 202: Accepted, 204: No Content
        if self.status in (200, 201, 202, 204):
            output = resp.read()
            #            if self.method in ('DELETE', 'PATCH', 'POST', 'PUT') and self.status in (200, 201, 204):
            #                self.result['changed'] = True
            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:
                payload = json.loads(resp.read())
            except Exception:
                payload = json.loads(info['body'])
            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 {}
Example #3
0
    def request_upload(self, path, fields=None):
        ''' Generic HTTP MultiPart POST method for MSO uploads. '''
        self.path = path
        self.url = urljoin(self.baseuri, path)

        if not HAS_MULTIPART_ENCODER:
            self.fail_json(msg='requests-toolbelt is required for the upload state of this module')

        mp_encoder = MultipartEncoder(fields=fields)
        self.headers['Content-Type'] = mp_encoder.content_type
        self.headers['Accept-Encoding'] = "gzip, deflate, br"

        resp, info = fetch_url(self.module,
                               self.url,
                               headers=self.headers,
                               data=mp_encoder,
                               method='POST',
                               timeout=self.params.get('timeout'),
                               use_proxy=self.params.get('use_proxy'))

        self.response = info.get('msg')
        self.status = info.get('status')

        # 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)

        # 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:
                payload = json.loads(resp.read())
            except (ValueError, AttributeError):
                try:
                    payload = json.loads(info.get('body'))
                except Exception:
                    self.fail_json(msg='MSO Error:', info=info)
            if 'code' in payload:
                self.fail_json(msg='MSO Error {code}: {message}'.format(**payload), info=info, payload=payload)
            else:
                self.fail_json(msg='MSO Error:'.format(**payload), info=info, payload=payload)

        return {}
Example #4
0
 def _get_list_of_active_tables(self):
     if self.bins['nft']:
         cmd = [self.bins['nft'], '-v']
         rc, stdout, stderr = Iptables.module.run_command(cmd,
                                                          check_rc=False)
         if rc == 0:
             if self._ipversion == '4':
                 cmd = [self.bins['nft'], '-j', 'list', 'tables', 'ip']
                 rc, stdout, stderr = Iptables.module.run_command(
                     cmd, check_rc=False)
                 jsonout = json.loads(stdout)
                 if rc == 0:
                     if len(jsonout['nftables']) > 0:
                         table_names = []
                         for table in jsonout['nftables']:
                             if 'table' in table.keys():
                                 table_names.append(table['table']['name'])
                         return table_names
                     else:
                         return self.TABLES
             else:
                 cmd = [self.bins['nft'], '-j', 'list', 'tables', 'ip6']
                 rc, stdout, stderr = Iptables.module.run_command(
                     cmd, check_rc=False)
                 jsonout = json.loads(stdout)
                 if rc == 0:
                     if len(jsonout['nftables']) > 0:
                         table_names = []
                         for table in jsonout['nftables']:
                             if 'table' in table.keys():
                                 table_names.append(table['table']['name'])
                         return table_names
                     else:
                         return self.TABLES
     # assume that no nftables is used --> netfilter fallback
     else:
         if self._ipversion == '4':
             iptables_names_file = '/proc/net/ip_tables_names'
             if os.path.isfile(iptables_names_file):
                 table_names = open(iptables_names_file, 'r').read()
                 if table_names:
                     return table_names.splitlines()
                 else:
                     return self.TABLES
         else:
             iptables_names_file = '/proc/net/ip6_tables_names'
             if os.path.isfile(iptables_names_file):
                 table_names = open(iptables_names_file, 'r').read()
                 if table_names:
                     return table_names.splitlines()
                 else:
                     return self.TABLES
     return []
def main():

    argument_spec = dict(
        name=dict(type='str', required=True),
        host=dict(type='str', required=True),
        user=dict(type='str', required=True),
        password=dict(type='str', required=True, no_log=True),
    )

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)

    try:
        # Get the cluster object id
        result = open_url(
            url="https://{}/v3/cluster?name={}".format(
                module.params.get("host"), module.params.get("name")),
            url_username=module.params.get("user"),
            url_password=module.params.get("password"),
            force_basic_auth=True,
            headers={
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            validate_certs=False,
            method='GET',
        )
        cluster_resource = json.loads(result.read())

        # get the cluster id
        cluster_id = cluster_resource['data'][0]['id']

        result = open_url(
            url="https://{}/v3/clusterregistrationtoken?clusterId={}".format(
                module.params.get("host"), cluster_id),
            url_username=module.params.get("user"),
            url_password=module.params.get("password"),
            force_basic_auth=True,
            headers={
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            validate_certs=False,
            method='GET',
        )
        crt_resource = json.loads(result.read())
        module.exit_json(changed=False,
                         resource=crt_resource,
                         status=result.status,
                         reason=result.reason)

    except urllib_request.HTTPError as e:
        module.fail_json(msg=json.loads(e.fp.read()))
Example #6
0
    def request(self,
                path,
                method=None,
                payload=None,
                params=None,
                pagination_items=None):
        """ Submit HTTP request to Meraki API """
        self._set_url(path, method, params)

        try:
            # Gather the body (resp) and header (info)
            resp, info = self._execute_request(path,
                                               method=method,
                                               payload=payload,
                                               params=params)
        except HTTPError:
            self.fail_json(
                msg="HTTP request to {url} failed with error code {code}".
                format(url=self.url, code=self.status))
        self.response = info['msg']
        self.status = info['status']
        # This needs to be refactored as it's not very clean
        # Looping process for pagination
        if pagination_items is not None:
            data = None
            if 'body' in info:
                self.body = info['body']
            data = json.loads(to_native(resp.read()))
            header_link = self._parse_pagination_header(info['link'])
            while header_link['next'] is not None:
                self.url = header_link['next']
                try:
                    # Gather the body (resp) and header (info)
                    resp, info = self._execute_request(header_link['next'],
                                                       method=method,
                                                       payload=payload,
                                                       params=params)
                except HTTPError:
                    self.fail_json(
                        msg="HTTP request to {url} failed with error code {code}"
                        .format(url=self.url, code=self.status))
                header_link = self._parse_pagination_header(info['link'])
                data.extend(json.loads(to_native(resp.read())))
            return data
        else:  # Non-pagination
            if 'body' in info:
                self.body = info['body']
            try:
                return json.loads(to_native(resp.read()))
            except json.decoder.JSONDecodeError:
                return {}
Example #7
0
 def inner(self, *args, **kwargs):
     while True:
         try:
             response = function(self, *args, **kwargs)
             if self.status == 429:
                 raise RateLimitException(
                     "Rate limiter hit, retry {0}".format(self.retry))
             elif self.status == 500:
                 raise InternalErrorException(
                     "Internal server error 500, retry {0}".format(
                         self.retry))
             elif self.status == 502:
                 raise InternalErrorException(
                     "Internal server error 502, retry {0}".format(
                         self.retry))
             elif self.status == 400:
                 raise HTTPError("")
             elif self.status >= 400:
                 raise HTTPError("")
             self.retry = 0  # Needs to reset in case of future retries
             return response
         except RateLimitException as e:
             self.retry += 1
             if self.retry <= 10:
                 self.retry_time += self.retry * RATE_LIMIT_RETRY_MULTIPLIER
                 time.sleep(self.retry * RATE_LIMIT_RETRY_MULTIPLIER)
             else:
                 self.retry_time += 30
                 time.sleep(30)
             if self.retry_time > self.params['rate_limit_retry_time']:
                 raise RateLimitException(e)
         except InternalErrorException as e:
             self.retry += 1
             if self.retry <= 10:
                 self.retry_time += self.retry * INTERNAL_ERROR_RETRY_MULTIPLIER
                 time.sleep(self.retry * INTERNAL_ERROR_RETRY_MULTIPLIER)
             else:
                 self.retry_time += 9
                 time.sleep(9)
             if self.retry_time > self.params['internal_error_retry_time']:
                 raise InternalErrorException(e)
         except HTTPError as e:
             try:
                 self.fail_json(msg="HTTP error {0} - {1} - {2}".format(
                     self.status, self.url,
                     json.loads(self.body)['errors']),
                                body=json.loads(self.body))
             except json.decoder.JSONDecodeError:
                 self.fail_json(msg="HTTP error {0} - {1}".format(
                     self.status, self.url))
Example #8
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
Example #9
0
    def request(self, url_path, method='GET', payload=None, operation=None):
        """Generic HTTP method for nfvis requests."""

        if operation in ['get_vlan', 'get_files']:
            self.headers = {
                'Content-Type': 'application/vnd.yang.data+json',
                'Accept': 'application/vnd.yang.collection+json'
            }
        else:
            self.headers = {
                'Content-Type': 'application/vnd.yang.data+json',
                'Accept': 'application/vnd.yang.data+json'
            }

        if method is not None:
            self.method = method
        self.url = 'https://{0}/api{1}'.format(self.host, url_path)
        self.method = method
        self.payload = payload

        resp, info = fetch_url(
            self.module,
            self.url,
            headers=self.headers,
            data=payload,
            method=self.method,
            timeout=self.params['timeout'],
        )
        self.response = info['msg']
        self.status = info['status']

        if self.status >= 300 or self.status < 0:
            try:
                self.fail_json(
                    msg='Request failed for {url}: {status} - {msg}'.format(
                        **info),
                    body=json.loads(to_native(info['body'])))
            except Exception:
                pass

            self.fail_json(
                msg='Request failed for {url}: {status} - {msg}'.format(
                    **info))

        try:
            return json.loads(to_native(resp.read()))
        except Exception:
            pass
def main():
    '''main function'''

    module = AnsibleModule(argument_spec=dict(
        subnet_type=dict(type='str', choices=SUBNET_TYPES),
        quantity=dict(type='int', default=None),
        vlan_id=dict(type='str', default=None),
        version=dict(type='int', default=4, choices=IP_VERSION),
        state=dict(default='present', choices=STATES),
        username=dict(type='str', default=None),
        api_key=dict(type='str', default=None),
    ))

    if not HAS_SL:
        module.fail_json(
            msg='softlayer python library required for this module')

    username = module.params.get('username')
    api_key = module.params.get('api_key')
    state = module.params.get('state')

    manager = SubnetManager(username, api_key)

    if state == 'absent':
        (changed, instance) = manager.remove_subnet(module)

    elif state == 'present':
        (changed, instance) = manager.add_subnet(module)

    module.exit_json(changed=changed,
                     instance=json.loads(
                         json.dumps(instance, default=lambda o: o.__dict__)))
def main():

    argument_spec = dict(token=dict(type='str', required=True, no_log=True),
                         hostname=dict(type='str', required=True))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)
    try:
        r = RedHatSubscription(module.params.get("token"))
        uuid = r.system_uuid(module.params.get("hostname"))
        if not uuid:
            module.exit_json(changed=False,
                             meta={"msg": "Could not find system."})
        deleted = r.delete_system(uuid)
        if deleted:
            module.exit_json(changed=True, meta={"msg": "System deleted."})
        else:
            module.fail_json(meta={
                "msg":
                "The system exists, but something went wrong deleting it."
            })

    except urllib_request.HTTPError as e:
        module.fail_json(msg=json.loads(e.fp.read()))

    except:
        module.fail_json(meta={"msg": "Unknown error."})
Example #12
0
    def login(self):
        ''' Log in to MSO '''

        # Perform login request
        if (self.params.get('login_domain') is not None) and (self.params.get('login_domain') != 'Local'):
            domain_id = self.get_login_domain_id(self.params.get('login_domain'))
            payload = {'username': self.params.get('username'), 'password': self.params.get('password'), 'domainId': domain_id}
        else:
            payload = {'username': self.params.get('username'), 'password': self.params.get('password')}
        self.url = urljoin(self.baseuri, 'auth/login')
        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)
Example #13
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
Example #14
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
Example #15
0
def _list_pritunl_user(module, organization_id, user_id=None, filters=None):
    users = []

    response = pritunl_auth_request(module, 'GET',
                                    "/user/%s" % organization_id)

    if response.getcode() != 200:
        module.fail_json(msg='Could not retrive users from Pritunl')
    else:
        for user in json.loads(response.read()):
            # No filtering
            if filters is None:
                users.append(user)

            else:
                filtered_flag = False

                for filter_key, filter_val in iteritems(filters):
                    if filter_val != user[filter_key]:
                        filtered_flag = True

                if not filtered_flag:
                    users.append(user)

    return users
 def _read_state_file(self):
     json_str = '{}'
     if os.path.isfile(self.state_save_path):
         json_str = open(self.state_save_path, 'r').read()
     read_dict = defaultdict(lambda: dict(dump='', rules_dict={}),
                             json.loads(json_str))
     return read_dict
Example #17
0
def delete_pritunl_organization(module):
    result = {}

    org_name = module.params.get('name')

    if org_name is None:
        module.fail_json(
            msg='Please provide an organization name using name=<OrgName>')

    # Grab existing orgs
    orgs = _list_pritunl_organization(module, {"name": org_name})

    # Check if the pritunl org exists, if not, do nothing
    if len(orgs) == 0:
        result['changed'] = False
        result['response'] = {}

    # Otherwise remove the org from Pritunl
    else:
        response = pritunl_auth_request(module, 'DELETE',
                                        "/organization/%s" % orgs[0]['id'])

        if response.getcode() != 200:
            module.fail_json(
                msg="Could not remove organization %s from Pritunl" %
                (org_name))
        else:
            result['changed'] = True
            result['response'] = json.loads(response.read())

    module.exit_json(**result)
Example #18
0
def post_pritunl_organization(module):
    result = {}

    org_name = module.params.get('name')

    if org_name is None:
        module.fail_json(msg=("Please provide an organization name "
                              "using name=<OrgName>"))

    # Grab existing orgs
    orgs = _list_pritunl_organization(module, {"name": org_name})

    # Check if the pritunl org already exists
    # If yes do nothing
    if len(orgs) > 0:
        result['changed'] = False
        result['response'] = orgs

    # Otherwise add the org to Pritunl
    else:
        response = pritunl_auth_request(
            module,
            'POST',
            '/organization',
            headers={'Content-Type': 'application/json'},
            data=json.dumps({'name': org_name}))

        if response.getcode() != 200:
            module.fail_json(msg="Could not add organization %s to Pritunl" %
                             (org_name))
        else:
            result['changed'] = True
            result['response'] = json.loads(response.read())

    module.exit_json(**result)
Example #19
0
def install_it(module):
    data = {
        'name': module.params.get('name'),
        'active': True,
        'builtin': False,
        'url': module.params.get('url'),
        'uiUrl': module.params.get('uiUrl'),
        'whitelistDomains': ['*', '10.74.82.71', 'sec01u0peafy11.uathost.prd']
    }
    result = open_url(
        url="https://{}/v3/nodedriver".format(
            module.params.get("host"),
            module.params.get("name")
        ),
        url_username=module.params.get("user"),
        url_password=module.params.get("password"),
        force_basic_auth=True,
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        validate_certs=False,
        method='POST',
        data=json.dumps(data),
    )
    resource = json.loads(result.read())
    module.exit_json(changed=True, resource=resource, reason=result.reason, status=result.status)
Example #20
0
def get_snmp(meraki, org_id):
    path = meraki.construct_path('get_all', org_id=org_id)
    r = meraki.request(
        path,
        method='GET',
    )
    return json.loads(r)
Example #21
0
 def json(self):
     if not self.body:
         return None
     try:
         return json.loads(self.body)
     except ValueError:
         return None
Example #22
0
def main():
    '''main function'''

    module = AnsibleModule(argument_spec=dict(
        name=dict(type='str', default=None),
        key=dict(type='str', default=None),
        state=dict(default='present', choices=STATES),
        username=dict(type='str', default=None),
        api_key=dict(type='str', default=None),
    ))

    if not HAS_SL:
        module.fail_json(
            msg='softlayer python library required for this module')

    username = module.params.get('username')
    api_key = module.params.get('api_key')
    state = module.params.get('state')
    name = module.params.get('name')
    key = module.params.get('key')

    manager = SecureShellManager(username, api_key)

    if state == 'absent':
        (changed, key) = manager.remove_key(name)

    elif state == 'present':
        (changed, key) = manager.add_key(name, key)

    module.exit_json(changed=changed,
                     key=json.loads(
                         json.dumps(key, default=lambda o: o.__dict__)))
Example #23
0
 def json(self):
     if not self.body:
         return None
     try:
         return json.loads(self.body)
     except ValueError:
         return None
Example #24
0
    def login(self):
        ''' Log in to MSC '''

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

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

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

        self.headers['Authorization'] = 'Bearer {token}'.format(**payload)
Example #25
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 get_systems(self, offset=0, limit=100):
     systems = open_url(
         url=
         "https://api.access.redhat.com/management/v1/systems?limit={}&offset={}"
         .format(limit, offset),
         method='GET',
         headers=self.headers,
     )
     return json.loads(systems.read())
Example #27
0
def set_snmp(meraki, org_id):
    payload = dict()
    if meraki.params['peer_ips']:
        if len(meraki.params['peer_ips']) > 7:
            if ';' not in meraki.params['peer_ips']:
                meraki.fail_json(
                    msg='Peer IP addresses are semi-colon delimited.')
    if meraki.params['v2c_enabled'] is not None:
        payload = {
            'v2cEnabled': meraki.params['v2c_enabled'],
        }
    if meraki.params['v3_enabled'] is not None:
        if len(meraki.params['v3_auth_pass']) < 8 or len(
                meraki.params['v3_priv_pass']) < 8:
            meraki.fail_json(
                msg=
                'v3_auth_pass and v3_priv_pass must both be at least 8 characters long.'
            )
        if (meraki.params['v3_auth_mode'] is None
                or meraki.params['v3_auth_pass'] is None
                or meraki.params['v3_priv_mode'] is None
                or meraki.params['v3_priv_pass'] is None):
            meraki.fail_json(
                msg=
                'v3_auth_mode, v3_auth_pass, v3_priv_mode, and v3_auth_pass are required'
            )
        payload = {
            'v3Enabled': meraki.params['v3_enabled'],
            'v3AuthMode': meraki.params['v3_auth_mode'].upper(),
            'v3AuthPass': meraki.params['v3_auth_pass'],
            'v3PrivMode': meraki.params['v3_priv_mode'].upper(),
            'v3PrivPass': meraki.params['v3_priv_pass'],
            'peerIps': meraki.params['peer_ips'],
        }
    full_compare = {
        'v2cEnabled': meraki.params['v2c_enabled'],
        'v3Enabled': meraki.params['v3_enabled'],
        'v3AuthMode': meraki.params['v3_auth_mode'],
        'v3PrivMode': meraki.params['v3_priv_mode'],
        'peerIps': meraki.params['peer_ips'],
    }
    if meraki.params['v3_enabled'] is None:
        full_compare['v3Enabled'] = False
    if meraki.params['v2c_enabled'] is None:
        full_compare['v2cEnabled'] = False
    path = meraki.construct_path('create', org_id=org_id)
    snmp = get_snmp(meraki, org_id)
    ignored_parameters = ('v3AuthPass', 'v3PrivPass', 'hostname', 'port',
                          'v2CommunityString', 'v3User')
    if meraki.is_update_required(snmp,
                                 full_compare,
                                 optional_ignore=ignored_parameters):
        r = meraki.request(path, method='PUT', payload=json.dumps(payload))
        meraki.result['changed'] = True
        return json.loads(r)
    return -1
Example #28
0
    def execute(self, commands, output=None, **kwargs):
        commands = collections.deque(commands)
        output = output or self.default_output

        # only 10 commands can be encoded in each request
        # messages sent to the remote device
        stack = list()
        requests = list()

        while commands:
            stack.append(commands.popleft())
            if len(stack) == 10:
                body = self._get_body(stack, output)
                data = self._jsonify(body)
                requests.append(data)
                stack = list()

        if stack:
            body = self._get_body(stack, output)
            data = self._jsonify(body)
            requests.append(data)

        headers = {'Content-Type': 'application/json'}
        result = list()

        for req in requests:
            if self._nxapi_auth:
                headers['Cookie'] = self._nxapi_auth

            response, headers = fetch_url(self.url_args,
                                          self.url,
                                          data=data,
                                          headers=headers,
                                          method='POST')
            self._nxapi_auth = headers.get('set-cookie')

            if 'Connection failure: timed out' == headers.get('msg'):
                pass
            else:
                if headers['status'] != 200:
                    self._error(**headers)

                try:
                    response = json.loads(response.read())
                except ValueError:
                    raise NetworkError(
                        msg='unable to load response from device')

                output = response['ins_api']['outputs']['output']
                for item in to_list(output):
                    if item['code'] != '200':
                        self._error(output=output, **item)
                    else:
                        result.append(item['body'])

        return result
def get_admins(meraki, org_id):
    admins = meraki.request(
        meraki.construct_path(
            'query',
            function='admin',
            org_id=org_id
        ),
        method='GET'
    )
    return json.loads(admins)
 def get_access(self):
     access = open_url(
         url=
         "https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token",
         method='POST',
         data="grant_type=refresh_token&client_id=rhsm-api&refresh_token={}"
         .format(self.token))
     if access.status != 200:
         return False
     return json.loads(access.read())['access_token']
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
Example #32
0
 def get_net(self, org_name, net_name, data=None):
     ''' Return network information '''
     if not data:
         org_id = self.get_org_id(org_name)
         path = '/organizations/{org_id}/networks/{net_id}'.format(org_id=org_id, net_id=self.get_net_id(org_name=org_name, net_name=net_name, data=data))
         return json.loads(self.request('GET', path))
     else:
         for n in data:
             if n['name'] == net_name:
                 return n
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 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['orgAccess'] is not None:
        payload['orgAccess'] = meraki.params['orgAccess']
    if meraki.params['tags'] is not None:
        payload['tags'] = json.loads(meraki.params['tags'])
    if meraki.params['networks'] is not None:
        nets = get_nets_temp(meraki, org_id)
        networks = network_factory(meraki, meraki.params['networks'], nets)
        # meraki.fail_json(msg=str(type(networks)), data=networks)
        payload['networks'] = networks
    if is_admin_existing is None:  # Create new admin
        path = meraki.construct_path('create', function='admin', org_id=org_id)
        r = meraki.request(path,
                           method='POST',
                           payload=json.dumps(payload)
                           )
        meraki.result['changed'] = True
        return json.loads(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:
            # meraki.fail_json(msg='Update is required!!!', original=is_admin_existing, proposed=payload)
            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)
                               )
            meraki.result['changed'] = True
            return json.loads(r)
        else:
            # meraki.fail_json(msg='No update is required!!!')
            return -1
Example #35
0
    def execute(self, commands, output=None, **kwargs):
        commands = collections.deque(commands)
        output = output or self.default_output

        # only 10 commands can be encoded in each request
        # messages sent to the remote device
        stack = list()
        requests = list()

        while commands:
            stack.append(commands.popleft())
            if len(stack) == 10:
                body = self._get_body(stack, output)
                data = self._jsonify(body)
                requests.append(data)
                stack = list()

        if stack:
            body = self._get_body(stack, output)
            data = self._jsonify(body)
            requests.append(data)

        headers = {'Content-Type': 'application/json'}
        result = list()

        for req in requests:
            if self._nxapi_auth:
                headers['Cookie'] = self._nxapi_auth

            response, headers = fetch_url(
                self.url_args, self.url, data=data, headers=headers, method='POST'
            )
            self._nxapi_auth = headers.get('set-cookie')

            if 'Connection failure: timed out' == headers.get('msg'):
                pass
            else:
                if headers['status'] != 200:
                    self._error(**headers)

                try:
                    response = json.loads(response.read())
                except ValueError:
                    raise NetworkError(msg='unable to load response from device')

                output = response['ins_api']['outputs']['output']
                for item in to_list(output):
                    if item['code'] != '200':
                        self._error(output=output, **item)
                    else:
                        result.append(item['body'])

        return result
Example #36
0
 def _read_state_file(self):
     json_str = '{}'
     if os.path.isfile(self.state_save_path):
         try:
             json_str = open(self.state_save_path, 'r').read()
         except:
             Iptables.module.fail_json(msg="Could not read the state file '%s'!" % self.state_save_path)
     try:
         read_dict = defaultdict(lambda: dict(dump='', rules_dict={}), json.loads(json_str))
     except:
         Iptables.module.fail_json(msg="Could not parse the state file '%s'! Please manually delete it to continue." % self.state_save_path)
     return read_dict
Example #37
0
 def run_commands(self, commands):
     cmds = list(prepare_commands(commands))
     responses = self.execute(cmds)
     for index, cmd in enumerate(commands):
         if cmd.output == 'json':
             try:
                 responses[index] = json.loads(responses[index])
             except ValueError:
                 raise NetworkError(
                     msg='unable to load response from device',
                     response=responses[index]
                 )
     return responses
Example #38
0
 def run_commands(self, commands):
     cmds = list(prepare_commands(commands))
     responses = self.execute(cmds)
     for index, cmd in enumerate(commands):
         raw = cmd.args.get('raw') or False
         if cmd.output == 'json' and not raw:
             try:
                 responses[index] = json.loads(responses[index])
             except ValueError:
                 raise NetworkError(
                     msg='unable to load response from device',
                     response=responses[index], command=str(cmd)
                 )
     return responses
Example #39
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
Example #40
0
    def execute(self, commands, output='json', **kwargs):
        """Send commands to the device.
        """
        if self.url is None:
            raise NetworkError('Not connected to endpoint.')

        if self.enable is not None:
            commands.insert(0, self.enable)

        body = self._get_body(commands, output)
        data = json.dumps(body)

        headers = {'Content-Type': 'application/json-rpc'}
        timeout = self.url_args.params['timeout']

        response, headers = fetch_url(
            self.url_args, self.url, data=data, headers=headers,
            method='POST', timeout=timeout
        )

        if headers['status'] != 200:
            raise NetworkError(**headers)

        try:
            response = json.loads(response.read())
        except ValueError:
            raise NetworkError('unable to load response from device')

        if 'error' in response:
            err = response['error']
            raise NetworkError(
                msg=err['message'], code=err['code'], data=err['data'],
                commands=commands
            )

        if self.enable:
            response['result'].pop(0)

        return response['result']
Example #41
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
Example #42
0
    def execute(self, commands, output=None, **kwargs):
        """Send commands to the device.
        """
        commands = to_list(commands)
        output = output or self.default_output

        data = self._get_body(commands, output)
        data = self._jsonify(data)

        headers = {'Content-Type': 'application/json'}
        if self._nxapi_auth:
            headers['Cookie'] = self._nxapi_auth

        response, headers = fetch_url(
            self.url_args, self.url, data=data, headers=headers, method='POST'
        )
        self._nxapi_auth = headers.get('set-cookie')

        if headers['status'] != 200:
            self._error(**headers)

        try:
            response = json.loads(response.read())
        except ValueError:
            raise NetworkError(msg='unable to load repsonse from device')

        result = list()

        output = response['ins_api']['outputs']['output']
        for item in to_list(output):
            if item['code'] != '200':
                self._error(**item)
            else:
                result.append(item['body'])

        return result
def main():

    # define the available arguments/parameters that a user can pass to
    # the module
    argument_spec = meraki_argument_spec()
    argument_spec.update(clone=dict(type='str'),
                         state=dict(type='str', choices=['present', 'query'], default='present'),
                         org_name=dict(type='str', aliases=['name', 'organization']),
                         org_id=dict(type='int', aliases=['id']),
                         )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
    )
    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           )
    meraki = MerakiModule(module, function='organizations')

    meraki.params['follow_redirects'] = 'all'

    create_urls = {'organizations': '/organizations',
                   }
    update_urls = {'organizations': '/organizations/{org_id}',
                   }
    clone_urls = {'organizations': '/organizations/{org_id}/clone',
                  }

    meraki.url_catalog['create'] = create_urls
    meraki.url_catalog['update'] = update_urls
    meraki.url_catalog['clone'] = clone_urls

    payload = None

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    # FIXME: Work with Meraki so they can implement a check mode
    if module.check_mode:
        meraki.exit_json(**meraki.result)

    # execute checks for argument completeness

    # manipulate or modify the state as needed (this is going to be the
    # part where your module will do what it needs to do)
    orgs = meraki.get_orgs()
    if meraki.params['state'] == 'query':
        if meraki.params['org_name']:  # Query by organization name
            module.warn('All matching organizations will be returned, even if there are duplicate named organizations')
            for o in orgs:
                if o['name'] == meraki.params['org_name']:
                    meraki.result['data'] = o
        elif meraki.params['org_id']:
            for o in orgs:
                if o['id'] == meraki.params['org_id']:
                    meraki.result['data'] = o
        else:  # Query all organizations, no matter what
            orgs = meraki.get_orgs()
            meraki.result['data'] = orgs
    elif meraki.params['state'] == 'present':
        if meraki.params['clone']:  # Cloning
            payload = {'name': meraki.params['org_name']}
            meraki.result['data'] = json.loads(
                meraki.request(
                    meraki.construct_path(
                        'clone',
                        org_name=meraki.params['clone']
                    ),
                    payload=json.dumps(payload),
                    method='POST'))
        elif not meraki.params['org_id'] and meraki.params['org_name']:  # Create new organization
            payload = {'name': meraki.params['org_name']}
            meraki.result['data'] = json.loads(
                meraki.request(
                    meraki.construct_path('create'),
                    method='POST',
                    payload=json.dumps(payload)))
        elif meraki.params['org_id'] and meraki.params['org_name']:  # Update an existing organization
            payload = {'name': meraki.params['org_name'],
                       'id': meraki.params['org_id'],
                       }
            meraki.result['data'] = json.loads(
                meraki.request(
                    meraki.construct_path(
                        'update',
                        org_id=meraki.params['org_id']
                    ),
                    method='PUT',
                    payload=json.dumps(payload)))

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    meraki.exit_json(**meraki.result)
Example #44
0
 def get_orgs(self):
     ''' Downloads all organizations '''
     return json.loads(self.request('/organizations', method='GET'))