예제 #1
0
def main():
    helper = get_connection(
        vsys=True,
        with_classic_provider_spec=True,
        panorama_error='Panorama is not supported for this module.',
        argument_spec=dict(
            tags=dict(type='list'),
            ips=dict(type='list')
        )
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        required_one_of=helper.required_one_of
    )

    tags = module.params['tags']
    ips = module.params['ips']

    device = helper.get_pandevice_parent(module)

    try:
        registered_ips = device.userid.get_registered_ip(tags=tags, ip=ips)

    except PanDeviceError as e:
        module.fail_json(msg='Failed get_registered_ip: {0}'.format(e))

    module.exit_json(changed=False, results=registered_ips)
def main():
    helper = get_connection(
        template=True,
        template_stack=True,
        with_classic_provider_spec=True,
        argument_spec=dict(name=dict(), ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    name = module.params['name']
    if name is None:
        try:
            listing = VirtualRouter.refreshall(parent)
        except PanDeviceError as e:
            module.fail_json(msg='Failed refreshall: {0}'.format(e))

        vrlist = helper.to_module_dict(listing)
        module.exit_json(changed=False, vrlist=vrlist)

    vr = VirtualRouter(name)
    parent.add(vr)
    try:
        vr.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    spec = helper.to_module_dict(vr)
    module.exit_json(changed=False, spec=spec)
예제 #3
0
def main():
    helper = get_connection(
        template=True,
        template_stack=True,
        with_state=True,
        with_classic_provider_spec=True,
        argument_spec=setup_args(),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify libs, initialize pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    vr = VirtualRouter(module.params['vr_name'])
    parent.add(vr)
    try:
        vr.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    bgp = vr.find('', Bgp)
    if bgp is None:
        module.fail_json(msg='BGP is not configured for virtual router "{0}"'.
                         format(vr.name))

    listing = bgp.findall(BgpDampeningProfile)
    spec = {
        'name':
        module.params['name'],
        'enable':
        module.params['enable'],
        'cutoff':
        module.params['cutoff'],
        'reuse':
        module.params['reuse'],
        'max_hold_time':
        module.params['max_hold_time'],
        'decay_half_life_reachable':
        module.params['decay_half_life_reachable'],
        'decay_half_life_unreachable':
        module.params['decay_half_life_unreachable'],
    }
    obj = BgpDampeningProfile(**spec)
    bgp.add(obj)

    # Apply the requested state.
    changed = helper.apply_state(obj, listing, module)

    # Optional commit.
    if changed and module.params['commit']:
        helper.commit(module)

    module.exit_json(changed=changed, msg='done')
def main():
    helper = get_connection(
        vsys_shared=True,
        device_group=True,
        with_state=True,
        with_classic_provider_spec=True,
        min_pandevice_version=(0, 11, 1),
        min_panos_version=(8, 0, 0),
        argument_spec=dict(
            log_forwarding_profile=dict(required=True),
            name=dict(required=True),
            description=dict(),
            log_type=dict(default='traffic', choices=[
                'traffic', 'threat', 'wildfire',
                'url', 'data', 'gtp', 'tunnel', 'auth', 'sctp']),
            filter=dict(),
            send_to_panorama=dict(type='bool'),
            snmp_profiles=dict(type='list'),
            email_profiles=dict(type='list'),
            syslog_profiles=dict(type='list'),
            http_profiles=dict(type='list'),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    lfp = LogForwardingProfile(module.params['log_forwarding_profile'])
    parent.add(lfp)
    try:
        lfp.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    listing = lfp.findall(LogForwardingProfileMatchList)

    spec = {
        'name': module.params['name'],
        'description': module.params['description'],
        'log_type': module.params['log_type'],
        'filter': module.params['filter'],
        'send_to_panorama': module.params['send_to_panorama'],
        'snmp_profiles': module.params['snmp_profiles'],
        'email_profiles': module.params['email_profiles'],
        'syslog_profiles': module.params['syslog_profiles'],
        'http_profiles': module.params['http_profiles'],
    }
    obj = LogForwardingProfileMatchList(**spec)
    lfp.add(obj)

    changed = helper.apply_state(obj, listing, module)
    module.exit_json(changed=changed, msg='Done')
예제 #5
0
def main():
    helper = get_connection(
        vsys=True,
        device_group=True,
        with_classic_provider_spec=True,
        with_state=True,
        argument_spec=dict(
            name=dict(required=True),
            value=dict(),
            address_type=dict(default='ip-netmask',
                              choices=['ip-netmask', 'ip-range', 'fqdn']),
            description=dict(),
            tag=dict(type='list'),
            commit=dict(type='bool', default=True),
        ),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        required_one_of=helper.required_one_of,
        supports_check_mode=True,
    )

    # Verify libs are present, get parent object.
    parent = helper.get_pandevice_parent(module)

    # Object params.
    spec = {
        'name': module.params['name'],
        'value': module.params['value'],
        'type': module.params['address_type'],
        'description': module.params['description'],
        'tag': module.params['tag'],
    }

    # Other info.
    commit = module.params['commit']

    # Retrieve current info.
    try:
        listing = AddressObject.refreshall(parent, add=False)
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    # Build the object based on the user spec.
    obj = AddressObject(**spec)
    parent.add(obj)

    # Apply the state.
    changed = helper.apply_state(obj, listing, module)

    # Commit.
    if commit and changed:
        helper.commit(module)

    # Done.
    module.exit_json(changed=changed)
예제 #6
0
def main():
    helper = get_connection(
        vsys=True,
        template=True,
        template_stack=True,
        with_state=True,
        with_classic_provider_spec=True,
        argument_spec=dict(
            zone=dict(required=True),
            mode=dict(choices=[
                'tap', 'virtual-wire', 'layer2', 'layer3', 'external'
            ],
                      default='layer3'),
            interface=dict(type='list'),
            zone_profile=dict(),
            log_setting=dict(),
            enable_userid=dict(type='bool', default=False),
            include_acl=dict(type='list'),
            exclude_acl=dict(type='list'),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    # Set the Zone object params
    zone_spec = {
        'name': module.params['zone'],
        'mode': module.params['mode'],
        'interface': module.params['interface'],
        'zone_profile': module.params['zone_profile'],
        'log_setting': module.params['log_setting'],
        'enable_user_identification': module.params['enable_userid'],
        'include_acl': module.params['include_acl'],
        'exclude_acl': module.params['exclude_acl']
    }

    # Retrieve the current list of zones
    try:
        zones = Zone.refreshall(parent, add=False)
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    # Build the zone and attach to the parent
    new_zone = Zone(**zone_spec)
    parent.add(new_zone)

    # Perform the requeseted action.
    changed = helper.apply_state(new_zone, zones, module)

    # Done!
    module.exit_json(changed=changed, msg='Done')
예제 #7
0
def main():
    name_params = ['name', 'name_regex']
    obj_types = {
        'address': objects.AddressObject,
        'address-group': objects.AddressGroup,
        'service': objects.ServiceObject,
        'service-group': objects.ServiceGroup,
        'tag': objects.Tag,
    }
    helper = get_connection(
        vsys=True,
        device_group=True,
        with_classic_provider_spec=True,
        required_one_of=[name_params, ],
        argument_spec=dict(
            name=dict(),
            name_regex=dict(),
            object_type=dict(default='address', choices=obj_types.keys()),
        ),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
        mutually_exclusive=[name_params, ],
    )

    parent = helper.get_pandevice_parent(module)

    object_type = module.params['object_type']
    obj_type = obj_types[object_type]

    try:
        obj_listing = obj_type.refreshall(parent)
    except PanDeviceError as e:
        module.fail_json(msg='Failed {0} refresh: {1}'.format(object_type, e))

    results = {}
    ans_objects = []
    if module.params['name'] is not None:
        obj = parent.find(module.params['name'], obj_type)
        if obj:
            results = colorize(obj, object_type)
            ans_objects.append(results)
    else:
        try:
            matcher = re.compile(module.params['name_regex'])
        except Exception as e:
            module.fail_json(msg='Invalid regex: {0}'.format(e))

        for x in obj_listing:
            if matcher.search(x.uid) is not None:
                ans_objects.append(colorize(x, object_type))

    module.exit_json(changed=False, results=results, objects=ans_objects)
예제 #8
0
def main():
    helper = get_connection(
        vsys=True,
        device_group=True,
        with_state=True,
        with_classic_provider_spec=True,
        argument_spec=dict(pg_name=dict(required=True),
                           data_filtering=dict(),
                           file_blocking=dict(),
                           spyware=dict(),
                           url_filtering=dict(),
                           virus=dict(),
                           vulnerability=dict(),
                           wildfire=dict(),
                           commit=dict(type='bool', default=True)),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify libs are present, build the pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    # Other info.
    commit = module.params['commit']

    # Retrieve current profiles.
    try:
        listing = SecurityProfileGroup.refreshall(parent, add=False)
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    spec = {
        'name': module.params['pg_name'],
        'virus': module.params['virus'],
        'spyware': module.params['spyware'],
        'vulnerability': module.params['vulnerability'],
        'url_filtering': module.params['url_filtering'],
        'file_blocking': module.params['file_blocking'],
        'data_filtering': module.params['data_filtering'],
        'wildfire_analysis': module.params['wildfire'],
    }
    obj = SecurityProfileGroup(**spec)
    parent.add(obj)

    # Apply the state.
    changed = helper.apply_state(obj, listing, module)

    # Optional commit.
    if changed and commit:
        helper.commit(module)

    module.exit_json(changed=changed, msg='done')
def main():
    helper = get_connection(
        template=True,
        template_stack=True,
        with_state=True,
        with_classic_provider_spec=True,
        argument_spec=setup_args(),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    parent = helper.get_pandevice_parent(module)

    vr = VirtualRouter(module.params['vr_name'])
    parent.add(vr)
    try:
        vr.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    bgp = vr.find('', Bgp)
    if bgp is None:
        module.fail_json(
            msg='BGP is not configured on virtual router {0}'.format(vr.name))

    listing = bgp.findall(BgpPolicyConditionalAdvertisement)

    spec = {
        'name': module.params['name'],
        'enable': module.params['enable'],
        'used_by': module.params['used_by'],
    }
    obj = BgpPolicyConditionalAdvertisement(**spec)
    bgp.add(obj)

    # TODO(gfreeman) - Remove this in 2.12.
    for ansible_param in ('non_exist_filter', 'advertise_filter'):
        val = module.params[ansible_param]
        if val is not None:
            import pickle
            from base64 import b64decode
            module.deprecate('Param {0} is deprecated'.format(ansible_param),
                             '2.12')
            filter_obj = pickle.loads(b64decode(val))
            obj.add(filter_obj)

    changed = helper.apply_state(obj, listing, module)
    if changed and module.params['commit']:
        helper.commit(module)

    module.exit_json(changed=changed, msg='done')
예제 #10
0
def main():
    helper = get_connection(
        vsys_shared=True,
        device_group=True,
        with_state=True,
        with_classic_provider_spec=True,
        min_pandevice_version=(0, 11, 1),
        min_panos_version=(8, 0, 0),
        argument_spec=dict(
            http_profile=dict(required=True),
            name=dict(required=True),
            address=dict(required=True),
            protocol=dict(default='HTTPS', choices=['HTTP', 'HTTPS']),
            http_port=dict(type='int', default=443),
            tls_version=dict(choices=['1.0', '1.1', '1.2']),
            certificate_profile=dict(),
            http_method=dict(default='POST'),
            http_username=dict(),
            http_password=dict(no_log=True),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    sp = HttpServerProfile(module.params['http_profile'])
    parent.add(sp)
    try:
        sp.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    listing = sp.findall(HttpServer)

    spec = {
        'name': module.params['name'],
        'address': module.params['address'],
        'protocol': module.params['protocol'],
        'port': module.params['http_port'],
        'tls_version': module.params['tls_version'],
        'certificate_profile': module.params['certificate_profile'],
        'http_method': module.params['http_method'],
        'username': module.params['http_username'],
        'password': module.params['http_password'],
    }
    obj = HttpServer(**spec)
    sp.add(obj)

    changed = helper.apply_state(obj, listing, module)
    module.exit_json(changed=changed, msg='Done')
예제 #11
0
def main():
    helper = get_connection(
        template=True,
        template_stack=True,
        with_state=True,
        with_classic_provider_spec=True,
        argument_spec=setup_args(),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify libs are present, get pandevice parent.
    parent = helper.get_pandevice_parent(module)

    # Verify the virtual router is present.
    vr = VirtualRouter(module.params['vr_name'])
    parent.add(vr)
    try:
        vr.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    bgp = vr.find('', Bgp)
    if bgp is None:
        module.fail_json(msg='BGP is not configured for "{0}"'.format(vr.name))

    listing = bgp.findall(BgpPeerGroup)
    spec = {
        'name': module.params['name'],
        'enable': module.params['enable'],
        'aggregated_confed_as_path':
        module.params['aggregated_confed_as_path'],
        'soft_reset_with_stored_info':
        module.params['soft_reset_with_stored_info'],
        'type': module.params['type'],
        'export_nexthop': module.params['export_nexthop'],
        'import_nexthop': module.params['import_nexthop'],
        'remove_private_as': module.params['remove_private_as'],
    }
    obj = BgpPeerGroup(**spec)
    bgp.add(obj)

    # Apply the state.
    changed = helper.apply_state(obj, listing, module)

    # Optional commit.
    if changed and module.params['commit']:
        helper.commit(module)

    module.exit_json(changed=changed, msg='done')
예제 #12
0
def main():
    helper = get_connection(
        vsys_shared=True,
        device_group=True,
        with_state=True,
        with_classic_provider_spec=True,
        min_pandevice_version=(0, 11, 1),
        min_panos_version=(7, 1, 0),
        argument_spec=dict(
            syslog_profile=dict(required=True),
            name=dict(required=True),
            server=dict(required=True),
            transport=dict(default='UDP', choices=['UDP', 'TCP', 'SSL']),
            syslog_port=dict(type='int'),
            format=dict(default='BSD', choices=['BSD', 'IETF']),
            facility=dict(default='LOG_USER',
                          choices=[
                              'LOG_USER', 'LOG_LOCAL0', 'LOG_LOCAL1',
                              'LOG_LOCAL2', 'LOG_LOCAL3', 'LOG_LOCAL4',
                              'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7'
                          ]),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    sp = SyslogServerProfile(module.params['syslog_profile'])
    parent.add(sp)
    try:
        sp.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    listing = sp.findall(SyslogServer)

    spec = {
        'name': module.params['name'],
        'server': module.params['server'],
        'transport': module.params['transport'],
        'port': module.params['syslog_port'],
        'format': module.params['format'],
        'facility': module.params['facility'],
    }
    obj = SyslogServer(**spec)
    sp.add(obj)

    changed = helper.apply_state(obj, listing, module)
    module.exit_json(changed=changed, msg='Done')
예제 #13
0
def main():
    helper = get_connection(
        with_classic_provider_spec=True,
        argument_spec=dict(
            cmd=dict(default='set',
                     choices=[
                         'show', 'get', 'delete', 'set', 'edit', 'move',
                         'rename', 'clone', 'override'
                     ]),
            xpath=dict(required=True),
            element=dict(),
            where=dict(),
            dst=dict(),
            new_name=dict(),
            xpath_from=dict(),
            extra_qs=dict(),
        ),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    parent = helper.get_pandevice_parent(module)

    cmd = module.params['cmd']
    func = getattr(parent.xapi, cmd)

    kwargs = {
        'xpath': ''.join(module.params['xpath'].strip().split('\n')),
        'extra_qs': module.params['extra_qs'],
    }

    if cmd in ('set', 'edit', 'override'):
        kwargs['element'] = module.params['element'].strip()

    if cmd in ('move', ):
        kwargs['where'] = module.params['where']
        kwargs['dst'] = module.params['dst']

    if cmd in ('rename', 'clone'):
        kwargs['newname'] = module.params['new_name']

    if cmd in ('clone', ):
        kwargs['xpath_from'] = module.params['xpath_from']

    try:
        func(**kwargs)
    except PanDeviceError as e:
        module.fail_json(msg='{0}'.format(e))

    module.exit_json(changed=True)
def main():
    helper = get_connection(
        vsys=True,
        device_group=True,
        rulebase=True,
        with_classic_provider_spec=True,
        error_on_shared=True,
        argument_spec=dict(
            rule_name=dict(),
        ),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    parent = helper.get_pandevice_parent(module)

    name = module.params['rule_name']
    if name is None:
        try:
            listing = SecurityRule.refreshall(parent, name_only=True)
        except PanDeviceError as e:
            module.fail_json(msg='Failed refreshall: {0}'.format(e))
        module.exit_json(changed=False, rules=[x.name for x in listing])

    rule = SecurityRule(name)
    parent.add(rule)
    try:
        rule.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh for "{0}": {1}'.format(name, e))

    spec = rule.about()

    renames = (
        ('name', 'rule_name'),
        ('fromzone', 'source_zone'),
        ('tozone', 'destination_zone'),
        ('source', 'source_ip'),
        ('destination', 'destination_ip'),
        ('type', 'rule_type'),
        ('tag', 'tag_name'),
        ('group', 'group_profile'),
        ('virus', 'antivirus'),
    )
    for pandevice_param, ansible_param in renames:
        spec[ansible_param] = spec[pandevice_param]
        del(spec[pandevice_param])

    module.exit_json(changed=False, spec=spec)
예제 #15
0
def main():
    helper = get_connection(
        template=True,
        template_stack=True,
        with_state=True,
        with_classic_provider_spec=True,
        argument_spec=setup_args(),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    parent = helper.get_pandevice_parent(module)

    vr = VirtualRouter(module.params['vr_name'])
    parent.add(vr)
    try:
        vr.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    bgp = vr.find('', Bgp)
    if bgp is None:
        module.fail_json(msg='BGP is not configured for "{0}"'.format(vr.name))

    spec = {
        'name': module.params['name'],
        'enable': module.params['enable'],
        'address_family_identifier':
        module.params['address_family_identifier'],
        'route_table': module.params['route_table'],
        'set_origin': module.params['set_origin'],
        'set_med': module.params['set_med'],
        'set_local_preference': module.params['set_local_preference'],
        'set_as_path_limit': module.params['set_as_path_limit'],
        'set_community': module.params['set_community'],
        'set_extended_community': module.params['set_extended_community'],
        'metric': module.params['metric'],
    }

    listing = bgp.findall(BgpRedistributionRule)
    obj = BgpRedistributionRule(**spec)
    bgp.add(obj)

    changed = helper.apply_state(obj, listing, module)

    if changed and module.params['commit']:
        helper.commit(module)

    module.exit_json(changed=changed, msg='done')
예제 #16
0
def main():
    helper = get_connection(
        template=True,
        template_stack=True,
        with_state=True,
        with_classic_provider_spec=True,
        argument_spec=setup_args(),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    parent = helper.get_pandevice_parent(module)

    vr = VirtualRouter(module.params['vr_name'])
    parent.add(vr)
    try:
        vr.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    spec = {
        'name': module.params['name'],
        'priority': module.params['priority'],
        'action': module.params['action'],
        'filter_type': module.params['filter_type'],
        'filter_interface': module.params['filter_interface'],
        'filter_destination': module.params['filter_destination'],
        'filter_nexthop': module.params['filter_nexthop'],
        'ospf_filter_pathtype': module.params['ospf_filter_pathtype'],
        'ospf_filter_area': module.params['ospf_filter_area'],
        'ospf_filter_tag': module.params['ospf_filter_tag'],
        'bgp_filter_community': module.params['bgp_filter_community'],
        'bgp_filter_extended_community': module.params['bgp_filter_extended_community'],
    }

    if module.params['type'] == 'ipv4':
        obj = RedistributionProfile(**spec)
    else:
        obj = RedistributionProfileIPv6(**spec)

    listing = vr.findall(obj.__class__)
    vr.add(obj)

    changed = helper.apply_state(obj, listing, module)
    if changed and module.params['commit']:
        helper.commit(module)

    module.exit_json(changed=changed, msg='done')
예제 #17
0
def main():
    helper = get_connection(
        with_classic_provider_spec=True,
        argument_spec=dict(
            cmd=dict(required=True),
            cmd_is_xml=dict(default=False, type='bool'),
        ),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    if not HAS_LIB:
        module.fail_json(msg='Missing required libraries.')

    parent = helper.get_pandevice_parent(module)

    cmd = module.params['cmd']
    cmd_is_xml = module.params['cmd_is_xml']

    changed = True
    safecmd = ['diff', 'show']

    xml_output = ''
    try:
        xml_output = parent.op(cmd, xml=True, cmd_xml=(not cmd_is_xml))
    except PanDeviceError as e1:
        if cmd_is_xml:
            module.fail_json(
                msg='Failed to run XML command : {0} : {1}'.format(cmd, e1))
        tokens = cmd.split()
        tokens[-1] = '"{0}"'.format(tokens[-1])
        cmd2 = ' '.join(tokens)
        try:
            xml_output = parent.op(cmd2, xml=True)
        except PanDeviceError as e2:
            module.fail_json(
                msg='Failed to run command : {0} : {1}'.format(cmd2, e2))

        if tokens[0] in safecmd:
            changed = False

    obj_dict = xmltodict.parse(xml_output)
    json_output = json.dumps(obj_dict)

    module.exit_json(changed=changed,
                     msg="Done",
                     stdout=json_output,
                     stdout_xml=xml_output)
예제 #18
0
def main():
    helper = get_connection(with_classic_provider_spec=True,
                            argument_spec=dict(version=dict(type='str',
                                                            required=True),
                                               sync_to_peer=dict(
                                                   type='bool', default=False),
                                               download=dict(type='bool',
                                                             default=True),
                                               install=dict(type='bool',
                                                            default=True),
                                               restart=dict(type='bool',
                                                            default=False)))

    module = AnsibleModule(argument_spec=helper.argument_spec,
                           required_one_of=helper.required_one_of,
                           supports_check_mode=True)

    # Verify libs are present, get parent object.
    device = helper.get_pandevice_parent(module)

    # Module params.
    version = module.params['version']
    sync_to_peer = module.params['sync_to_peer']
    download = module.params['download']
    install = module.params['install']
    restart = module.params['restart']

    changed = False

    try:
        device.software.check()

        if PanOSVersion(version) != PanOSVersion(device.version):

            if not module.check_mode:
                if download:
                    device.software.download(version,
                                             sync_to_peer=sync_to_peer,
                                             sync=True)

                if install:
                    device.software.install(version, sync=True)

                if restart:
                    device.restart()

            changed = True

    except PanDeviceError as e:
        module.fail_json(msg=e.message)

    module.exit_json(changed=changed, version=version)
예제 #19
0
def main():
    helper = get_connection(
        template=True,
        template_stack=True,
        with_state=True,
        with_classic_provider_spec=True,
        argument_spec=setup_args(),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    parent = helper.get_pandevice_parent(module)

    # TODO(gfreeman) - removed in 2.12
    if module.params['replace'] is not None:
        module.deprecate('Param "replace" is deprecated; please remove it from your playbooks', '2.12')

    vr = VirtualRouter(module.params['vr_name'])
    parent.add(vr)
    try:
        vr.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    bgp = vr.find('', Bgp)
    if bgp is None:
        module.fail_json(msg='BGP config not yet added to {0}'.format(vr.name))
    parent = bgp

    listing = parent.findall(BgpAuthProfile)

    commit = module.params['commit']

    spec = {
        'name': module.params['name'],
        'secret': module.params['secret'],
    }
    obj = BgpAuthProfile(**spec)
    parent.add(obj)

    changed = helper.apply_state(obj, listing, module)

    if commit and changed:
        helper.commit(module)

    module.exit_json(changed=changed, msg='done')
예제 #20
0
def main():
    helper = get_connection(
        vsys_shared=True,
        device_group=True,
        with_state=True,
        with_classic_provider_spec=True,
        min_pandevice_version=(0, 11, 1),
        min_panos_version=(7, 1, 0),
        argument_spec=dict(
            snmp_profile=dict(required=True),
            name=dict(required=True),
            manager=dict(),
            user=dict(),
            engine_id=dict(),
            auth_password=dict(no_log=True),
            priv_password=dict(no_log=True),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    sp = SnmpServerProfile(module.params['snmp_profile'])
    parent.add(sp)
    try:
        sp.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    listing = sp.findall(SnmpV3Server)

    spec = {
        'name': module.params['name'],
        'manager': module.params['manager'],
        'user': module.params['user'],
        'engine_id': module.params['engine_id'],
        'auth_password': module.params['auth_password'],
        'priv_password': module.params['priv_password'],
    }
    obj = SnmpV3Server(**spec)
    sp.add(obj)

    changed = helper.apply_state(obj, listing, module)
    module.exit_json(changed=changed, msg='Done')
예제 #21
0
def main():
    helper = get_connection(
        vsys_shared=True,
        device_group=True,
        with_state=True,
        with_classic_provider_spec=True,
        min_pandevice_version=(0, 11, 1),
        min_panos_version=(7, 1, 0),
        argument_spec=dict(
            email_profile=dict(required=True),
            name=dict(required=True),
            display_name=dict(),
            from_email=dict(),
            to_email=dict(),
            also_to_email=dict(),
            email_gateway=dict(),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    sp = EmailServerProfile(module.params['email_profile'])
    parent.add(sp)
    try:
        sp.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    listing = sp.findall(EmailServer)

    spec = {
        'name': module.params['name'],
        'display_name': module.params['display_name'],
        'from': module.params['from_email'],
        'to': module.params['to_email'],
        'also_to': module.params['also_to_email'],
        'email_gateway': module.params['email_gateway'],
    }
    obj = EmailServer(**spec)
    sp.add(obj)

    changed = helper.apply_state(obj, listing, module)
    module.exit_json(changed=changed, msg='Done')
예제 #22
0
def main():
    helper = get_connection(
        vsys=True,
        with_classic_provider_spec=True,
        with_state=True,
        panorama_error='Panorama is not supported for this module.',
        argument_spec=dict(
            ips=dict(type='list', required=True),
            tags=dict(type='list', required=True),
        ))

    module = AnsibleModule(argument_spec=helper.argument_spec,
                           required_one_of=helper.required_one_of,
                           supports_check_mode=True)

    # Verify libs are present, get parent object.
    device = helper.get_pandevice_parent(module)

    ips = module.params['ips']
    tags = module.params['tags']
    state = module.params['state']

    changed = False

    try:
        registered_ips = device.userid.get_registered_ip(tags=tags)

        if state == 'present':
            # Check to see if IPs actually need to be registered.
            to_add = set(ips) - set(registered_ips.keys())
            if to_add:
                if not module.check_mode:
                    device.userid.register(ips, tags=tags)
                changed = True

        elif state == 'absent':
            # Check to see if IPs actually need to be unregistered.
            to_remove = set(ips) & set(registered_ips.keys())
            if to_remove:
                if not module.check_mode:
                    device.userid.unregister(to_remove, tags=tags)
                changed = True

        results = device.userid.get_registered_ip(ips)

    except PanDeviceError as e:
        module.fail_json(msg='Failed register/unregister: {0}'.format(e))

    module.exit_json(changed=changed, results=results)
예제 #23
0
def main():
    helper = get_connection(
        vsys=True,
        template=True,
        template_stack=True,
        with_classic_provider_spec=True,
        argument_spec=dict(
            name=dict(),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    renames = (
        ('name', 'zone'),
        ('enable_user_identification', 'enable_userid'),
    )

    name = module.params['name']
    if name is None:
        try:
            listing = Zone.refreshall(parent)
        except PanDeviceError as e:
            module.fail_json(msg='Failed refreshall: {0}'.format(e))

        zones = helper.to_module_dict(listing, renames)
        module.exit_json(changed=False, zones=zones)

    zone = Zone(name)
    parent.add(zone)
    try:
        zone.refresh()
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    spec = helper.to_module_dict(zone, renames)
    module.exit_json(changed=False, spec=spec)
예제 #24
0
def main():
    helper = get_connection(
        with_classic_provider_spec=True,
        argument_spec=dict(),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    parent = helper.get_pandevice_parent(module)

    try:
        parent.restart()
    except PanDeviceError as e:
        module.fail_json(msg='Failed to restart: {0}'.format(e))

    module.exit_json(changed=True, msg="done")
예제 #25
0
def main():
    helper = get_connection(vsys=True,
                            device_group=True,
                            with_classic_provider_spec=True,
                            with_state=True,
                            argument_spec=dict(name=dict(type='str',
                                                         required=True),
                                               color=dict(type='str',
                                                          choices=COLOR_NAMES),
                                               comments=dict(type='str'),
                                               commit=dict(type='bool',
                                                           default=True)))

    module = AnsibleModule(argument_spec=helper.argument_spec,
                           required_one_of=helper.required_one_of,
                           supports_check_mode=True)

    parent = helper.get_pandevice_parent(module)

    spec = {
        'name': module.params['name'],
        'color': Tag.color_code(module.params['color']),
        'comments': module.params['comments']
    }

    commit = module.params['commit']

    try:
        listing = Tag.refreshall(parent, add=False)
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    obj = Tag(**spec)
    parent.add(obj)

    changed = helper.apply_state(obj, listing, module)

    if commit and changed:
        helper.commit(module)

    module.exit_json(changed=changed)
예제 #26
0
def main():
    helper = get_connection(
        with_classic_provider_spec=True,
        argument_spec=dict(initial_delay=dict(default=0, type='int'),
                           timeout=dict(default=60, type='int'),
                           interval=dict(default=0, type='int')),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    # Optional delay before performing readiness checks.
    if module.params['initial_delay']:
        time.sleep(module.params['initial_delay'])

    timeout = module.params['timeout']
    interval = module.params['interval']
    end_time = time.time() + timeout

    parent = helper.get_pandevice_parent(module, timeout)

    # TODO(gfreeman) - consider param for "show chassis-ready".
    while True:
        try:
            ans = parent.op(cmd="show jobs all")
        except PanDeviceError:
            pass
        else:
            jobs = ans.findall('.//job')
            if check_jobs(jobs):
                break

        if time.time() > end_time:
            module.fail_json(msg='Timeout')

        time.sleep(interval)

    module.exit_json(changed=True, msg="done")
def main():
    helper = get_connection(
        device_group=True,
        with_classic_provider_spec=True,
        min_pandevice_version=(0, 12, 0),
        argument_spec=dict(
            include_template=dict(type='bool'),
            admins=dict(type='list'),
            # TODO(gfreeman) - remove in 2.12.
            devicegroup=dict(),
        ),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    changed = False

    # TODO(gfreeman) - remove in 2.12
    if module.params['devicegroup'] is not None:
        module.deprecate(
            'Param "devicegroup" is deprecated; use "device_group"', '2.12')
        if module.params['device_group'] is not None:
            msg = [
                'Both "devicegroup" and "device_group" specified',
                'please use one or the other.',
            ]
            module.fail_json(msg='; '.join(msg))
        module.params['device_group'] = module.params['devicegroup']

    helper.get_pandevice_parent(module)
    changed = helper.commit(
        module,
        include_template=module.params['include_template'],
        admins=module.params['admins'],
    )

    module.exit_json(changed=changed)
예제 #28
0
def main():
    helper = get_connection(
        with_state=True,
        with_classic_provider_spec=True,
        panorama_error='The user-id API is not supported on Panorama',
        argument_spec=dict(
            userid=dict(required=True),
            register_ip=dict(required=True),

            # TODO(gfreeman) - remove in the next role release.
            operation=dict(),
        ),
    )

    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    parent = helper.get_pandevice_parent(module)

    # TODO(gfreeman) - remove in the next role release.
    if module.params['operation'] is not None:
        module.fail_json(msg='Param "operation" is removed; use "state" instead')

    func = None
    prefix = ''
    if module.params['state'] == 'present':
        func = 'login'
    else:
        func = 'logout'
        prefix = 'un'

    # Apply the state.
    try:
        getattr(parent.userid, func)(module.params['userid'], module.params['register_ip'])
    except PanDeviceError as e:
        module.fail_json(msg='Failed to {0} {1}: {2}'.format(func, module.params['userid'], e))

    module.exit_json(msg="User '{0}' successfully {1}registered".format(module.params['userid'], prefix))
def main():
    helper = get_connection(
        vsys_shared=True,
        device_group=True,
        with_state=True,
        with_classic_provider_spec=True,
        min_pandevice_version=(0, 11, 1),
        min_panos_version=(8, 0, 0),
        argument_spec=dict(
            name=dict(required=True),
            description=dict(),
            enhanced_logging=dict(type='bool'),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    try:
        listing = LogForwardingProfile.refreshall(parent)
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    spec = {
        'name': module.params['name'],
        'description': module.params['description'],
        'enhanced_logging': module.params['enhanced_logging'],
    }
    obj = LogForwardingProfile(**spec)
    parent.add(obj)

    changed = helper.apply_state(obj, listing, module)
    module.exit_json(changed=changed, msg='Done')
예제 #30
0
def main():
    helper = get_connection(
        with_classic_provider_spec=True,
        argument_spec={},
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=False,
        required_one_of=helper.required_one_of,
    )

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    # Done.
    if helper.device.parent is not None:
        # Firewall via Panorama connections.
        api_key = helper.device.parent.api_key
    else:
        # Standard.
        api_key = helper.device.api_key

    module.exit_json(changed=False, msg="Done", api_key=api_key)