Cisco Secure Access Policy Rules sample script

Policy Rules API Guide

This guide provides Python client samples for the Cisco Secure Access Policy Rules API.

Note: Your Secure Access API key must have the permissions to read and write on the policies key scope. For more information about the API key scopes, see Secure Access OAuth 2.0 Scopes.

First get your Secure Access API key, set up your environment, and install the Secure Access API client. For more information, see Samples Overview.

Run the Script

  1. Copy the script to a local file called main.py. Locate the script in your environment in a directory above the cisco directory.
  2. Run python3 main.py.

main.py

"""
Copyright (c) 2025 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at

https://developer.cisco.com/docs/licenses

All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately in
writing, software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied.
"""

import requests
from requests_toolbelt import MultipartEncoder
import json
import os
from dotenv import load_dotenv

from cisco.secure_access import API
from cisco.secure_access import policies
from cisco.secure_access import GET
from cisco.secure_access import POST
from cisco.secure_access import PUT
from cisco.secure_access import DELETE
from cisco.secure_access import token_url
from cisco.secure_access import client_id
from cisco.secure_access import client_secret

# Policy Rules API endpoints
policies_endpoint = 'policies'
policies_details_endpoint = 'policies/{}'
settings_endpoint = 'settings'
settings_details_endpoint = 'settings/{}'
setting_types_endpoint = 'settingTypes'
setting_types_details_endpoint = 'settingTypes/{}'
rules_endpoint = 'rules'
rules_details_endpoint = 'rules/{}'

load_dotenv()

def get_settings(api):
    ''' Get Rule Settings. '''
    try:
        # Get Rule Settings.
        response = api.Query(policies, settings_endpoint, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. GET {settings_endpoint}, {response.json()}")
            return response.json()
        else:
            print(f"Failed to get the Rule Settings. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def put_settings(api, payload=None):
    ''' Update Rule Settings. '''
    try:
        if payload is None:
            raise ValueError("payload is required to create the Rule Setting.")

        # Update Rule Settings
        response = api.Query(policies, settings_endpoint, PUT, payload)

        # Check the response status
        if response.status_code == 201:
            print(f"Success. PUT {settings_endpoint}, {response.json()}")
            return response.json()
        else:
            print(f"Failed to update the Rule Settings. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except Exception as e:
        print(f"An error occurred: {e}.")

def get_setting(api, setting_name):
    ''' Get the properties of a Rule Setting. '''
    try:
        if setting_name is None:
            raise ValueError("setting_name is required to get the Rule Setting.")

        url = settings_details_endpoint.format(setting_name)

        # Get the properties of a Rule Setting.
        response = api.Query(policies, url, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. GET {url}, {response.json()}")
            return response.json()
        else:
            print(f"Failed to get the properties of the Rule Setting. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def put_setting(api, setting_name, payload=None):
    ''' Update the properties of a Rule Setting. '''
    try:
        if setting_name is None:
            raise ValueError("setting_name is required to get the Rule Setting.")

        if payload is None:
            raise ValueError("payload is required to create the Rule Setting.")

        url = settings_details_endpoint.format(setting_name)

        # Update the properties for the Rule Setting.
        response = api.Query(policies, url, PUT, payload)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. PUT {url}, {response.json()}.")
            return response.json()
        else:
            print(f"Failed to update the Rule Setting {setting_name}. Status code: {response.status_code}, Response: {response.text}.")
            return
    except Exception as e:
        print(f"An error occurred: {e}.")

def get_setting_types(api):
    ''' Get Rule Setting Types. '''
    try:
        # Get Rule Setting Types.
        response = api.Query(policies, setting_types_endpoint, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. GET {setting_types_endpoint}, {response.json()}")
            return response.json()
        else:
            print(f"Failed to get the Rule Setting Types. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def get_setting_type(api, setting_name):
    ''' Get the properties of the Setting Type. '''
    try:
        if setting_name is None:
            raise ValueError("setting_name is required to get the Private Resource Group.")
        url = setting_types_details_endpoint.format(setting_name)

        # Get the properties for the Setting Type
        response = api.Query(policies, url, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. GET {url}, {response.json()}.")
            return response.json()
        else:
            print(f"Failed to get the Setting Type {setting_name}. Status code: {response.status_code}, Response: {response.text}.")
            return
    except Exception as e:
        print(f"An error occurred: {e}.")

def get_rules(api):
    ''' Get Rules. '''
    try:
        # Get Access Rules.
        response = api.Query(policies, rules_endpoint, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. GET {rules_endpoint}, {response.json()}")
            return response.json()
        else:
            print(f"Failed to get the Rules. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def post_rules(api, payload=None):
    ''' Create an Access Rule. '''
    try:
        if payload is None:
            raise ValueError("payload is required to create the Access Rule.")

        # Create Rule
        response = api.Query(policies, rules_endpoint, POST, payload)

        # Check the response status
        if response.status_code == 200:
            print(f"Success. POST {rules_endpoint}, {response.json()}")
            return response.json()
        else:
            print(f"Failed to create the Rule. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except Exception as e:
        print(f"An error occurred: {e}.")

def put_rules(api, payload=None):
    ''' Update Access Rules. '''
    try:
        if payload is None:
            raise ValueError("payload is required to update the Access Rule.")

        # Update Rules
        response = api.Query(policies, rules_endpoint, PUT, payload)

        # Check the response status
        if response.status_code == 200:
            print(f"Success. PUT {rules_endpoint}, {response.json()}")
            return response.json()
        else:
            print(f"Failed to update the Rules. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except Exception as e:
        print(f"An error occurred: {e}.")

def get_rule(api, id):
    ''' Get the properties of the Access Rule. '''
    try:
        if id is None:
            raise ValueError("id is required to get the Access Rule.")
        url = rules_details_endpoint.format(id)

        # Get the properties for the Access Rule
        response = api.Query(policies, url, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. GET {url}, {response.json()}.")
            return response.json()
        else:
            print(f"Failed to get the Rule {id}. Status code: {response.status_code}, Response: {response.text}.")
            return
    except Exception as e:
        print(f"An error occurred: {e}.")

def put_rule(api, id, payload=None):
    ''' Update the properties of the Access Rule. '''
    try:
        if id is None or payload is None:
            raise ValueError("id and payload are required to update the Access Rule.")
        url = rules_details_endpoint.format(id)

        # Update the properties of the Access Rule
        response = api.Query(policies, url, PUT, payload)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. PUT {url}, {response.json()}.")
            return response.json()
        else:
            print(f"Failed to update the Rule {id}. Status code: {response.status_code}, Response: {response.text}.")
            return
    except Exception as e:
        print(f"An error occurred: {e}.")

def delete_rule(api, id):
    ''' Delete the Access Rule. '''
    try:
        if id is None:
            raise ValueError("id is required to delete the Access Rule.")
        url = rules_details_endpoint.format(id)

        # Delete the Access Rule
        response = api.Query(policies, url, DELETE)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"DELETE {url} Response: {response.text}.")
        else:
            print(f"Failed to delete the Access Rule {id}. Status code: {response.status_code}, Response: {response.text}.")
    except Exception as e:
        print(f"An error occurred: {e}.")

def main():
    # Exit out if the required client_id or client_secret is not set
    for var in ['API_KEY', 'API_SECRET', 'OUTPUT_DIR']:
        if os.environ.get(var) == None:
            print("Required environment variable: {} not set".format(var))
            exit()

    # Get an API token
    api = API(token_url, client_id, client_secret)

    try:
        # Get settings on the rules in the organization
        json_data = get_settings(api)

        # Update settings with an array of settings
        data = []
        setting_1 = {
            "settingName": "umbrella.logLevel",
            "settingValue": "LOG_ALL"
        }
        setting_2 = {
            "settingName": "sse.globalIPSEnabled",
            "settingValue": True
        }
        data.append(setting_1)
        data.append(setting_2)
        json_data = put_settings(api, data)

        # Get setting by setting name
        json_data = get_setting(api, "umbrella.logLevel")

        # Update setting by setting name. Accepts an object with settingName and settingValue
        data = {}
        data['settingName'] = "umbrella.logLevel"
        data['settingValue'] = "LOG_NONE"
        json_data = put_setting(api, "umbrella.logLevel", data)

        # Reset log level setting
        data = {}
        data['settingName'] = "umbrella.logLevel"
        data['settingValue'] = "LOG_ALL"
        json_data = put_setting(api, "umbrella.logLevel", data)

        # Get the types of the settings
        json_data = get_setting_types(api)

        # Get a specific type of setting
        json_data = get_setting_type(api, "umbrella.logLevel")

        # Get the rules in the Access policy.
        json_data = get_rules(api)
        result = json_data['results']

        # Create a rule in the Access policy.
        data = {}
        data['ruleName'] = "testwhynot"
        data['ruleAction'] = "allow"
        data['ruleDescription'] =  "create a new rule for any to any."
        data['ruleConditions'] = [
            {
                "attributeName": "umbrella.destination.all",
                "attributeValue": True,
                "attributeOperator": "="
            },
            {
                "attributeName": "umbrella.source.all",
                "attributeValue": True,
                "attributeOperator": "=",
            }
        ]
        data['ruleSettings'] = [
            {
               "settingName": "umbrella.logLevel",
                "settingValue": "LOG_ALL"
            },
            {
                "settingName": "umbrella.default.traffic",
                "settingValue": "PUBLIC_INTERNET"
            }
        ]
        json_data = post_rules(api, data)

        # Get rule
        rule_id = json_data['ruleId']
        json_data = get_rule(api, rule_id)

        # Update rules in the Access policy.
        data = {}
        data['ruleIds'] = []
        data['ruleIds'].append(rule_id)
        data['properties'] = []
        data['properties'].append( { "ruleIsEnabled": False })
        json_data = put_rules(api, data)

        # Reenable the test rule
        data = {}
        data['ruleIds'] = []
        data['ruleIds'].append(rule_id)
        data['properties'] = []
        data['properties'].append( { "ruleIsEnabled": True })
        json_data = put_rules(api, data)

        # Update a rule. Change the priority for the rule to an existing priority of another rule.
        data = {}
        data['ruleName'] = "testa"
        data['ruleAction'] = "allow"
        data['ruleDescription'] =  "aupdate a rule for any to any."
        data['rulePriority'] = 1
        data['ruleConditions'] = [
            {
                "attributeName": "umbrella.destination.all",
                "attributeValue": True,
                "attributeOperator": "="
            },
            {
                "attributeName": "umbrella.source.all",
                "attributeValue": True,
                "attributeOperator": "=",
            }
        ]
        data['ruleSettings'] = [
            {
               "settingName": "umbrella.logLevel",
                "settingValue": "LOG_ALL"
            },
            {
                "settingName": "umbrella.default.traffic",
                "settingValue": "PUBLIC_INTERNET"
            }
        ]
        json_data = put_rule(api, rule_id, data)

        # Delete the rule
        delete_rule(api, rule_id)
    except Exception as e:
        print(e)

# main
if __name__ == "__main__":
    main()