def main():

    # define the available arguments/parameters that a user can pass to
    # the module

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        net_id=dict(type='str'),
        net_name=dict(type='str', aliases=['network']),
        state=dict(type='str', default='present', choices=['present', 'query']),
        allowed_urls=dict(type='list', elements='str'),
        blocked_urls=dict(type='list', elements='str'),
        blocked_categories=dict(type='list', elements='str'),
        category_list_size=dict(type='str', choices=['top sites', 'full list']),
        subset=dict(type='str', choices=['categories', 'policy']),
    )

    # 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='content_filtering')
    module.params['follow_redirects'] = 'all'

    category_urls = {'content_filtering': '/networks/{net_id}/contentFiltering/categories'}
    policy_urls = {'content_filtering': '/networks/{net_id}/contentFiltering'}

    meraki.url_catalog['categories'] = category_urls
    meraki.url_catalog['policy'] = policy_urls

    if meraki.params['net_name'] and meraki.params['net_id']:
        meraki.fail_json(msg='net_name and net_id are mutually exclusive')

    # manipulate or modify the state as needed (this is going to be the
    # part where your module will do what it needs to do)

    org_id = meraki.params['org_id']
    if not org_id:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = None
    if net_id is None:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(org_id, meraki.params['net_name'], data=nets)

    if meraki.params['state'] == 'query':
        if meraki.params['subset']:
            if meraki.params['subset'] == 'categories':
                path = meraki.construct_path('categories', net_id=net_id)
            elif meraki.params['subset'] == 'policy':
                path = meraki.construct_path('policy', net_id=net_id)
            meraki.result['data'] = meraki.request(path, method='GET')
        else:
            response_data = {'categories': None,
                             'policy': None,
                             }
            path = meraki.construct_path('categories', net_id=net_id)
            response_data['categories'] = meraki.request(path, method='GET')
            path = meraki.construct_path('policy', net_id=net_id)
            response_data['policy'] = meraki.request(path, method='GET')
            meraki.result['data'] = response_data
    if module.params['state'] == 'present':
        payload = dict()
        if meraki.params['allowed_urls']:
            payload['allowedUrlPatterns'] = meraki.params['allowed_urls']
        if meraki.params['blocked_urls']:
            payload['blockedUrlPatterns'] = meraki.params['blocked_urls']
        if meraki.params['blocked_categories']:
            if len(meraki.params['blocked_categories']) == 0:  # Corner case for resetting
                payload['blockedUrlCategories'] = []
            else:
                category_path = meraki.construct_path('categories', net_id=net_id)
                categories = meraki.request(category_path, method='GET')
                payload['blockedUrlCategories'] = []
                for category in meraki.params['blocked_categories']:
                    payload['blockedUrlCategories'].append(get_category_dict(meraki,
                                                                             categories,
                                                                             category))
        if meraki.params['category_list_size']:
            if meraki.params['category_list_size'].lower() == 'top sites':
                payload['urlCategoryListSize'] = "topSites"
            elif meraki.params['category_list_size'].lower() == 'full list':
                payload['urlCategoryListSize'] = "fullList"
        path = meraki.construct_path('policy', net_id=net_id)
        current = meraki.request(path, method='GET')
        proposed = current.copy()
        proposed.update(payload)
        if meraki.is_update_required(current, payload) is True:
            if module.check_mode:
                meraki.generate_diff(current, payload)
                current.update(payload)
                meraki.result['changed'] = True
                meraki.result['data'] = current
                meraki.exit_json(**meraki.result)
            response = meraki.request(path, method='PUT', payload=json.dumps(payload))
            meraki.result['data'] = response
            meraki.result['changed'] = True
            meraki.generate_diff(current, response)
        else:
            meraki.result['data'] = current
            if module.check_mode:
                meraki.result['data'] = current
                meraki.exit_json(**meraki.result)
            meraki.result['data'] = current
            meraki.exit_json(**meraki.result)

    # 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)
Exemple #2
0
def main():

    # define the available arguments/parameters that a user can pass to
    # the module

    server_arg_spec = dict(
        host=dict(type='str'),
        port=dict(type='int', default="514"),
        roles=dict(type='list',
                   elements='str',
                   choices=[
                       'Wireless Event log',
                       'Appliance event log',
                       'Switch event log',
                       'Air Marshal events',
                       'Flows',
                       'URLs',
                       'IDS alerts',
                       'Security events',
                   ]),
    )

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        net_id=dict(type='str'),
        servers=dict(type='list', elements='dict', options=server_arg_spec),
        state=dict(type='str', choices=['present', 'query'],
                   default='present'),
        net_name=dict(type='str', aliases=['name', 'network']),
    )

    # 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='syslog')
    module.params['follow_redirects'] = 'all'
    payload = None

    syslog_urls = {'syslog': '/networks/{net_id}/syslogServers'}
    meraki.url_catalog['query_update'] = syslog_urls

    if not meraki.params['org_name'] and not meraki.params['org_id']:
        meraki.fail_json(msg='org_name or org_id parameters are required')
    if meraki.params['state'] != 'query':
        if not meraki.params['net_name'] and not meraki.params['net_id']:
            meraki.fail_json(
                msg=
                'net_name or net_id is required for present or absent states')
    if meraki.params['net_name'] and meraki.params['net_id']:
        meraki.fail_json(msg='net_name and net_id are mutually exclusive')

    # 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

    # manipulate or modify the state as needed (this is going to be the
    # part where your module will do what it needs to do)

    org_id = meraki.params['org_id']
    if not org_id:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = meraki.params['net_id']
    if net_id is None:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(net_name=meraki.params['net_name'],
                                   data=nets)

    if meraki.params['state'] == 'query':
        path = meraki.construct_path('query_update', net_id=net_id)
        r = meraki.request(path, method='GET')
        if meraki.status == 200:
            meraki.result['data'] = r
    elif meraki.params['state'] == 'present':
        # Construct payload
        payload = dict()
        payload['servers'] = meraki.params['servers']

        # Convert port numbers to string for idempotency checks
        for server in payload['servers']:
            if server['port']:
                server['port'] = str(server['port'])
        path = meraki.construct_path('query_update', net_id=net_id)
        r = meraki.request(path, method='GET')
        if meraki.status == 200:
            original = dict()
            original['servers'] = r

        if meraki.is_update_required(original, payload):
            if meraki.module.check_mode is True:
                meraki.generate_diff(original, payload)
                original.update(payload)
                meraki.result['data'] = original
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path('query_update', net_id=net_id)
            r = meraki.request(path, method='PUT', payload=json.dumps(payload))
            if meraki.status == 200:
                meraki.generate_diff(original, r)
                meraki.result['data'] = r
                meraki.result['changed'] = True
        else:
            if meraki.module.check_mode is True:
                meraki.result['data'] = original
                meraki.exit_json(**meraki.result)
            meraki.result['data'] = original

    # 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)
def main():

    # define the available arguments/parameters that a user can pass to
    # the module

    destinations_arg_spec = dict(all_admins=dict(type='bool'),
                                 snmp=dict(type='bool'),
                                 emails=dict(type='list', elements='str'),
                                 http_server_ids=dict(type='list', elements='str', default=[]),
                                 )

    alerts_arg_spec = dict(alert_type=dict(type='str'),
                           enabled=dict(type='bool'),
                           alert_destinations=dict(type='dict', default=None, options=destinations_arg_spec),
                           filters=dict(type='raw', default={}),
                           )

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        net_id=dict(type='str'),
        net_name=dict(type='str', aliases=['name', 'network']),
        state=dict(type='str', choices=['present', 'query'], default='present'),
        default_destinations=dict(type='dict', default=None, options=destinations_arg_spec),
        alerts=dict(type='list', elements='dict', options=alerts_arg_spec),
    )

    # 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='alert')
    module.params['follow_redirects'] = 'all'

    query_urls = {'alert': '/networks/{net_id}/alerts/settings'}
    update_urls = {'alert': '/networks/{net_id}/alerts/settings'}
    meraki.url_catalog['get_all'].update(query_urls)
    meraki.url_catalog['update'] = update_urls

    # manipulate or modify the state as needed (this is going to be the
    # part where your module will do what it needs to do)

    org_id = meraki.params['org_id']
    if org_id is None:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = meraki.params['net_id']
    if net_id is None:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(net_name=meraki.params['net_name'], data=nets)

    if meraki.params['state'] == 'query':
        path = meraki.construct_path('get_all', net_id=net_id)
        response = meraki.request(path, method='GET')
        if meraki.status == 200:
            meraki.result['data'] = response
        meraki.exit_json(**meraki.result)
    elif meraki.params['state'] == 'present':
        path = meraki.construct_path('get_all', net_id=net_id)
        original = meraki.request(path, method='GET')
        payload = construct_payload(meraki, original)
        # meraki.fail_json(msg="Compare", original=original, payload=payload)
        # meraki.fail_json(msg=payload)
        if meraki.is_update_required(original, payload):
            if meraki.check_mode is True:
                meraki.generate_diff(original, payload)
                meraki.result['data'] = payload
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path('update', net_id=net_id)
            response = meraki.request(path, method='PUT', payload=json.dumps(payload))
            if meraki.status == 200:
                meraki.generate_diff(original, payload)
                meraki.result['data'] = response
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
        else:
            meraki.result['data'] = original
            meraki.exit_json(**meraki.result)

    # 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)
def main():
    # define the available arguments/parameters that a user can pass to
    # the module

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   choices=['absent', 'present', 'query'],
                   default='query'),
        net_name=dict(type='str', aliases=['network']),
        net_id=dict(type='str'),
        name=dict(type='str'),
        url=dict(type='str'),
        shared_secret=dict(type='str', no_log=True),
        webhook_id=dict(type='str'),
        test=dict(type='str', choices=['test', 'status']),
        test_id=dict(type='str'),
    )

    # 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='webhooks')

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

    query_url = {'webhooks': '/networks/{net_id}/httpServers'}
    query_one_url = {'webhooks': '/networks/{net_id}/httpServers/{hookid}'}
    create_url = {'webhooks': '/networks/{net_id}/httpServers'}
    update_url = {'webhooks': '/networks/{net_id}/httpServers/{hookid}'}
    delete_url = {'webhooks': '/networks/{net_id}/httpServers/{hookid}'}
    test_url = {'webhooks': '/networks/{net_id}/httpServers/webhookTests'}
    test_status_url = {
        'webhooks': '/networks/{net_id}/httpServers/webhookTests/{testid}'
    }

    meraki.url_catalog['get_all'].update(query_url)
    meraki.url_catalog['get_one'].update(query_one_url)
    meraki.url_catalog['create'] = create_url
    meraki.url_catalog['update'] = update_url
    meraki.url_catalog['delete'] = delete_url
    meraki.url_catalog['test'] = test_url
    meraki.url_catalog['test_status'] = test_status_url

    org_id = meraki.params['org_id']
    if org_id is None:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = meraki.params['net_id']
    if net_id is None:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(net_name=meraki.params['net_name'],
                                   data=nets)
    webhook_id = meraki.params['webhook_id']
    if webhook_id is None and meraki.params['name']:
        webhooks = get_all_webhooks(meraki, net_id)
        webhook_id = get_webhook_id(meraki.params['name'], webhooks)

    if meraki.params['state'] == 'present' and meraki.params['test'] is None:
        payload = {
            'name': meraki.params['name'],
            'url': meraki.params['url'],
            'sharedSecret': meraki.params['shared_secret']
        }

    if meraki.params['state'] == 'query':
        if webhook_id is not None:  # Query a single webhook
            path = meraki.construct_path('get_one',
                                         net_id=net_id,
                                         custom={'hookid': webhook_id})
            response = meraki.request(path, method='GET')
            if meraki.status == 200:
                meraki.result['data'] = response
        else:
            path = meraki.construct_path('get_all', net_id=net_id)
            response = meraki.request(path, method='GET')
            if meraki.status == 200:
                meraki.result['data'] = response
    elif meraki.params['state'] == 'present':
        if meraki.params['test'] == 'test':
            payload = {'url': meraki.params['url']}
            path = meraki.construct_path('test', net_id=net_id)
            response = meraki.request(path,
                                      method='POST',
                                      payload=json.dumps(payload))
            if meraki.status == 200:
                meraki.result['data'] = response
                meraki.exit_json(**meraki.result)
        elif meraki.params['test'] == 'status':
            if meraki.params['test_id'] is None:
                meraki.fail_json(
                    "test_id is required when querying test status.")
            path = meraki.construct_path(
                'test_status',
                net_id=net_id,
                custom={'testid': meraki.params['test_id']})
            response = meraki.request(path, method='GET')
            if meraki.status == 200:
                meraki.result['data'] = response
                meraki.exit_json(**meraki.result)
        if webhook_id is None:  # Make sure it is downloaded
            if webhooks is None:
                webhooks = get_all_webhooks(meraki, net_id)
            webhook_id = get_webhook_id(meraki.params['name'], webhooks)
        if webhook_id is None:  # Test to see if it needs to be created
            if meraki.check_mode is True:
                meraki.result['data'] = payload
                meraki.result['data']['networkId'] = net_id
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path('create', net_id=net_id)
            response = meraki.request(path,
                                      method='POST',
                                      payload=json.dumps(payload))
            if meraki.status == 201:
                meraki.result['data'] = response
                meraki.result['changed'] = True
        else:  # Need to update
            path = meraki.construct_path('get_one',
                                         net_id=net_id,
                                         custom={'hookid': webhook_id})
            original = meraki.request(path, method='GET')
            if meraki.is_update_required(original, payload):
                if meraki.check_mode is True:
                    meraki.generate_diff(original, payload)
                    original.update(payload)
                    meraki.result['data'] = original
                    meraki.result['changed'] = True
                    meraki.exit_json(**meraki.result)
                path = meraki.construct_path('update',
                                             net_id=net_id,
                                             custom={'hookid': webhook_id})
                response = meraki.request(path,
                                          method='PUT',
                                          payload=json.dumps(payload))
                if meraki.status == 200:
                    meraki.generate_diff(original, response)
                    meraki.result['data'] = response
                    meraki.result['changed'] = True
            else:
                meraki.result['data'] = original
    elif meraki.params['state'] == 'absent':
        if webhook_id is None:  # Make sure it is downloaded
            if webhooks is None:
                webhooks = get_all_webhooks(meraki, net_id)
            webhook_id = get_webhook_id(meraki.params['name'], webhooks)
            if webhook_id is None:
                meraki.fail_json(msg="There is no webhook with the name {0}".
                                 format(meraki.params['name']))
        if webhook_id:  # Test to see if it exists
            if meraki.module.check_mode is True:
                meraki.result['data'] = None
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path('delete',
                                         net_id=net_id,
                                         custom={'hookid': webhook_id})
            response = meraki.request(path, method='DELETE')
            if meraki.status == 204:
                meraki.result['data'] = response
                meraki.result['changed'] = True

    # 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)
def main():
    # define the available arguments/parameters that a user can pass to
    # the module

    urls_arg_spec = dict(
        url=dict(type='str'),
        comment=dict(type='str'),
    )

    files_arg_spec = dict(
        sha256=dict(type='str', aliases=['hash']),
        comment=dict(type='str'),
    )

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   choices=['absent', 'present', 'query'],
                   default='query'),
        net_name=dict(type='str', aliases=['network']),
        net_id=dict(type='str'),
        mode=dict(type='str', choices=['enabled', 'disabled']),
        allowed_urls=dict(type='list',
                          default=None,
                          elements='dict',
                          options=urls_arg_spec),
        allowed_files=dict(type='list',
                           default=None,
                           elements='dict',
                           options=files_arg_spec),
    )

    # 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='malware')

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

    query_url = {'malware': '/networks/{net_id}/appliance/security/malware'}
    update_url = {'malware': '/networks/{net_id}/appliance/security/malware'}

    meraki.url_catalog['get_one'].update(query_url)
    meraki.url_catalog['update'] = update_url

    org_id = meraki.params['org_id']
    if org_id is None:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = meraki.params['net_id']
    if net_id is None:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(net_name=meraki.params['net_name'],
                                   data=nets)

    # Check for argument completeness
    if meraki.params['state'] == 'present':
        if meraki.params['allowed_files'] is not None or meraki.params[
                'allowed_urls'] is not None:
            if meraki.params['mode'] is None:
                meraki.fail_json(
                    msg=
                    "mode must be set when allowed_files or allowed_urls is set."
                )

    # Assemble payload
    if meraki.params['state'] == 'present':
        payload = dict()
        if meraki.params['mode'] is not None:
            payload['mode'] = meraki.params['mode']
        if meraki.params['allowed_urls'] is not None:
            payload['allowedUrls'] = meraki.params['allowed_urls']
        if meraki.params['allowed_files'] is not None:
            payload['allowedFiles'] = meraki.params['allowed_files']

    if meraki.params['state'] == 'query':
        path = meraki.construct_path('get_one', net_id=net_id)
        data = meraki.request(path, method='GET')
        if meraki.status == 200:
            meraki.result['data'] = data
    elif meraki.params['state'] == 'present':
        path = meraki.construct_path('get_one', net_id=net_id)
        original = meraki.request(path, method='GET')
        if meraki.is_update_required(original, payload):
            if meraki.module.check_mode is True:
                meraki.generate_diff(original, payload)
                original.update(payload)
                meraki.result['data'] = original
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path('update', net_id=net_id)
            data = meraki.request(path,
                                  method='PUT',
                                  payload=json.dumps(payload))
            if meraki.status == 200:
                meraki.generate_diff(original, data)
                meraki.result['data'] = data
                meraki.result['changed'] = True
        else:
            meraki.result['data'] = original

    # 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)
Exemple #6
0
def main():
    # define the available arguments/parameters that a user can pass to
    # the module

    fixed_ip_arg_spec = dict(
        mac=dict(type='str'),
        ip=dict(type='str'),
        name=dict(type='str'),
    )

    reserved_ip_arg_spec = dict(
        start=dict(type='str'),
        end=dict(type='str'),
        comment=dict(type='str'),
    )

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   choices=['absent', 'present', 'query'],
                   default='query'),
        net_name=dict(type='str', aliases=['network']),
        net_id=dict(type='str'),
        vlan_id=dict(type='int'),
        name=dict(type='str', aliases=['vlan_name']),
        subnet=dict(type='str'),
        appliance_ip=dict(type='str'),
        fixed_ip_assignments=dict(type='list',
                                  default=None,
                                  elements='dict',
                                  options=fixed_ip_arg_spec),
        reserved_ip_range=dict(type='list',
                               default=None,
                               elements='dict',
                               options=reserved_ip_arg_spec),
        vpn_nat_subnet=dict(type='str'),
        dns_nameservers=dict(type='str'),
    )

    # 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='vlan')

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

    query_urls = {'vlan': '/networks/{net_id}/vlans'}
    query_url = {'vlan': '/networks/{net_id}/vlans/{vlan_id}'}
    create_url = {'vlan': '/networks/{net_id}/vlans'}
    update_url = {'vlan': '/networks/{net_id}/vlans/'}
    delete_url = {'vlan': '/networks/{net_id}/vlans/'}

    meraki.url_catalog['get_all'].update(query_urls)
    meraki.url_catalog['get_one'].update(query_url)
    meraki.url_catalog['create'] = create_url
    meraki.url_catalog['update'] = update_url
    meraki.url_catalog['delete'] = delete_url

    payload = None

    org_id = meraki.params['org_id']
    if org_id is None:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = meraki.params['net_id']
    if net_id is None:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(net_name=meraki.params['net_name'],
                                   data=nets)

    if meraki.params['state'] == 'query':
        if not meraki.params['vlan_id']:
            meraki.result['data'] = get_vlans(meraki, net_id)
        else:
            path = meraki.construct_path(
                'get_one',
                net_id=net_id,
                custom={'vlan_id': meraki.params['vlan_id']})
            response = meraki.request(path, method='GET')
            meraki.result['data'] = response
    elif meraki.params['state'] == 'present':
        payload = {
            'id': meraki.params['vlan_id'],
            'name': meraki.params['name'],
            'subnet': meraki.params['subnet'],
            'applianceIp': meraki.params['appliance_ip'],
        }
        if is_vlan_valid(meraki, net_id,
                         meraki.params['vlan_id']) is False:  # Create new VLAN
            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', net_id=net_id)
            response = meraki.request(path,
                                      method='POST',
                                      payload=json.dumps(payload))
            meraki.result['changed'] = True
            meraki.result['data'] = response
        else:  # Update existing VLAN
            path = meraki.construct_path(
                'get_one',
                net_id=net_id,
                custom={'vlan_id': meraki.params['vlan_id']})
            original = meraki.request(path, method='GET')
            if meraki.params['dns_nameservers']:
                if meraki.params['dns_nameservers'] not in ('opendns',
                                                            'google_dns',
                                                            'upstream_dns'):
                    payload['dnsNameservers'] = format_dns(
                        meraki.params['dns_nameservers'])
                else:
                    payload['dnsNameservers'] = meraki.params[
                        'dns_nameservers']
            if meraki.params['fixed_ip_assignments']:
                payload['fixedIpAssignments'] = fixed_ip_factory(
                    meraki, meraki.params['fixed_ip_assignments'])
            if meraki.params['reserved_ip_range']:
                payload['reservedIpRanges'] = meraki.params[
                    'reserved_ip_range']
            if meraki.params['vpn_nat_subnet']:
                payload['vpnNatSubnet'] = meraki.params['vpn_nat_subnet']
            ignored = ['networkId']
            if meraki.is_update_required(original,
                                         payload,
                                         optional_ignore=ignored):
                meraki.generate_diff(original, payload)
                if meraki.module.check_mode is True:
                    original.update(payload)
                    meraki.result['changed'] = True
                    meraki.result['data'] = original
                    meraki.exit_json(**meraki.result)
                path = meraki.construct_path('update', net_id=net_id) + str(
                    meraki.params['vlan_id'])
                response = meraki.request(path,
                                          method='PUT',
                                          payload=json.dumps(payload))
                meraki.result['changed'] = True
                meraki.result['data'] = response
                meraki.generate_diff(original, response)
            else:
                if meraki.module.check_mode is True:
                    meraki.result['data'] = original
                    meraki.exit_json(**meraki.result)
                meraki.result['data'] = original
    elif meraki.params['state'] == 'absent':
        if is_vlan_valid(meraki, net_id, meraki.params['vlan_id']):
            if meraki.module.check_mode is True:
                meraki.result['data'] = {}
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path('delete', net_id=net_id) + str(
                meraki.params['vlan_id'])
            response = meraki.request(path, 'DELETE')
            meraki.result['changed'] = True
            meraki.result['data'] = response

    # 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)
Exemple #7
0
def main():
    # define the available arguments/parameters that a user can pass to
    # the module

    application_arg_spec = dict(
        id=dict(type='str'),
        name=dict(type='str'),
    )

    rule_arg_spec = dict(
        policy=dict(type='str', choices=['deny'], default='deny'),
        type=dict(type='str',
                  choices=[
                      'application', 'application_category',
                      'blacklisted_countries', 'host', 'ip_range', 'port',
                      'whitelisted_countries'
                  ]),
        ip_range=dict(type='str'),
        application=dict(type='dict',
                         default=None,
                         options=application_arg_spec),
        host=dict(type='str'),
        port=dict(type='str'),
        countries=dict(type='list', elements='str'),
    )

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        state=dict(type='str', choices=['present', 'query'],
                   default='present'),
        net_name=dict(type='str'),
        net_id=dict(type='str'),
        rules=dict(type='list',
                   default=None,
                   elements='dict',
                   options=rule_arg_spec),
        categories=dict(type='bool'),
    )

    # 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='mx_l7_firewall')

    # check for argument completeness
    if meraki.params['rules']:
        for rule in meraki.params['rules']:
            if rule['type'] == 'application' and rule['application'] is None:
                meraki.fail_json(
                    msg=
                    "application argument is required when type is application."
                )
            elif rule['type'] == 'application_category' and rule[
                    'application'] is None:
                meraki.fail_json(
                    msg=
                    "application argument is required when type is application_category."
                )
            elif rule['type'] == 'blacklisted_countries' and rule[
                    'countries'] is None:
                meraki.fail_json(
                    msg=
                    "countries argument is required when type is blacklisted_countries."
                )
            elif rule['type'] == 'host' and rule['host'] is None:
                meraki.fail_json(
                    msg="host argument is required when type is host.")
            elif rule['type'] == 'port' and rule['port'] is None:
                meraki.fail_json(
                    msg="port argument is required when type is port.")
            elif rule['type'] == 'whitelisted_countries' and rule[
                    'countries'] is None:
                meraki.fail_json(
                    msg=
                    "countries argument is required when type is whitelisted_countries."
                )

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

    query_urls = {'mx_l7_firewall': '/networks/{net_id}/l7FirewallRules/'}
    query_category_urls = {
        'mx_l7_firewall':
        '/networks/{net_id}/l7FirewallRules/applicationCategories'
    }
    update_urls = {'mx_l7_firewall': '/networks/{net_id}/l7FirewallRules/'}

    meraki.url_catalog['get_all'].update(query_urls)
    meraki.url_catalog['get_categories'] = (query_category_urls)
    meraki.url_catalog['update'] = update_urls

    payload = None

    # manipulate or modify the state as needed (this is going to be the
    # part where your module will do what it needs to do)
    org_id = meraki.params['org_id']
    orgs = None
    if org_id is None:
        orgs = meraki.get_orgs()
        for org in orgs:
            if org['name'] == meraki.params['org_name']:
                org_id = org['id']
    net_id = meraki.params['net_id']
    if net_id is None:
        if orgs is None:
            orgs = meraki.get_orgs()
        net_id = meraki.get_net_id(net_name=meraki.params['net_name'],
                                   data=meraki.get_nets(org_id=org_id))

    if meraki.params['state'] == 'query':
        if meraki.params['categories'] is True:  # Output only applications
            meraki.result['data'] = get_applications(meraki, net_id)
        else:
            meraki.result['data'] = restructure_response(
                get_rules(meraki, net_id))
    elif meraki.params['state'] == 'present':
        rules = get_rules(meraki, net_id)
        path = meraki.construct_path('get_all', net_id=net_id)
        if meraki.params['rules']:
            payload = {'rules': []}
            for rule in meraki.params['rules']:
                payload['rules'].append(assemble_payload(meraki, net_id, rule))
        else:
            payload = dict()
        '''
        The rename_* functions are needed because the key is id and
        is_update_required() by default ignores id.
        '''
        rules = rename_id_to_appid(rules)
        payload = rename_id_to_appid(payload)
        if meraki.is_update_required(rules, payload):
            rules = rename_appid_to_id(rules)
            payload = rename_appid_to_id(payload)
            if meraki.module.check_mode is True:
                response = restructure_response(payload)
                meraki.generate_diff(restructure_response(rules), response)
                meraki.result['data'] = response
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            response = meraki.request(path,
                                      method='PUT',
                                      payload=json.dumps(payload))
            response = restructure_response(response)
            if meraki.status == 200:
                meraki.generate_diff(restructure_response(rules), response)
                meraki.result['data'] = response
                meraki.result['changed'] = True
        else:
            rules = rename_appid_to_id(rules)
            payload = rename_appid_to_id(payload)
            if meraki.module.check_mode is True:
                meraki.result['data'] = rules
                meraki.result['changed'] = False
                meraki.exit_json(**meraki.result)
            meraki.result['data'] = 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)
Exemple #8
0
def main():

    # define the available arguments/parameters that a user can pass to
    # the module

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        net_id=dict(type='str'),
        net_name=dict(type='str', aliases=['network']),
        state=dict(type='str', default='present', choices=['query',
                                                           'present']),
        service=dict(type='str', default=None, choices=['ICMP', 'SNMP',
                                                        'web']),
        access=dict(type='str',
                    choices=['blocked', 'restricted', 'unrestricted']),
        allowed_ips=dict(type='list', elements='str'),
    )

    mutually_exclusive = [('net_name', 'net_id')]

    # 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,
                           mutually_exclusive=mutually_exclusive)

    meraki = MerakiModule(module, function='firewalled_services')
    module.params['follow_redirects'] = 'all'

    net_services_urls = {
        'firewalled_services': '/networks/{net_id}/firewalledServices'
    }
    services_urls = {
        'firewalled_services':
        '/networks/{net_id}/firewalledServices/{service}'
    }

    meraki.url_catalog['network_services'] = net_services_urls
    meraki.url_catalog['service'] = services_urls

    # manipulate or modify the state as needed (this is going to be the
    # part where your module will do what it needs to do)

    org_id = meraki.params['org_id']
    if not org_id:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = meraki.params['net_id']
    if net_id is None:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(org_id,
                                   meraki.params['net_name'],
                                   data=nets)

    if meraki.params['state'] == 'present':
        if meraki.params['access'] != 'restricted' and meraki.params[
                'allowed_ips'] is not None:
            meraki.fail_json(
                msg="allowed_ips is only allowed when access is restricted.")
        payload = {'access': meraki.params['access']}
        if meraki.params['access'] == 'restricted':
            payload['allowedIps'] = meraki.params['allowed_ips']

    if meraki.params['state'] == 'query':
        if meraki.params['service'] is None:
            path = meraki.construct_path('network_services', net_id=net_id)
            response = meraki.request(path, method='GET')
            meraki.result['data'] = response
            meraki.exit_json(**meraki.result)
        else:
            path = meraki.construct_path(
                'service',
                net_id=net_id,
                custom={'service': meraki.params['service']})
            response = meraki.request(path, method='GET')
            meraki.result['data'] = response
            meraki.exit_json(**meraki.result)
    elif meraki.params['state'] == 'present':
        path = meraki.construct_path(
            'service',
            net_id=net_id,
            custom={'service': meraki.params['service']})
        original = meraki.request(path, method='GET')
        if meraki.is_update_required(original,
                                     payload,
                                     optional_ignore=['service']):
            if meraki.check_mode is True:
                diff_payload = {
                    'service': meraki.params['service']
                }  # Need to add service as it's not in payload
                diff_payload.update(payload)
                meraki.generate_diff(original, diff_payload)
                original.update(payload)
                meraki.result['data'] = original
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path(
                'service',
                net_id=net_id,
                custom={'service': meraki.params['service']})
            response = meraki.request(path,
                                      method='PUT',
                                      payload=json.dumps(payload))
            if meraki.status == 200:
                meraki.generate_diff(original, response)
                meraki.result['data'] = response
                meraki.result['changed'] = True
        else:
            meraki.result['data'] = original

    # 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)
Exemple #9
0
def main():

    # define the available arguments/parameters that a user can pass to
    # the module

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        net_id=dict(type='str'),
        net_name=dict(type='str', aliases=['name', 'network']),
        state=dict(type='str', choices=['present', 'query'], default='present'),
        number=dict(type='int', aliases=['port', 'port_id']),
        vlan=dict(type='int'),
        access_policy=dict(type='str', choices=['open', '8021x-radius', 'mac-radius', 'hybris-radius']),
        allowed_vlans=dict(type='str'),
        port_type=dict(type='str', choices=['access', 'trunk']),
        drop_untagged_traffic=dict(type='bool'),
        enabled=dict(type='bool'),
    )

    # 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='mx_l2_interface')
    module.params['follow_redirects'] = 'all'

    get_all_urls = {'mx_l2_interface': '/networks/{net_id}/appliance/ports'}
    get_one_urls = {'mx_l2_interface': '/networks/{net_id}/appliance/ports/{port_id}'}
    update_urls = {'mx_l2_interface': '/networks/{net_id}/appliance/ports/{port_id}'}
    meraki.url_catalog['query_all'] = get_all_urls
    meraki.url_catalog['query_one'] = get_one_urls
    meraki.url_catalog['update'] = update_urls

    if meraki.params['net_name'] and meraki.params['net_id']:
        meraki.fail_json(msg='net_name and net_id are mutually exclusive.')
    if meraki.params['port_type'] == 'access':
        if meraki.params['allowed_vlans'] is not None:
            meraki.meraki.fail_json(msg='allowed_vlans is mutually exclusive with port type trunk.')

    org_id = meraki.params['org_id']
    if not org_id:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = meraki.params['net_id']
    if net_id is None:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(org_id, meraki.params['net_name'], data=nets)

    if meraki.params['state'] == 'query':
        if meraki.params['number'] is not None:
            path = meraki.construct_path('query_one', net_id=net_id, custom={'port_id': meraki.params['number']})
        else:
            path = meraki.construct_path('query_all', net_id=net_id)
        response = meraki.request(path, method='GET')
        meraki.result['data'] = response
        meraki.exit_json(**meraki.result)
    elif meraki.params['state'] == 'present':
        path = meraki.construct_path('query_one', net_id=net_id, custom={'port_id': meraki.params['number']})
        original = meraki.request(path, method='GET')
        payload = construct_payload(meraki)
        if meraki.is_update_required(original, payload):
            meraki.generate_diff(original, payload)
            if meraki.check_mode is True:
                original.update(payload)
                meraki.result['data'] = original
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
            path = meraki.construct_path('update', net_id=net_id, custom={'port_id': meraki.params['number']})
            response = meraki.request(path, method='PUT', payload=json.dumps(payload))
            if meraki.status == 200:
                meraki.result['data'] = response
                meraki.result['changed'] = True
                meraki.exit_json(**meraki.result)
        else:
            meraki.result['data'] = original
            meraki.exit_json(**meraki.result)

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