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), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=False, required_one_of=helper.required_one_of, ) parent = helper.get_pandevice_parent(module) 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( 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)
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), value=dict(type='list', elements='str'), tag=dict(type='list', elements='str'), )) required_if = [["state", "present", ["value"]]] module = AnsibleModule(argument_spec=helper.argument_spec, required_one_of=helper.required_one_of, required_if=required_if, supports_check_mode=True) parent = helper.get_pandevice_parent(module) spec = { 'name': module.params['name'], 'value': module.params['value'], 'tag': module.params['tag'], } try: listing = ApplicationGroup.refreshall(parent, add=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) obj = ApplicationGroup(**spec) parent.add(obj) changed, diff = helper.apply_state(obj, listing, module) module.exit_json(changed=changed, diff=diff)
def main(): helper = get_connection(vsys=True, device_group=True, min_panos_version=(9, 1, 0), with_classic_provider_spec=True, with_state=True, argument_spec=dict( name=dict(type='str', required=True), address=dict(type='list', elements='str'), latitude=dict(type='float'), longitude=dict(type='float'), )) 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'], 'address': module.params['address'], 'latitude': module.params['latitude'], 'longitude': module.params['longitude'], } try: listing = Region.refreshall(parent, add=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) obj = Region(**spec) parent.add(obj) changed, diff = helper.apply_state(obj, listing, module) module.exit_json(changed=changed, diff=diff)
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( name=dict(required=True), version=dict(default='v2c', choices=['v2c', 'v3']), ), ) 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 = SnmpServerProfile.refreshall(parent) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) spec = { 'name': module.params['name'], 'version': module.params['version'], } obj = SnmpServerProfile(**spec) parent.add(obj) changed, diff = helper.apply_state(obj, listing, module) module.exit_json(changed=changed, diff=diff, 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=(7, 1, 0), argument_spec=dict( name=dict(required=True), config=dict(), system=dict(), threat=dict(), traffic=dict(), hip_match=dict(), url=dict(), data=dict(), wildfire=dict(), tunnel=dict(), user_id=dict(), gtp=dict(), auth=dict(), sctp=dict(), iptag=dict(), escaped_characters=dict(), escape_character=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) try: listing = EmailServerProfile.refreshall(parent) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) spec = { 'name': module.params['name'], 'config': module.params['config'], 'system': module.params['system'], 'threat': module.params['threat'], 'traffic': module.params['traffic'], 'hip_match': module.params['hip_match'], 'url': module.params['url'], 'data': module.params['data'], 'wildfire': module.params['wildfire'], 'tunnel': module.params['tunnel'], 'user_id': module.params['user_id'], 'gtp': module.params['gtp'], 'auth': module.params['auth'], 'sctp': module.params['sctp'], 'iptag': module.params['iptag'], 'escaped_characters': module.params['escaped_characters'], 'escape_character': module.params['escape_character'], } obj = EmailServerProfile(**spec) parent.add(obj) changed, diff = helper.apply_state(obj, listing, 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, with_state=True, argument_spec=dict( name=dict(required=True), dh_group=dict( type="list", elements="str", default=["group2"], choices=["group1", "group2", "group5", "group14", "group19", "group20"], aliases=["dhgroup"], ), authentication=dict( type="list", elements="str", choices=["md5", "sha1", "sha256", "sha384", "sha512"], default=["sha1"], ), encryption=dict( type="list", elements="str", choices=["des", "3des", "aes-128-cbc", "aes-192-cbc", "aes-256-cbc"], default=["aes-256-cbc", "3des"], ), lifetime_seconds=dict(type="int", aliases=["lifetime_sec"]), lifetime_minutes=dict(type="int"), lifetime_hours=dict(type="int"), lifetime_days=dict(type="int"), commit=dict(type="bool", default=False), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=True, required_one_of=helper.required_one_of, mutually_exclusive=[ ["lifetime_seconds", "lifetime_minutes", "lifetime_hours", "lifetime_days"] ], ) # Verify libs are present, get parent object. parent = helper.get_pandevice_parent(module) # Object params. spec = { "name": module.params["name"], "dh_group": module.params["dh_group"], "authentication": module.params["authentication"], "encryption": module.params["encryption"], "lifetime_seconds": module.params["lifetime_seconds"], "lifetime_minutes": module.params["lifetime_minutes"], "lifetime_hours": module.params["lifetime_hours"], "lifetime_days": module.params["lifetime_days"], } # Other info. commit = module.params["commit"] # Reflect GUI behavior. Default is 8 hour key lifetime if nothing else is # specified. if not any( [ spec["lifetime_seconds"], spec["lifetime_minutes"], spec["lifetime_hours"], spec["lifetime_days"], ] ): spec["lifetime_hours"] = 8 # Retrieve current info. try: listing = IkeCryptoProfile.refreshall(parent, add=False) except PanDeviceError as e: module.fail_json(msg="Failed refresh: {0}".format(e)) obj = IkeCryptoProfile(**spec) parent.add(obj) # Apply the state. changed, diff = helper.apply_state(obj, listing, module) # Commit. if commit and changed: helper.commit(module) # Done. module.exit_json(changed=changed, diff=diff)
def main(): helper = get_connection( vsys=True, device_group=True, rulebase=True, with_state=True, with_classic_provider_spec=True, error_on_shared=True, argument_spec=dict( rule_name=dict(required=True), source_zone=dict(type='list', default=['any']), source_ip=dict(type='list', default=["any"]), source_user=dict(type='list', default=['any']), hip_profiles=dict(type='list', default=['any']), destination_zone=dict(type='list', default=['any']), destination_ip=dict(type='list', default=["any"]), application=dict(type='list', default=['any']), service=dict(type='list', default=['application-default']), category=dict(type='list', default=['any']), action=dict( default='allow', choices=[ 'allow', 'deny', 'drop', 'reset-client', 'reset-server', 'reset-both' ], ), log_setting=dict(), log_start=dict(type='bool', default=False), log_end=dict(type='bool', default=True), description=dict(), rule_type=dict(default='universal', choices=['universal', 'intrazone', 'interzone']), tag_name=dict(type='list'), negate_source=dict(type='bool', default=False), negate_destination=dict(type='bool', default=False), disabled=dict(type='bool', default=False), schedule=dict(), icmp_unreachable=dict(type='bool'), disable_server_response_inspection=dict(type='bool', default=False), group_profile=dict(), antivirus=dict(), spyware=dict(), vulnerability=dict(), url_filtering=dict(), file_blocking=dict(), wildfire_analysis=dict(), data_filtering=dict(), target=dict(type='list'), negate_target=dict(type='bool'), location=dict(choices=['top', 'bottom', 'before', 'after']), existing_rule=dict(), commit=dict(type='bool', default=True), # TODO(gfreeman) - remove this in the next role release. operation=dict(), # TODO(gfreeman) - remove this in the next role release. devicegroup=dict(), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=True, required_one_of=helper.required_one_of, ) # TODO(gfreeman) - removed when operation is removed. if module.params['operation'] is not None: module.fail_json( msg='Param "operation" is removed; use "state" instead') # TODO(gfreeman) - remove when devicegroup is removed. 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" are specified', 'Specify one or the other, not both.', ] module.fail_json(msg='. '.join(msg)) module.params['device_group'] = module.params['devicegroup'] # Verify imports, build pandevice object tree. parent = helper.get_pandevice_parent(module) # Set the SecurityRule object params. rule_spec = { 'name': module.params['rule_name'], 'fromzone': module.params['source_zone'], 'tozone': module.params['destination_zone'], 'source': module.params['source_ip'], 'source_user': module.params['source_user'], 'hip_profiles': module.params['hip_profiles'], 'destination': module.params['destination_ip'], 'application': module.params['application'], 'service': module.params['service'], 'category': module.params['category'], 'action': module.params['action'], 'log_setting': module.params['log_setting'], 'log_start': module.params['log_start'], 'log_end': module.params['log_end'], 'description': module.params['description'], 'type': module.params['rule_type'], 'tag': module.params['tag_name'], 'negate_source': module.params['negate_source'], 'negate_destination': module.params['negate_destination'], 'disabled': module.params['disabled'], 'schedule': module.params['schedule'], 'icmp_unreachable': module.params['icmp_unreachable'], 'disable_server_response_inspection': module.params['disable_server_response_inspection'], 'group': module.params['group_profile'], 'virus': module.params['antivirus'], 'spyware': module.params['spyware'], 'vulnerability': module.params['vulnerability'], 'url_filtering': module.params['url_filtering'], 'file_blocking': module.params['file_blocking'], 'wildfire_analysis': module.params['wildfire_analysis'], 'data_filtering': module.params['data_filtering'], 'target': module.params['target'], 'negate_target': module.params['negate_target'], } # Other module info. location = module.params['location'] existing_rule = module.params['existing_rule'] commit = module.params['commit'] # Retrieve the current rules. try: rules = SecurityRule.refreshall(parent, add=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) # Create new rule object from the params. new_rule = SecurityRule(**rule_spec) parent.add(new_rule) # Which action shall we take on the rule object? changed, diff = helper.apply_state(new_rule, rules, module) # Move the rule to the correct spot, if applicable. if module.params['state'] == 'present': changed |= helper.apply_position(new_rule, location, existing_rule, module) # Optional commit. if changed and commit: helper.commit(module) # Done. module.exit_json(changed=changed, diff=diff, msg='Done')
def main(): helper = get_connection( min_pandevice_version=(1, 0, 0), min_panos_version=(8, 0, 0), argument_spec=dict(description=dict(type='str'), admins=dict(type='list', elements='str'), device_groups=dict(type='list', elements='str'), templates=dict(type='list', elements='str'), template_stacks=dict(type='list', elements='str'), wildfire_appliances=dict(type='list', elements='str'), wildfire_clusters=dict(type='list', elements='str'), log_collectors=dict(type='list', elements='str'), log_collector_groups=dict(type='list', elements='str'), exclude_device_and_network=dict(type='bool'), exclude_shared_objects=dict(type='bool'), force=dict(type='bool'), sync=dict(type='bool', default=True))) module = AnsibleModule(argument_spec=helper.argument_spec, supports_check_mode=False, required_one_of=helper.required_one_of) # Verify libs are present, get the parent object. parent = helper.get_pandevice_parent(module) # Construct the commit command cmd = PanoramaCommit( description=module.params['description'], admins=module.params['admins'], device_groups=module.params['device_groups'], templates=module.params['templates'], template_stacks=module.params['template_stacks'], wildfire_appliances=module.params['wildfire_appliances'], wildfire_clusters=module.params['wildfire_clusters'], log_collectors=module.params['log_collectors'], log_collector_groups=module.params['log_collector_groups'], exclude_device_and_network=module.params['exclude_device_and_network'], exclude_shared_objects=module.params['exclude_shared_objects'], force=module.params['force']) # Execute the commit commit_results = dict(changed=False, jobid=0) # commit_results = {} sync = module.params['sync'] result = parent.commit(cmd=cmd, sync=sync) # Exit with status if result is None: # No commit was needed pass elif not sync: # When sync is False only jobid is returned commit_results['jobid'] = int(result) elif not result['success']: # The commit failed module.fail_json(msg=' | '.join(result["messages"])) else: # The commit succeeded commit_results['changed'] = True commit_results['jobid'] = result['jobid'] commit_results['details'] = result['messages'] module.exit_json(**commit_results)
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), tag_registration=dict(type="bool"), config_name=dict(), config_uri_format=dict(), config_payload=dict(), system_name=dict(), system_uri_format=dict(), system_payload=dict(), threat_name=dict(), threat_uri_format=dict(), threat_payload=dict(), traffic_name=dict(), traffic_uri_format=dict(), traffic_payload=dict(), hip_match_name=dict(), hip_match_uri_format=dict(), hip_match_payload=dict(), url_name=dict(), url_uri_format=dict(), url_payload=dict(), data_name=dict(), data_uri_format=dict(), data_payload=dict(), wildfire_name=dict(), wildfire_uri_format=dict(), wildfire_payload=dict(), tunnel_name=dict(), tunnel_uri_format=dict(), tunnel_payload=dict(), user_id_name=dict(), user_id_uri_format=dict(), user_id_payload=dict(), gtp_name=dict(), gtp_uri_format=dict(), gtp_payload=dict(), auth_name=dict(), auth_uri_format=dict(), auth_payload=dict(), sctp_name=dict(), sctp_uri_format=dict(), sctp_payload=dict(), iptag_name=dict(), iptag_uri_format=dict(), iptag_payload=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) try: listing = HttpServerProfile.refreshall(parent) except PanDeviceError as e: module.fail_json(msg="Failed refresh: {0}".format(e)) spec = { "name": module.params["name"], "tag_registration": module.params["tag_registration"], "config_name": module.params["config_name"], "config_uri_format": module.params["config_uri_format"], "config_payload": module.params["config_payload"], "system_name": module.params["system_name"], "system_uri_format": module.params["system_uri_format"], "system_payload": module.params["system_payload"], "threat_name": module.params["threat_name"], "threat_uri_format": module.params["threat_uri_format"], "threat_payload": module.params["threat_payload"], "traffic_name": module.params["traffic_name"], "traffic_uri_format": module.params["traffic_uri_format"], "traffic_payload": module.params["traffic_payload"], "hip_match_name": module.params["hip_match_name"], "hip_match_uri_format": module.params["hip_match_uri_format"], "hip_match_payload": module.params["hip_match_payload"], "url_name": module.params["url_name"], "url_uri_format": module.params["url_uri_format"], "url_payload": module.params["url_payload"], "data_name": module.params["data_name"], "data_uri_format": module.params["data_uri_format"], "data_payload": module.params["data_payload"], "wildfire_name": module.params["wildfire_name"], "wildfire_uri_format": module.params["wildfire_uri_format"], "wildfire_payload": module.params["wildfire_payload"], "tunnel_name": module.params["tunnel_name"], "tunnel_uri_format": module.params["tunnel_uri_format"], "tunnel_payload": module.params["tunnel_payload"], "user_id_name": module.params["user_id_name"], "user_id_uri_format": module.params["user_id_uri_format"], "user_id_payload": module.params["user_id_payload"], "gtp_name": module.params["gtp_name"], "gtp_uri_format": module.params["gtp_uri_format"], "gtp_payload": module.params["gtp_payload"], "auth_name": module.params["auth_name"], "auth_uri_format": module.params["auth_uri_format"], "auth_payload": module.params["auth_payload"], "sctp_name": module.params["sctp_name"], "sctp_uri_format": module.params["sctp_uri_format"], "sctp_payload": module.params["sctp_payload"], "iptag_name": module.params["iptag_name"], "iptag_uri_format": module.params["iptag_uri_format"], "iptag_payload": module.params["iptag_payload"], } obj = HttpServerProfile(**spec) parent.add(obj) changed, diff = helper.apply_state(obj, listing, 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')
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( with_classic_provider_spec=True, argument_spec=dict( hostname=dict(), domain=dict(), dns_server_primary=dict(), dns_server_secondary=dict(), timezone=dict(), panorama_primary=dict(), panorama_secondary=dict(), login_banner=dict(), update_server=dict(), verify_update_server=dict(type='bool'), ntp_server_primary=dict(), ntp_server_secondary=dict(), commit=dict(type='bool', default=True), # TODO(gfreeman) - remove in the next role release. devicegroup=dict(), ), ) 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) - remove this in the next role release. if module.params['devicegroup'] is not None: module.fail_json(msg='Param "devicegroup" has been removed') obj = SystemSettings() parent.add(obj) try: obj.refresh() except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) param_relationships = { 'hostname': 'hostname', 'domain': 'domain', 'dns_server_primary': 'dns_primary', 'dns_server_secondary': 'dns_secondary', 'timezone': 'timezone', 'panorama_primary': 'panorama', 'panorama_secondary': 'panorama2', 'login_banner': 'login_banner', 'update_server': 'update_server', 'verify_update_server': 'verify_update_server', } changed = False for ansible_param, obj_param in param_relationships.items(): value = module.params[ansible_param] if value is not None and getattr(obj, obj_param) != value: changed = True setattr(obj, obj_param, value) if not module.check_mode: try: obj.update(obj_param) except PanDeviceError as e: module.fail_json( msg='Failed to update {0}: {1}'.format(obj_param, e)) ntp_relationships = { 'ntp_server_primary': NTPServerPrimary, 'ntp_server_secondary': NTPServerSecondary, } for ansible_param, ntp_obj_cls in ntp_relationships.items(): value = module.params[ansible_param] if value is not None: ntp_obj = None # As of pandevice v0.8.0, can't use .find() here as NTP objects # erroneously have cls.NAME != None. for ntp_obj in obj.children: if isinstance(ntp_obj, ntp_obj_cls): break else: ntp_obj = ntp_obj_cls() obj.add(ntp_obj) if ntp_obj.address != value: changed = True ntp_obj.address = value if not module.check_mode: try: ntp_obj.apply() except PanDeviceError as e: module.fail_json(msg='Failed to set {0}: {1}'.format( ansible_param, e)) # Optional commit. if changed and module.params['commit'] and not module.check_mode: helper.commit(module) module.exit_json(changed=changed, msg='done')
def main(): helper = get_connection( template=True, with_classic_provider_spec=True, with_state=True, min_pandevice_version=(0, 14, 0), argument_spec=dict( iface_name=dict(required=True), address=dict(required=True), enable_on_interface=dict(type='bool', default=True), prefix=dict(type='bool'), anycast=dict(type='bool'), advertise_enabled=dict(type='bool'), valid_lifetime=dict(type='int', default=2592000), preferred_lifetime=dict(type='int', default=604800), onlink_flag=dict(type='bool', default=True), auto_config_flag=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, get the parent object. parent = helper.get_pandevice_parent(module) # Get the object params. spec = { 'address': module.params['address'], 'enable_on_interface': module.params['enable_on_interface'], 'prefix': module.params['prefix'], 'anycast': module.params['anycast'], 'advertise_enabled': module.params['advertise_enabled'], 'valid_lifetime': module.params['valid_lifetime'], 'preferred_lifetime': module.params['preferred_lifetime'], 'onlink_flag': module.params['onlink_flag'], 'auto_config_flag': module.params['auto_config_flag'], } # Get other info. iname = module.params['iface_name'] # Determine parent interface. eth = None part = iname if iname.startswith('ethernet') or iname.startswith('ae'): part = iname.split('.')[0] if iname.startswith('ethernet'): eth = EthernetInterface(part) else: eth = AggregateInterface(part) else: if iname.startswith('loopback'): eth = LoopbackInterface(iname) elif iname.startswith('tunnel'): eth = TunnelInterface(iname) elif iname.startswith('vlan'): eth = VlanInterface(iname) else: module.fail_json(msg='Unknown interface style: {0}'.format(iname)) parent.add(eth) try: eth.refresh() except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) if iname != part: for child in eth.children: if child.uid == iname: eth = child break else: module.fail_json(msg='Could not find parent interface') listing = eth.findall(IPv6Address) # Build the object based on the user spec. obj = IPv6Address(**spec) eth.add(obj) # Apply the state changed, diff = helper.apply_state(obj, listing, module) # Done. module.exit_json(changed=changed, diff=diff)
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(), all_details=dict(default=False, type='bool'), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=False, required_one_of=helper.required_one_of, ) parent = helper.get_pandevice_parent(module) 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'), ) name = module.params['rule_name'] all_details = module.params['all_details'] if all_details and name is None: try: listing = SecurityRule.refreshall(parent) except PanDeviceError as e: module.fail_json(msg='Failed refreshall: {0}'.format(e)) rules = [rule.about() for rule in listing] for rule in rules: for pandevice_param, ansible_param in renames: rule[ansible_param] = rule[pandevice_param] del rule[pandevice_param] module.exit_json( changed=False, policy=rules, ) elif 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() for pandevice_param, ansible_param in renames: spec[ansible_param] = spec[pandevice_param] del (spec[pandevice_param]) module.exit_json(changed=False, spec=spec)
def main(): helper = get_connection( vsys_importable=True, template=True, template_stack=True, with_state=True, with_classic_provider_spec=True, argument_spec=dict( name=dict( type="str", required=True, ), interface1=dict(type="str", required=True), interface2=dict(type="str", required=True), tag=dict(type="int"), multicast=dict(type="bool"), pass_through=dict(type="bool"), ), ) 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"], "interface1": module.params["interface1"], "interface2": module.params["interface2"], "tag": module.params["tag"], "multicast": module.params["multicast"], "pass_through": module.params["pass_through"], } obj = VirtualWire(**spec) try: listing = VirtualWire.refreshall(parent, matching_vsys=False) except PanDeviceError as e: module.fail_json(msg="Failed refresh: {0}".format(e)) reference_params = { "refresh": True, "update": not module.check_mode, "return_type": "bool", } parent.add(obj) changed = False if module.params["state"] == "present": for vwire in listing: if vwire.name != obj.name: continue if not vwire.equal(obj, compare_children=False): changed = True obj.extend(vwire.children) if not module.check_mode: try: obj.apply() except PanDeviceError as e: module.fail_json(msg="Failed apply: {0}".format(e)) break else: changed = True if not module.check_mode: try: obj.create() except PanDeviceError as e: module.fail_json(msg="Failed create: {0}".format(e)) try: changed |= obj.set_vsys(module.params["vsys"], **reference_params) except PanDeviceError as e: module.fail_json(msg="Failed setref: {0}".format(e)) elif module.params["state"] == "absent": try: changed |= obj.set_vsys(None, **reference_params) except PanDeviceError as e: module.fail_json(msg="Failed setref: {0}".format(e)) if obj.name in [x.name for x in listing]: changed = True if not module.check_mode: try: obj.delete() except PanDeviceError as e: module.fail_json(msg="Failed delete: {0}".format(e)) 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, ) # 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')
def main(): helper = get_connection( template=True, template_stack=True, with_classic_provider_spec=True, with_state=True, required_one_of=[[ 'lifetime_seconds', 'lifetime_minutes', 'lifetime_hours', 'lifetime_days' ]], argument_spec=dict( name=dict(required=True), esp_encryption=dict(type='list', choices=[ 'des', '3des', 'null', 'aes-128-cbc', 'aes-192-cbc', 'aes-256-cbc', 'aes-128-gcm', 'aes-256-gcm' ], aliases=['encryption']), esp_authentication=dict( type='list', choices=['none', 'md5', 'sha1', 'sha256', 'sha384', 'sha512'], aliases=['authentication']), ah_authentication=dict( type='list', choices=['md5', 'sha1', 'sha256', 'sha384', 'sha512']), dh_group=dict(choices=[ 'no-pfs', 'group1', 'group2', 'group5', 'group14', 'group19', 'group20' ], default='group2', aliases=['dhgroup']), lifetime_seconds=dict(type='int'), lifetime_minutes=dict(type='int'), lifetime_hours=dict(type='int', aliases=['lifetime_hrs']), lifetime_days=dict(type='int'), lifesize_kb=dict(type='int'), lifesize_mb=dict(type='int'), lifesize_gb=dict(type='int'), lifesize_tb=dict(type='int'), commit=dict(type='bool', default=True))) module = AnsibleModule( argument_spec=helper.argument_spec, required_one_of=helper.required_one_of, mutually_exclusive=[['esp_encryption', 'ah_authentication'], ['esp_authentication', 'ah_authentication'], [ 'lifetime_seconds', 'lifetime_minutes', 'lifetime_hours', 'lifetime_days' ], [ 'lifesize_kb', 'lifesize_mb', 'lifesize_gb', 'lifesize_tb' ]], supports_check_mode=True) # Verify libs are present, get parent object. parent = helper.get_pandevice_parent(module) spec = { 'name': module.params['name'], 'esp_encryption': module.params['esp_encryption'], 'esp_authentication': module.params['esp_authentication'], 'ah_authentication': module.params['ah_authentication'], 'dh_group': module.params['dh_group'], 'lifetime_seconds': module.params['lifetime_seconds'], 'lifetime_minutes': module.params['lifetime_minutes'], 'lifetime_hours': module.params['lifetime_hours'], 'lifetime_days': module.params['lifetime_days'], 'lifesize_kb': module.params['lifesize_kb'], 'lifesize_mb': module.params['lifesize_mb'], 'lifesize_gb': module.params['lifesize_gb'], 'lifesize_tb': module.params['lifesize_tb'] } # Other info. commit = module.params['commit'] if spec['esp_encryption'] is None and spec['ah_authentication'] is None: spec['esp_encryption'] = ['aes-256-cbc', '3des'] if spec['esp_authentication'] is None and spec['ah_authentication'] is None: spec['esp_authentication'] = ['sha1'] # Reflect GUI behavior. Default is 1 hour key lifetime if nothing else is # specified. if not any([ spec['lifetime_seconds'], spec['lifetime_minutes'], spec['lifetime_hours'], spec['lifetime_days'] ]): spec['lifetime_hours'] = 1 # Retrieve current info. try: listing = IpsecCryptoProfile.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 = IpsecCryptoProfile(**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)
def main(): helper = get_connection(template=True, template_stack=True, with_classic_provider_spec=True, with_state=True, argument_spec=dict( name=dict(type='str', required=True), tunnel_name=dict(default='default'), local=dict(default='192.168.2.0/24'), remote=dict(default='192.168.1.0/24'), any_protocol=dict(type='bool', default=True), number_proto=dict(type='int'), tcp_local_port=dict(type='int'), tcp_remote_port=dict(type='int'), udp_local_port=dict(type='int'), udp_remote_port=dict(type='int'), commit=dict(type='bool', default=False), )) module = AnsibleModule(argument_spec=helper.argument_spec, supports_check_mode=True, required_one_of=helper.required_one_of) # Object specifications spec = { 'name': module.params['name'], 'local': module.params['local'], 'remote': module.params['remote'], 'any_protocol': module.params['any_protocol'], 'number_protocol': module.params['number_proto'], 'tcp_local_port': module.params['tcp_local_port'], 'tcp_remote_port': module.params['tcp_remote_port'], 'udp_local_port': module.params['udp_local_port'], 'udp_remote_port': module.params['udp_remote_port'], } # Additional infos commit = module.params['commit'] # Verify libs are present, get parent object. parent = helper.get_pandevice_parent(module) tunnel_name = module.params['tunnel_name'] # get the tunnel object tunnel = IpsecTunnel(tunnel_name) parent.add(tunnel) try: tunnel.refresh() except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) # get the listing listing = tunnel.findall(IpsecTunnelIpv4ProxyId) obj = IpsecTunnelIpv4ProxyId(**spec) tunnel.add(obj) # Apply the state. changed, diff = helper.apply_state(obj, listing, module) # Commit. if commit and changed: helper.commit(module) # Done. module.exit_json(changed=changed, diff=diff)
def main(): helper = get_connection( vsys_importable=True, template=True, with_classic_provider_spec=True, with_state=True, min_pandevice_version=(0, 13, 0), argument_spec=dict( if_name=dict(required=True), mode=dict( default='layer3', choices=['layer3', 'layer2', 'virtual-wire', 'ha'], ), ip=dict(type='list'), ipv6_enabled=dict(type='bool'), management_profile=dict(), mtu=dict(type='int'), adjust_tcp_mss=dict(type='bool'), netflow_profile=dict(), lldp_enabled=dict(type='bool'), lldp_profile=dict(), comment=dict(), ipv4_mss_adjust=dict(type='int'), ipv6_mss_adjust=dict(type='int'), enable_dhcp=dict(type='bool'), create_dhcp_default_route=dict(type='bool'), dhcp_default_route_metric=dict(type='int'), zone_name=dict(), vr_name=dict(default='default'), commit=dict(type='bool', default=True), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=True, required_one_of=helper.required_one_of, ) # 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'], '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'], 'create_dhcp_default_route': module.params['create_dhcp_default_route'], 'dhcp_default_route_metric': module.params['dhcp_default_route_metric'], } # Get other info. state = module.params['state'] zone_name = module.params['zone_name'] vr_name = module.params['vr_name'] vsys = module.params['vsys'] commit = module.params['commit'] # Verify libs are present, get the parent object. parent = helper.get_pandevice_parent(module) # Retrieve the current config. try: interfaces = AggregateInterface.refreshall( parent, add=False, matching_vsys=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) # Build the object based on the user spec. obj = AggregateInterface(**spec) parent.add(obj) # Which action should we take on the interface? changed = False reference_params = { 'refresh': True, 'update': not module.check_mode, 'return_type': 'bool', } if state == 'present': for item in interfaces: if item.name != obj.name: continue # Interfaces have children, so don't compare them. if not item.equal(obj, compare_children=False): changed = True obj.extend(item.children) if not module.check_mode: try: obj.apply() except PanDeviceError as e: module.fail_json(msg='Failed apply: {0}'.format(e)) break else: changed = True if not module.check_mode: try: obj.create() except PanDeviceError as e: module.fail_json(msg='Failed create: {0}'.format(e)) # Set references. try: changed |= obj.set_vsys(vsys, **reference_params) changed |= obj.set_zone(zone_name, mode=eth.mode, **reference_params) changed |= obj.set_virtual_router(vr_name, **reference_params) except PanDeviceError as e: module.fail_json(msg='Failed setref: {0}'.format(e)) elif state == 'absent': # Remove references. try: changed |= obj.set_virtual_router(None, **reference_params) changed |= obj.set_zone(None, mode=eth.mode, **reference_params) changed |= obj.set_vsys(None, **reference_params) except PanDeviceError as e: module.fail_json(msg='Failed setref: {0}'.format(e)) # Remove the interface. if obj.name in [x.name for x in interfaces]: changed = True if not module.check_mode: try: obj.delete() except PanDeviceError as e: module.fail_json(msg='Failed delete: {0}'.format(e)) # Commit if we were asked to do so. if changed and commit: helper.commit(module) # Done! module.exit_json(changed=changed, msg='Done')
def main(): helper = get_connection( template=True, template_stack=True, with_classic_provider_spec=True, with_state=True, min_pandevice_version=(0, 8, 0), argument_spec=dict( name=dict(required=True), ping=dict(type='bool'), telnet=dict(type='bool'), ssh=dict(type='bool'), http=dict(type='bool'), http_ocsp=dict(type='bool'), https=dict(type='bool'), snmp=dict(type='bool'), response_pages=dict(type='bool'), userid_service=dict(type='bool'), userid_syslog_listener_ssl=dict(type='bool'), userid_syslog_listener_udp=dict(type='bool'), permitted_ip=dict(type='list', elements='str'), commit=dict(type='bool', default=False), # TODO(gfreeman) - Removed in the next role release. panorama_template=dict(), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=True, required_one_of=helper.required_one_of, ) # TODO(gfreeman) - Removed when "panorama_template" is removed. if module.params['panorama_template'] is not None: module.deprecate( 'Param "panorama_template" is deprecated; use "template"', version='3.0.0', collection_name='paloaltonetworks.panos') if module.params['template'] is not None: msg = [ 'Both "template" and "panorama_template" have been given', 'Specify one or the other, not both.', ] module.fail_json(msg='. '.join(msg)) module.params['template'] = module.params['panorama_template'] # Verify imports, build pandevice object tree. parent = helper.get_pandevice_parent(module) # Build the object based on the spec. obj = ManagementProfile(*[ module.params[x] for x in ('name', 'ping', 'telnet', 'ssh', 'http', 'http_ocsp', 'https', 'snmp', 'response_pages', 'userid_service', 'userid_syslog_listener_ssl', 'userid_syslog_listener_udp', 'permitted_ip') ]) parent.add(obj) # Retrieve current config. try: profiles = ManagementProfile.refreshall(parent, add=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) # Perform requested action. changed, diff = helper.apply_state(obj, profiles, module) if changed and module.params['commit']: helper.commit(module) # Done. module.exit_json(changed=changed, diff=diff, 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=(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, diff = helper.apply_state(obj, listing, 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 = 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( 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( vsys=True, device_group=True, rulebase=True, with_classic_provider_spec=True, error_on_firewall_shared=True, argument_spec=dict( rule_name=dict(), names=dict(type='list', elements='str'), details=dict(default=False, type='bool', aliases=['all_details']), match_rules=dict(type='dict', options=dict(source_zone=dict(type='str', required=True), source_ip=dict(type='str', required=True), source_user=dict(type='str'), destination_zone=dict(type='str', required=True), destination_ip=dict(type='str', required=True), destination_port=dict(type='str', required=True), protocol=dict( type='str', choices=['tcp', 'udp', 'icmp'], required=True), application=dict(type='str'), category=dict(type='str'), show_all=dict(type='bool'))), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=False, required_one_of=helper.required_one_of, ) parent = helper.get_pandevice_parent(module) 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'), ) names = module.params['names'] details = module.params['details'] if module.params.get('all_details'): module.deprecate('Please use details instead of all_details.', version='3.0.0', collection_name='paloaltonetworks.panos') if module.params['rule_name']: module.deprecate( 'Please use the names parameter instead of rule_name.', version='3.0.0', collection_name='paloaltonetworks.panos') names = [module.params['rule_name']] if module.params['match_rules']: names = match_rules(module, parent.nearest_pandevice()) if names is None and details is False: # Didn't specify specific rules, so just return list of rule names. listing = SecurityRule.refreshall(parent, name_only=True) module.exit_json(changed=False, rule_names=[r.name for r in listing]) elif module.params['match_rules'] and details is False: # match_rules was set, but not details, so return list of rule names. module.exit_json(changed=False, rule_names=names) else: # Return full policy details. Will return full policy details even if # details is False if specific rules are given, because returning the # user's list of rules back to them is pointless. if names is None: listing = SecurityRule.refreshall(parent) rules = [rule.about() for rule in listing] else: rules = [] for name in names: rule = SecurityRule(name) parent.add(rule) try: rule.refresh() except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) rules.append(rule.about()) # Fix up names in returned dict. for rule in rules: for p, a in renames: rule[a] = rule[p] del rule[p] module.exit_json(changed=False, rule_details=rules)
def main(): helper = get_connection( vsys_importable=True, template=True, template_stack=True, with_state=True, with_classic_provider_spec=True, argument_spec=dict( name=dict(required=True, ), interface=dict(type='list', elements='str'), virtual_interface=dict(), ), ) 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'], 'interface': module.params['interface'], 'virtual_interface': module.params['virtual_interface'], } obj = Vlan(**spec) try: listing = Vlan.refreshall(parent, matching_vsys=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) reference_params = { 'refresh': True, 'update': not module.check_mode, 'return_type': 'bool', } parent.add(obj) changed = False if module.params['state'] == 'present': for vlan in listing: if vlan.name != obj.name: continue if not vlan.equal(obj, compare_children=False): changed = True obj.extend(vlan.children) if not module.check_mode: try: obj.apply() except PanDeviceError as e: module.fail_json(msg='Failed apply: {0}'.format(e)) break else: changed = True if not module.check_mode: try: obj.create() except PanDeviceError as e: module.fail_json(msg='Failed create: {0}'.format(e)) try: changed |= obj.set_vsys(module.params['vsys'], **reference_params) except PanDeviceError as e: module.fail_json(msg='Failed setref: {0}'.format(e)) elif module.params['state'] == 'absent': try: changed |= obj.set_vsys(None, **reference_params) except PanDeviceError as e: module.fail_json(msg='Failed setref: {0}'.format(e)) if obj.name in [x.name for x in listing]: changed = True if not module.check_mode: try: obj.delete() except PanDeviceError as e: module.fail_json(msg='Failed delete: {0}'.format(e)) module.exit_json(changed=changed, msg='done')
def main(): helper = get_connection( template=True, template_stack=True, with_classic_provider_spec=True, with_state=True, argument_spec=dict( name=dict(required=True), version=dict(default='ikev2', choices=['ikev1', 'ikev2', 'ikev2-preferred'], aliases=['protocol_version']), interface=dict(default='ethernet1/1'), local_ip_address_type=dict(default=None, choices=['ip', 'floating-ip']), local_ip_address=dict(default=None), enable_passive_mode=dict(type='bool', default=True, aliases=['passive_mode']), enable_nat_traversal=dict(type='bool', default=False, aliases=['nat_traversal']), enable_fragmentation=dict(type='bool', default=False, aliases=['fragmentation']), enable_liveness_check=dict(type='bool', default=True), liveness_check_interval=dict(type='int', default=5, aliases=['liveness_check']), peer_ip_type=dict(default='ip', choices=['ip', 'dynamic', 'fqdn']), peer_ip_value=dict(default='127.0.0.1'), enable_dead_peer_detection=dict(type='bool', default=False, aliases=['dead_peer_detection']), dead_peer_detection_interval=dict(type='int', default=99), dead_peer_detection_retry=dict(type='int', default=10), pre_shared_key=dict(no_log=True, default='CHANGEME', aliases=['psk']), local_id_type=dict( default=None, choices=['ipaddr', 'fqdn', 'ufqdn', 'keyid', 'dn']), local_id_value=dict(default=None), peer_id_type=dict( default=None, choices=['ipaddr', 'fqdn', 'ufqdn', 'keyid', 'dn']), peer_id_value=dict(default=None), peer_id_check=dict(choices=['exact', 'wildcard']), ikev1_crypto_profile=dict(default='default', aliases=['crypto_profile_name']), ikev1_exchange_mode=dict(default=None, choices=['auto', 'main', 'aggressive']), ikev2_crypto_profile=dict(default='default', aliases=['crypto_profile_name']), commit=dict(type='bool', default=False), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=True, required_one_of=helper.required_one_of, required_together=[ ['peer_id_value', 'peer_id_type'], ['local_id_value', 'local_id_type'], ['local_ip_address', 'local_ip_address_type'], ], ) # Verify libs are present, get parent object. parent = helper.get_pandevice_parent(module) # Object params. spec = { 'name': module.params['name'], 'version': module.params['version'], 'interface': module.params['interface'], 'local_ip_address_type': module.params['local_ip_address_type'], 'local_ip_address': module.params['local_ip_address'], 'auth_type': 'pre-shared-key', 'enable_passive_mode': module.params['enable_passive_mode'], 'enable_nat_traversal': module.params['enable_nat_traversal'], 'enable_fragmentation': module.params['enable_fragmentation'], 'enable_liveness_check': module.params['enable_liveness_check'], 'liveness_check_interval': module.params['liveness_check_interval'], 'peer_ip_type': module.params['peer_ip_type'], 'peer_ip_value': module.params['peer_ip_value'], 'enable_dead_peer_detection': module.params['enable_dead_peer_detection'], 'dead_peer_detection_interval': module.params['dead_peer_detection_interval'], 'dead_peer_detection_retry': module.params['dead_peer_detection_retry'], 'pre_shared_key': module.params['pre_shared_key'], 'local_id_type': module.params['local_id_type'], 'local_id_value': module.params['local_id_value'], 'peer_id_type': module.params['peer_id_type'], 'peer_id_value': module.params['peer_id_value'], 'peer_id_check': module.params['peer_id_check'], 'ikev1_crypto_profile': module.params['ikev1_crypto_profile'], 'ikev1_exchange_mode': module.params['ikev1_exchange_mode'], 'ikev2_crypto_profile': module.params['ikev2_crypto_profile'], } # Remove the IKEv1 crypto profile if we're doing IKEv2. if spec['version'] == 'ikev2': spec['ikev1_crypto_profile'] = None # Remove the IKEv2 crypto profile if we're doing IKEv1. if spec['version'] == 'ikev1': spec['ikev2_crypto_profile'] = None # Other info. commit = module.params['commit'] # Retrieve current info. try: listing = IkeGateway.refreshall(parent, add=False) except PanDeviceError as e: module.fail_json(msg='Failed refresh: {0}'.format(e)) obj = IkeGateway(**spec) parent.add(obj) # Apply the state. changed, diff = helper.apply_state(obj, listing, module) # Commit. if commit and changed: helper.commit(module) # Done. module.exit_json(changed=changed, diff=diff)
def main(): helper = get_connection( template=True, template_stack=True, template_is_optional=True, with_state=True, with_classic_provider_spec=True, min_pandevice_version=(0, 8, 0), argument_spec=dict( admin_username=dict(default="admin"), authentication_profile=dict(), web_client_cert_only=dict(type="bool"), superuser=dict(type="bool"), superuser_read_only=dict(type="bool"), panorama_admin=dict(type="bool"), device_admin=dict(type="bool"), device_admin_read_only=dict(type="bool"), vsys=dict(type="list", elements="str"), vsys_read_only=dict(type="list", elements="str"), ssh_public_key=dict(), role_profile=dict(), admin_password=dict(no_log=True), admin_phash=dict(no_log=True), password_profile=dict(no_log=False), commit=dict(type="bool", default=False), ), ) 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) # Get administrator object spec. spec_params = [ "authentication_profile", "web_client_cert_only", "superuser", "superuser_read_only", "panorama_admin", "device_admin", "device_admin_read_only", "vsys", "vsys_read_only", "ssh_public_key", "role_profile", "password_profile", ] params = dict((k, module.params[k]) for k in spec_params) params["name"] = module.params["admin_username"] password = module.params["admin_password"] phash = module.params["admin_phash"] # Get other params. state = module.params["state"] commit = module.params["commit"] # Get the current administrators. try: admins = Administrator.refreshall(parent, add=False) except PanDeviceError as e: module.fail_json(msg="Failed refresh: {0}".foramt(e)) obj = Administrator(**params) parent.add(obj) # Set "password_hash" by requesting a password hash. if password is not None: try: obj.password_hash = helper.device.request_password_hash(password) except PanDeviceError as e: module.fail_json(msg="Failed to get phash: {0}".format(e)) elif phash is not None: obj.password_hash = phash # Perform the requested action. changed = False if state == "present": for item in admins: if item.name != obj.name: continue # If user did not specify a password, keep the current one. if obj.password_hash is None and item.password_hash: obj.password_hash = item.password_hash # Don't use .equal() here because we don't want pandevice to # try and do smart things with the password_hash field. if obj.element_str() != item.element_str(): changed = True if not module.check_mode: try: obj.apply() except PanDeviceError as e: module.fail_json(msg="Failed apply: {0}".format(e)) # If changing the current user's password, we have to # fetch the new API key before any subsequent API commands # (aka - commit) will work. if helper.device._api_username == obj.name and ( password is not None or phash is not None ): if phash is not None: msg = [ "Password of current user was changed by hash.", "Exiting module as API key cannot be determined.", ] module.warn(" ".join(msg)) module.exit_json(changed=changed) helper.device._api_key = None helper.device._api_password = password try: helper.device.xapi.api_key = helper.device.api_key except PanDeviceError as e: module.fail_json( msg="Failed API key refresh: {0}".format(e) ) break else: changed = True if not module.check_mode: try: obj.create() except PanDeviceError as e: module.fail_json(msg="Failed create: {0}".format(e)) elif state == "absent": if obj.name in [x.name for x in admins]: changed = True if not module.check_mode: try: obj.delete() except PanDeviceError as e: module.fail_json(msg="Failed delete: {0}".format(e)) # Commit if appropriate. if changed and commit: helper.commit(module) # Done. 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')