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)
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, diff = helper.apply_state(obj, listing, module)

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

    module.exit_json(changed=changed, diff=diff, 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:
            module.deprecate(
                "Param {0} is deprecated".format(ansible_param),
                version="3.0.0",
                collection_name="paloaltonetworks.panos",
            )
            filter_obj = pickle.loads(b64decode(val))
            obj.add(filter_obj)

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

    module.exit_json(changed=changed, diff=diff, msg="done")
Ejemplo n.º 4
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',
            version="3.0.0",
            collection_name="paloaltonetworks.panos",
        )

    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, diff = helper.apply_state(obj, listing, module)

    if commit and changed:
        helper.commit(module)

    module.exit_json(changed=changed, diff=diff, msg="done")
Ejemplo n.º 5
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, diff = helper.apply_state(obj, listing, module)

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

    module.exit_json(changed=changed, diff=diff, 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 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, diff = helper.apply_state(obj, listing, module)

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

    module.exit_json(changed=changed, diff=diff, 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))

    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, diff = helper.apply_state(obj, listing, module)
    if changed and module.params["commit"]:
        helper.commit(module)

    module.exit_json(changed=changed, diff=diff, 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)

    spec = {
        'name': module.params['name'],
        'enable': module.params['enable'],
        'prefix': module.params['prefix'],
        'summary': module.params['summary'],
        'as_set': module.params['as_set'],
        'attr_local_preference': module.params['attr_local_preference'],
        'attr_med': module.params['attr_med'],
        'attr_weight': module.params['attr_weight'],
        'attr_nexthop': module.params['attr_nexthop'],
        'attr_origin': module.params['attr_origin'],
        'attr_as_path_limit': module.params['attr_as_path_limit'],
        'attr_as_path_type': module.params['attr_as_path_type'],
        'attr_as_path_prepend_times': module.params['attr_as_path_prepend_times'],
        'attr_community_type': module.params['attr_community_type'],
        'attr_community_argument': module.params['attr_community_argument'],
        'attr_extended_community_type': module.params['attr_extended_community_type'],
        'attr_extended_community_argument': module.params['attr_extended_community_argument'],
    }
    obj = BgpPolicyAggregationAddress(**spec)

    vr_name = module.params['vr_name']
    commit = module.params['commit']

    vr = VirtualRouter(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(BgpPolicyAggregationAddress)
    bgp.add(obj)

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

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

    module.exit_json(changed=changed, diff=diff, msg='done')
Ejemplo n.º 9
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, setup 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 "{0}".'.format(vr.name))

    group = bgp.find(module.params['peer_group'], BgpPeerGroup)
    if group is None:
        module.fail_json(msg='BGP peer group does not exist: {0}.'.format(
            module.params['peer_group']))

    listing = group.findall(BgpPeer)
    spec = {
        'name':
        module.params['name'],
        'enable':
        module.params['enable'],
        'peer_as':
        module.params['peer_as'],
        'enable_mp_bgp':
        module.params['enable_mp_bgp'],
        'address_family_identifier':
        module.params['address_family_identifier'],
        'subsequent_address_unicast':
        module.params['subsequent_address_unicast'],
        'subsequent_address_multicast':
        module.params['subsequent_address_multicast'],
        'local_interface':
        module.params['local_interface'],
        'local_interface_ip':
        module.params['local_interface_ip'],
        'peer_address_ip':
        module.params['peer_address_ip'],
        'connection_authentication':
        module.params['connection_authentication'],
        'connection_keep_alive_interval':
        module.params['connection_keep_alive_interval'],
        'connection_min_route_adv_interval':
        module.params['connection_min_route_adv_interval'],
        'connection_multihop':
        module.params['connection_multihop'],
        'connection_open_delay_time':
        module.params['connection_open_delay_time'],
        'connection_hold_time':
        module.params['connection_hold_time'],
        'connection_idle_hold_time':
        module.params['connection_idle_hold_time'],
        'connection_incoming_allow':
        module.params['connection_incoming_allow'],
        'connection_outgoing_allow':
        module.params['connection_outgoing_allow'],
        'connection_incoming_remote_port':
        module.params['connection_incoming_remote_port'],
        'connection_outgoing_local_port':
        module.params['connection_outgoing_local_port'],
        'enable_sender_side_loop_detection':
        module.params['enable_sender_side_loop_detection'],
        'reflector_client':
        module.params['reflector_client'],
        'peering_type':
        module.params['peering_type'],
        'max_prefixes':
        module.params['max_prefixes'],
        'bfd_profile':
        module.params['bfd_profile'],
    }
    obj = BgpPeer(**spec)
    group.add(obj)

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

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

    module.exit_json(changed=changed, diff=diff, msg='done')
Ejemplo n.º 10
0
def main():
    helper = get_connection(
        template=True,
        template_stack=True,
        with_enabled_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)

    # Other params.
    vr_name = module.params["vr_name"]
    commit = module.params["commit"]

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

    listing = parent.findall(Bgp)

    # Generate the kwargs for network.Bgp.
    bgp_params = [
        "enable",
        "router_id",
        "reject_default_route",
        "allow_redist_default_route",
        "install_route",
        "ecmp_multi_as",
        "enforce_first_as",
        "local_as",
        "global_bfd_profile",
    ]
    bgp_spec = dict((k, module.params[k]) for k in bgp_params)

    # Generate the kwargs for network.BgpRoutingOptions.
    bgp_routing_options_params = [
        "as_format",
        "always_compare_med",
        "deterministic_med_comparison",
        "default_local_preference",
        "graceful_restart_enable",
        "gr_stale_route_time",
        "gr_local_restart_time",
        "gr_max_peer_restart_time",
        "reflector_cluster_id",
        "confederation_member_as",
        "aggregate_med",
    ]
    bgp_routing_options_spec = dict(
        (k, module.params[k]) for k in bgp_routing_options_params)

    bgp = Bgp(**bgp_spec)
    bgp_routing_options = BgpRoutingOptions(**bgp_routing_options_spec)
    bgp.add(bgp_routing_options)
    parent.add(bgp)

    # Apply the state.
    changed, diff = helper.apply_state(bgp, listing, module, "enable")

    if commit and changed:
        helper.commit(module)

    module.exit_json(msg="BGP configuration successful.",
                     changed=changed,
                     diff=diff)
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'],
        'match_afi':
        module.params['match_afi'],
        'match_safi':
        module.params['match_safi'],
        'match_route_table':
        module.params['match_route_table'],
        'match_nexthop':
        module.params['match_nexthop'],
        'match_from_peer':
        module.params['match_from_peer'],
        'match_med':
        module.params['match_med'],
        'match_as_path_regex':
        module.params['match_as_path_regex'],
        'match_community_regex':
        module.params['match_community_regex'],
        'match_extended_community_regex':
        module.params['match_extended_community_regex'],
        'used_by':
        module.params['used_by'],
        'action':
        module.params['action'],
        'action_local_preference':
        module.params['action_local_preference'],
        'action_med':
        module.params['action_med'],
        'action_nexthop':
        module.params['action_nexthop'],
        'action_origin':
        module.params['action_origin'],
        'action_as_path_limit':
        module.params['action_as_path_limit'],
        'action_as_path_type':
        module.params['action_as_path_type'],
        'action_as_path_prepend_times':
        module.params['action_as_path_prepend_times'],
        'action_community_type':
        module.params['action_community_type'],
        'action_community_argument':
        module.params['action_community_argument'],
        'action_extended_community_type':
        module.params['action_extended_community_type'],
        'action_extended_community_argument':
        module.params['action_extended_community_argument'],
    }
    # Add the correct rule type.
    if module.params['type'] == 'import':
        spec['action_dampening'] = module.params['action_dampening']
        spec['action_weight'] = module.params['action_weight']
        obj = BgpPolicyImportRule(**spec)
    else:
        obj = BgpPolicyExportRule(**spec)

    # Handle address prefixes.
    for x in module.params['address_prefix']:
        if 'name' not in x:
            module.fail_json(
                msg='Address prefix dict requires "name": {0}'.format(x))
        obj.add(
            BgpPolicyAddressPrefix(
                to_text(x['name'],
                        encoding='utf-8',
                        errors='surrogate_or_strict'),
                None if x.get('exact') is None else module.boolean(x['exact']),
            ))

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

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

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

    module.exit_json(changed=changed, diff=diff, msg='done')
Ejemplo n.º 12
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, diff = helper.apply_state(obj, listing, module)
    if changed and module.params['commit']:
        helper.commit(module)

    module.exit_json(changed=changed, diff=diff, msg='done')
def main():
    helper = get_connection(
        template=True,
        template_stack=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 virtual router {0}'.format(vr.name))

    policy = None
    if module.params['policy_type'] == 'conditional-advertisement':
        policy_cls = BgpPolicyConditionalAdvertisement
    else:
        policy_cls = BgpPolicyAggregationAddress
    policy = bgp.find_or_create(module.params['policy_name'], policy_cls)

    obj_type = None
    if module.params['filter_type'] == 'non-exist':
        obj_type = BgpPolicyNonExistFilter
    elif module.params['filter_type'] == 'advertise':
        obj_type = BgpPolicyAdvertiseFilter
    elif module.params['filter_type'] == 'suppress':
        obj_type = BgpPolicySuppressFilter
    else:
        module.fail_json(msg='Unknown filter_type: {0}'.format(module.params['filter_type']))
    listing = policy.findall(obj_type)

    spec = {
        'name': module.params['name'],
        'enable': module.params['enable'],
        'match_afi': module.params['match_afi'],
        'match_safi': module.params['match_safi'],
        'match_route_table': module.params['match_route_table'],
        'match_nexthop': module.params['match_nexthop'],
        'match_from_peer': module.params['match_from_peer'],
        'match_med': module.params['match_med'],
        'match_as_path_regex': module.params['match_as_path_regex'],
        'match_community_regex': module.params['match_community_regex'],
        'match_extended_community_regex': module.params['match_extended_community_regex'],
    }

    commit = module.params['commit']

    obj = obj_type(**spec)
    policy.add(obj)

    # Handle address prefixes.
    for x in module.params['address_prefix']:
        obj.add(BgpPolicyAddressPrefix(
            to_text(x['name'], encoding='utf-8', errors='surrogate_or_strict'),
            None if x.get('exact') is None else module.boolean(x['exact']),
        ))

    if module.params['state'] == 'return-object':
        module.deprecate('state=return-object is deprecated', version='3.0.0', collection_name='paloaltonetworks.panos')
        obj.parent = None
        panos_obj = b64encode(pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL))
        module.exit_json(msg='returning serialized object', panos_obj=panos_obj)

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

    module.exit_json(changed=changed, diff=diff, msg='done')
def main():
    helper = get_connection(
        template=True,
        template_stack=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 virtual router {0}".format(vr.name))

    policy = None
    if module.params["policy_type"] == "conditional-advertisement":
        policy_cls = BgpPolicyConditionalAdvertisement
    else:
        policy_cls = BgpPolicyAggregationAddress
    policy = bgp.find_or_create(module.params["policy_name"], policy_cls)

    obj_type = None
    if module.params["filter_type"] == "non-exist":
        obj_type = BgpPolicyNonExistFilter
    elif module.params["filter_type"] == "advertise":
        obj_type = BgpPolicyAdvertiseFilter
    elif module.params["filter_type"] == "suppress":
        obj_type = BgpPolicySuppressFilter
    else:
        module.fail_json(msg="Unknown filter_type: {0}".format(
            module.params["filter_type"]))
    listing = policy.findall(obj_type)

    spec = {
        "name":
        module.params["name"],
        "enable":
        module.params["enable"],
        "match_afi":
        module.params["match_afi"],
        "match_safi":
        module.params["match_safi"],
        "match_route_table":
        module.params["match_route_table"],
        "match_nexthop":
        module.params["match_nexthop"],
        "match_from_peer":
        module.params["match_from_peer"],
        "match_med":
        module.params["match_med"],
        "match_as_path_regex":
        module.params["match_as_path_regex"],
        "match_community_regex":
        module.params["match_community_regex"],
        "match_extended_community_regex":
        module.params["match_extended_community_regex"],
    }

    commit = module.params["commit"]

    obj = obj_type(**spec)
    policy.add(obj)

    # Handle address prefixes.
    for x in module.params["address_prefix"]:
        obj.add(
            BgpPolicyAddressPrefix(
                to_text(x["name"],
                        encoding="utf-8",
                        errors="surrogate_or_strict"),
                None if x.get("exact") is None else module.boolean(x["exact"]),
            ))

    if module.params["state"] == "return-object":
        module.deprecate(
            "state=return-object is deprecated",
            version="3.0.0",
            collection_name="paloaltonetworks.panos",
        )
        obj.parent = None
        panos_obj = b64encode(
            pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL))
        module.exit_json(msg="returning serialized object",
                         panos_obj=panos_obj)

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

    module.exit_json(changed=changed, diff=diff, 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 for "{0}"'.format(vr.name))

    spec = {
        "name":
        module.params["name"],
        "enable":
        module.params["enable"],
        "match_afi":
        module.params["match_afi"],
        "match_safi":
        module.params["match_safi"],
        "match_route_table":
        module.params["match_route_table"],
        "match_nexthop":
        module.params["match_nexthop"],
        "match_from_peer":
        module.params["match_from_peer"],
        "match_med":
        module.params["match_med"],
        "match_as_path_regex":
        module.params["match_as_path_regex"],
        "match_community_regex":
        module.params["match_community_regex"],
        "match_extended_community_regex":
        module.params["match_extended_community_regex"],
        "used_by":
        module.params["used_by"],
        "action":
        module.params["action"],
        "action_local_preference":
        module.params["action_local_preference"],
        "action_med":
        module.params["action_med"],
        "action_nexthop":
        module.params["action_nexthop"],
        "action_origin":
        module.params["action_origin"],
        "action_as_path_limit":
        module.params["action_as_path_limit"],
        "action_as_path_type":
        module.params["action_as_path_type"],
        "action_as_path_prepend_times":
        module.params["action_as_path_prepend_times"],
        "action_community_type":
        module.params["action_community_type"],
        "action_community_argument":
        module.params["action_community_argument"],
        "action_extended_community_type":
        module.params["action_extended_community_type"],
        "action_extended_community_argument":
        module.params["action_extended_community_argument"],
    }
    # Add the correct rule type.
    if module.params["type"] == "import":
        spec["action_dampening"] = module.params["action_dampening"]
        spec["action_weight"] = module.params["action_weight"]
        obj = BgpPolicyImportRule(**spec)
    else:
        obj = BgpPolicyExportRule(**spec)

    # Handle address prefixes.
    for x in module.params["address_prefix"]:
        if "name" not in x:
            module.fail_json(
                msg='Address prefix dict requires "name": {0}'.format(x))
        obj.add(
            BgpPolicyAddressPrefix(
                to_text(x["name"],
                        encoding="utf-8",
                        errors="surrogate_or_strict"),
                None if x.get("exact") is None else module.boolean(x["exact"]),
            ))

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

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

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

    module.exit_json(changed=changed, diff=diff, msg="done")