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 = 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( 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, 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, ) # 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')
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) # 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')
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')
def populate_facts(self): listing = VirtualRouter.refreshall(self.parent, add=False) virtual_routers = [] for vr in listing: info = { 'vr_name': vr.name, 'vr_iflist': vr.interface or [], 'vr_asn': None, 'vr_routerid': None, } for child in vr.children: if isinstance(child, Bgp): info['vr_asn'] = child.local_as info['vr_routerid'] = child.router_id virtual_routers.append(info) self.facts.update({'virtual_routers': virtual_routers})
def configure_network(device): eth1 = EthernetInterface(name='ethernet1/1', mode='layer3', ip=('192.168.55.20/24', )) eth2 = EthernetInterface(name='ethernet1/2', mode='layer3', ip=('192.168.45.20/24', )) eth3 = EthernetInterface(name='ethernet1/3', mode='layer3', ip=('192.168.35.20/24', )) device.add(eth1) device.add(eth2) device.add(eth3) eth1.create() eth2.create() eth3.create() untrust = Zone(name='untrust', mode='layer3', interface=['ethernet1/1']) web = Zone(name='web', mode='layer3', interface=['ethernet1/2']) db = Zone(name='db', mode='layer3', interface=['ethernet1/3']) device.add(untrust) device.add(web) device.add(db) untrust.create() web.create() db.create() vr_default = VirtualRouter( name='default', interface=['ethernet1/1', 'ethernet1/2', 'ethernet1/3']) device.add(vr_default) vr_default.create() default_route = StaticRoute(name='default', destination='0.0.0.0/0', nexthop='192.168.55.2') vr_default.add(default_route) default_route.create()
def main(): helper = get_connection( template=True, template_stack=True, with_state=True, with_classic_provider_spec=True, argument_spec=dict( name=dict(required=True), destination=dict(), nexthop_type=dict( default='ip-address', choices=['ip-address', 'discard', 'none', 'next-vr'], ), nexthop=dict(), admin_dist=dict(), metric=dict(type='int', default=10), virtual_router=dict(default='default'), interface=dict(), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=True, required_one_of=helper.required_one_of, ) spec = { 'name': module.params['name'], 'destination': module.params['destination'], 'nexthop_type': module.params['nexthop_type'], 'nexthop': module.params['nexthop'], 'interface': module.params['interface'], 'admin_dist': module.params['admin_dist'], 'metric': module.params['metric'], } parent = helper.get_pandevice_parent(module) virtual_router = module.params['virtual_router'] # Allow None for nexthop_type. if spec['nexthop_type'] == 'none': spec['nexthop_type'] = None try: vr_list = VirtualRouter.refreshall(parent, add=False, name_only=True) except PanDeviceError as e: module.fail_json(msg='Failed vr refresh: {0}'.format(e)) # Find the virtual router. for vr in vr_list: if vr.name == virtual_router: parent.add(vr) break else: module.fail_json( msg='Virtual router "{0}" does not exist'.format(virtual_router)) # Get the listing. try: listing = StaticRoute.refreshall(vr, add=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) # Create the object and attach it to the object tree. obj = StaticRoute(**spec) vr.add(obj) # Apply the state. changed = helper.apply_state(obj, listing, module) module.exit_json(changed=changed)
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' ] 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( vsys_importable=True, 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 imports, build pandevice object tree. parent = helper.get_pandevice_parent(module) # Exclude non-object items from kwargs passed to the object. exclude_list = [ 'ip_address', 'username', 'password', 'api_key', 'state', 'commit', 'provider', 'template', 'template_stack', 'vsys', 'port', ] # Generate the kwargs for network.VirtualRouter. obj_spec = dict((k, module.params[k]) for k in helper.argument_spec.keys() if k not in exclude_list) name = module.params['name'] state = module.params['state'] commit = module.params['commit'] # Retrieve current virtual routers. try: vr_list = VirtualRouter.refreshall(parent, add=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) # Create the new state object. virtual_router = VirtualRouter(**obj_spec) parent.add(virtual_router) reference_params = { 'refresh': True, 'update': not module.check_mode, 'return_type': 'bool', } changed = False if state == 'present': for item in vr_list: if item.name != name: continue if not item.equal(virtual_router, compare_children=False): changed = True virtual_router.extend(item.children) if not module.check_mode: try: virtual_router.apply() except PanDeviceError as e: module.fail_json(msg='Failed apply: {0}'.format(e)) break else: changed = True if not module.check_mode: try: virtual_router.create() except PanDeviceError as e: module.fail_json(msg='Failed apply: {0}'.format(e)) changed |= virtual_router.set_vsys(module.params['vsys'], **reference_params) else: changed |= virtual_router.set_vsys(None, **reference_params) if name in [x.name for x in vr_list]: changed = True if not module.check_mode: try: virtual_router.delete() except PanDeviceError as e: module.fail_json(msg='Failed delete: {0}'.format(e)) if commit and changed: helper.commit(module) if not changed: msg = 'no changes required.' elif module.check_mode: msg = 'Changes are required.' else: msg = 'Virtual router update successful.' module.exit_json(msg=msg, changed=changed)
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) # Other params. state = module.params['state'] 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 # 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' ] 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) changed = False live_bgp = parent.find('', Bgp) if state == 'present': if live_bgp is None: changed = True parent.add(bgp) if not module.check_mode: try: bgp.create() except PanDeviceError as e: module.fail_json(msg='Failed create: {0}'.format(e)) else: live_options = None other_children = [] options_children = [] for x in live_bgp.children: if x.__class__ == BgpRoutingOptions: live_options = x options_children = x.children x.removeall() else: other_children.append(x) live_bgp.removeall() if live_options is not None: live_bgp.add(live_options) parent.add(bgp) if not live_bgp.equal(bgp): changed = True bgp.extend(other_children) bgp_routing_options.extend(options_children) if not module.check_mode: try: bgp.apply() except PanDeviceError as e: module.fail_json(msg='Failed apply: {0}'.format(e)) else: if live_bgp is not None: changed = True if not module.check_mode: try: live_bgp.delete() except PanDeviceError as e: module.fail_json(msg='Failed delete: {0}'.format(e)) if commit and changed: helper.commit(module) module.exit_json(msg='BGP configuration successful.', changed=changed)
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 = helper.apply_state(obj, listing, module) if changed and module.params['commit']: helper.commit(module) module.exit_json(changed=changed, 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'], } obj = obj_type(**spec) policy.add(obj) # Handle address prefixes. for x in module.params['address_prefix']: if isinstance(x, dict): 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']), )) else: obj.add(BgpPolicyAddressPrefix(to_text(x, encoding='utf-8', errors='surrogate_or_strict'))) if module.params['state'] == 'return-object': module.deprecate('state=return-object is deprecated', '2.12') import pickle from base64 import b64encode 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 = helper.apply_state(obj, listing, module) if changed and module.params['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) 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')
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 isinstance(x, dict): 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']), )) else: obj.add( BgpPolicyAddressPrefix( to_text(x, encoding='utf-8', errors='surrogate_or_strict'))) 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')
def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), operation=dict(default='add', choices=['add', 'update', 'delete']), state=dict(choices=['present', 'absent']), if_name=dict(required=True), ip=dict(type='list'), ipv6_enabled=dict(), management_profile=dict(), mtu=dict(), netflow_profile=dict(), comment=dict(), zone_name=dict(required=True), vr_name=dict(default='default'), vsys_dg=dict(default='vsys1'), commit=dict(type='bool', default=True), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['api_key', 'password']]) if not HAS_LIB: module.fail_json(msg='Missing required libraries.') # Get the firewall / panorama auth. auth = [ module.params[x] for x in ('ip_address', 'username', 'password', 'api_key') ] # Get the object params. spec = { 'name': module.params['if_name'], 'ip': module.params['ip'], 'ipv6_enabled': module.params['ipv6_enabled'], 'management_profile': module.params['management_profile'], 'mtu': module.params['mtu'], 'netflow_profile': module.params['netflow_profile'], 'comment': module.params['comment'], } # Get other info. operation = module.params['operation'] state = module.params['state'] zone_name = module.params['zone_name'] vr_name = module.params['vr_name'] vsys_dg = module.params['vsys_dg'] commit = module.params['commit'] if_name = module.params['if_name'] # Open the connection to the PANOS device. con = PanDevice.create_from_device(*auth) # Set vsys if firewall, device group if panorama. if hasattr(con, 'refresh_devices'): # Panorama # Normally we want to set the device group here, but there are no # interfaces on Panorama. So if we're given a Panorama device, then # error out. ''' groups = panorama.DeviceGroup.refreshall(con, add=False) for parent in groups: if parent.name == vsys_dg: con.add(parent) break else: module.fail_json(msg="'{0}' device group is not present".format(vsys_dg)) ''' module.fail_json(msg="Ethernet interfaces don't exist on Panorama") else: # Firewall # Normally we should set the vsys here, but since interfaces are # vsys importables, we'll use organize_into_vsys() to help find and # cleanup when the interface is imported into an undesired vsys. # con.vsys = vsys_dg pass # Retrieve the current config. try: interfaces = TunnelInterface.refreshall(con, add=False, name_only=True) zones = Zone.refreshall(con) routers = VirtualRouter.refreshall(con) vsys_list = Vsys.refreshall(con) except PanDeviceError: e = get_exception() module.fail_json(msg=e.message) # Build the object based on the user spec. tun = TunnelInterface(**spec) con.add(tun) # Which action should we take on the interface? changed = False if state == 'present': if tun.name in [x.name for x in interfaces]: i = TunnelInterface(tun.name) con.add(i) try: i.refresh() except PanDeviceError as e: module.fail_json(msg='Failed "present" refresh: {0}'.format(e)) if not i.equal(tun, compare_children=False): tun.extend(i.children) try: tun.apply() changed = True except PanDeviceError as e: module.fail_json( msg='Failed "present" apply: {0}'.format(e)) else: try: tun.create() changed = True except PanDeviceError as e: module.fail_json(msg='Failed "present" create: {0}'.format(e)) try: changed |= set_zone(con, tun, zone_name, zones) changed |= set_virtual_router(con, tun, vr_name, routers) except PanDeviceError as e: module.fail_json(msg='Failed zone/vr assignment: {0}'.format(e)) elif state == 'absent': try: changed |= set_zone(con, tun, None, zones) changed |= set_virtual_router(con, tun, None, routers) except PanDeviceError as e: module.fail_json( msg='Failed "absent" zone/vr cleanup: {0}'.format(e)) changed = True if tun.name in [x.name for x in interfaces]: try: tun.delete() changed = True except PanDeviceError as e: module.fail_json(msg='Failed "absent" delete: {0}'.format(e)) elif operation == 'delete': if tun.name not in [x.name for x in interfaces]: module.fail_json( msg='Interface {0} does not exist, and thus cannot be deleted'. format(tun.name)) try: con.organize_into_vsys() set_zone(con, tun, None, zones) set_virtual_router(con, tun, None, routers) tun.delete() changed = True except (PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) elif operation == 'add': if tun.name in [x.name for x in interfaces]: module.fail_json( msg='Interface {0} is already present; use operation "update"'. format(tun.name)) con.vsys = vsys_dg # Create the interface. try: tun.create() set_zone(con, tun, zone_name, zones) set_virtual_router(con, tun, vr_name, routers) changed = True except (PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) elif operation == 'update': if tun.name not in [x.name for x in interfaces]: module.fail_json( msg= 'Interface {0} is not present; use operation "add" to create it' .format(tun.name)) # If the interface is in the wrong vsys, remove it from the old vsys. try: con.organize_into_vsys() except PanDeviceError: e = get_exception() module.fail_json(msg=e.message) if tun.vsys != vsys_dg: try: tun.delete_import() except PanDeviceError: e = get_exception() module.fail_json(msg=e.message) # Move the ethernet object to the correct vsys. for vsys in vsys_list: if vsys.name == vsys_dg: vsys.add(tun) break else: module.fail_json(msg='Vsys {0} does not exist'.format(vsys)) # Update the interface. try: tun.apply() set_zone(con, tun, zone_name, zones) set_virtual_router(con, tun, vr_name, routers) changed = True except (PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) else: module.fail_json(msg="Unsupported operation '{0}'".format(operation)) # Commit if we were asked to do so. if changed and commit: try: con.commit(sync=True) except PanDeviceError: e = get_exception() module.fail_json(msg='Performed {0} but commit failed: {1}'.format( operation, e.message)) # Done! module.exit_json(changed=changed, msg='okey dokey')
def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), operation=dict(default='add', choices=['add', 'update', 'delete']), state=dict(choices=['present', 'absent']), if_name=dict(required=True), mode=dict(default='layer3', choices=[ 'layer3', 'layer2', 'virtual-wire', 'tap', 'ha', 'decrypt-mirror', 'aggregate-group' ]), ip=dict(type='list'), ipv6_enabled=dict(), management_profile=dict(), mtu=dict(), adjust_tcp_mss=dict(), netflow_profile=dict(), lldp_enabled=dict(), lldp_profile=dict(), netflow_profile_l2=dict(), link_speed=dict(), link_duplex=dict(), link_state=dict(), aggregate_group=dict(), comment=dict(), ipv4_mss_adjust=dict(), ipv6_mss_adjust=dict(), enable_dhcp=dict(type='bool', default=True), create_default_route=dict(type='bool', default=False), create_dhcp_default_route=dict(type='bool', default=False), dhcp_default_route_metric=dict(), dhcp_default_route=dict(type='str', default="no"), zone_name=dict(required=True), vr_name=dict(default='default'), vsys_dg=dict(default='vsys1'), commit=dict(type='bool', default=True), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['api_key', 'password']]) if not HAS_LIB: module.fail_json(msg='Missing required libraries.') # Get the firewall / panorama auth. auth = [ module.params[x] for x in ('ip_address', 'username', 'password', 'api_key') ] # Get the object params. spec = { 'name': module.params['if_name'], 'mode': module.params['mode'], 'ip': module.params['ip'], 'ipv6_enabled': module.params['ipv6_enabled'], 'management_profile': module.params['management_profile'], 'mtu': module.params['mtu'], 'adjust_tcp_mss': module.params['adjust_tcp_mss'], 'netflow_profile': module.params['netflow_profile'], 'lldp_enabled': module.params['lldp_enabled'], 'lldp_profile': module.params['lldp_profile'], 'netflow_profile_l2': module.params['netflow_profile_l2'], 'link_speed': module.params['link_speed'], 'link_duplex': module.params['link_duplex'], 'link_state': module.params['link_state'], 'aggregate_group': module.params['aggregate_group'], 'comment': module.params['comment'], 'ipv4_mss_adjust': module.params['ipv4_mss_adjust'], 'ipv6_mss_adjust': module.params['ipv6_mss_adjust'], 'enable_dhcp': module.params['enable_dhcp'] or None, 'create_dhcp_default_route': module.params['create_default_route'] or None, 'dhcp_default_route_metric': module.params['dhcp_default_route_metric'], } # Get other info. enable_dhcp = module.params['enable_dhcp'] operation = module.params['operation'] state = module.params['state'] zone_name = module.params['zone_name'] vr_name = module.params['vr_name'] vsys_dg = module.params['vsys_dg'] commit = module.params['commit'] dhcp_default_route = module.params['dhcp_default_route'] management_profile = module.params['management_profile'] if_name = module.params['if_name'] dhcpe = ( '<entry name="%s"><layer3><dhcp-client><enable>yes</enable><create-default-route>%s</create-default-route>' '</dhcp-client><interface-management-profile>%s</interface-management-profile></layer3></entry>' % (if_name, dhcp_default_route, management_profile)) dhcpx = ( "/config/devices/entry[@name='localhost.localdomain']/network/interface/ethernet/entry[@name='%s']" % (if_name)) # Open the connection to the PANOS device. con = PanDevice.create_from_device(*auth) # Set vsys if firewall, device group if panorama. if hasattr(con, 'refresh_devices'): # Panorama # Normally we want to set the device group here, but there are no # interfaces on Panorama. So if we're given a Panorama device, then # error out. ''' groups = panorama.DeviceGroup.refreshall(con, add=False) for parent in groups: if parent.name == vsys_dg: con.add(parent) break else: module.fail_json(msg="'{0}' device group is not present".format(vsys_dg)) ''' module.fail_json(msg="Ethernet interfaces don't exist on Panorama") else: # Firewall # Normally we should set the vsys here, but since interfaces are # vsys importables, we'll use organize_into_vsys() to help find and # cleanup when the interface is imported into an undesired vsys. # con.vsys = vsys_dg pass # Retrieve the current config. try: interfaces = EthernetInterface.refreshall(con, add=False, name_only=True) zones = Zone.refreshall(con) routers = VirtualRouter.refreshall(con) vsys_list = Vsys.refreshall(con) except PanDeviceError: e = get_exception() module.fail_json(msg=e.message) # Build the object based on the user spec. eth = EthernetInterface(**spec) con.add(eth) # Which action should we take on the interface? changed = False if state == 'present': if eth.name in [x.name for x in interfaces]: i = EthernetInterface(eth.name) con.add(i) try: i.refresh() except PanDeviceError as e: module.fail_json(msg='Failed "present" refresh: {0}'.format(e)) if not i.equal(eth, compare_children=False): eth.extend(i.children) try: eth.apply() changed = True except PanDeviceError as e: module.fail_json( msg='Failed "present" apply: {0}'.format(e)) else: try: eth.create() changed = True except PanDeviceError as e: module.fail_json(msg='Failed "present" create: {0}'.format(e)) try: changed |= set_zone(con, eth, zone_name, zones) changed |= set_virtual_router(con, eth, vr_name, routers) if enable_dhcp is True: con.xapi.edit(xpath=dhcpx, element=dhcpe) except PanDeviceError as e: module.fail_json(msg='Failed zone/vr assignment: {0}'.format(e)) elif state == 'absent': try: changed |= set_zone(con, eth, None, zones) changed |= set_virtual_router(con, eth, None, routers) except PanDeviceError as e: module.fail_json( msg='Failed "absent" zone/vr cleanup: {0}'.format(e)) changed = True if eth.name in [x.name for x in interfaces]: try: eth.delete() changed = True except PanDeviceError as e: module.fail_json(msg='Failed "absent" delete: {0}'.format(e)) elif operation == 'delete': if eth.name not in [x.name for x in interfaces]: module.fail_json( msg='Interface {0} does not exist, and thus cannot be deleted'. format(eth.name)) try: con.organize_into_vsys() set_zone(con, eth, None, zones) set_virtual_router(con, eth, None, routers) eth.delete() changed = True except (PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) elif operation == 'add': if eth.name in [x.name for x in interfaces]: module.fail_json( msg='Interface {0} is already present; use operation "update"'. format(eth.name)) con.vsys = vsys_dg # Create the interface. try: eth.create() set_zone(con, eth, zone_name, zones) set_virtual_router(con, eth, vr_name, routers) changed = True except (PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) elif operation == 'update': if eth.name not in [x.name for x in interfaces]: module.fail_json( msg= 'Interface {0} is not present; use operation "add" to create it' .format(eth.name)) # If the interface is in the wrong vsys, remove it from the old vsys. try: con.organize_into_vsys() except PanDeviceError: e = get_exception() module.fail_json(msg=e.message) if eth.vsys != vsys_dg: try: eth.delete_import() except PanDeviceError: e = get_exception() module.fail_json(msg=e.message) # Move the ethernet object to the correct vsys. for vsys in vsys_list: if vsys.name == vsys_dg: vsys.add(eth) break else: module.fail_json(msg='Vsys {0} does not exist'.format(vsys)) # Update the interface. try: eth.apply() set_zone(con, eth, zone_name, zones) set_virtual_router(con, eth, vr_name, routers) changed = True except (PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) else: module.fail_json(msg="Unsupported operation '{0}'".format(operation)) # Commit if we were asked to do so. if changed and commit: try: con.commit(sync=True, exceptions=True) except PanDeviceError: e = get_exception() module.fail_json(msg='Performed {0} but commit failed: {1}'.format( operation, e.message)) # Done! module.exit_json(changed=changed, msg='okey dokey')