Create and Manage Tenants

The Deep Security API enables you to programmatically create, modify, and delete tenants on Deep Security Manager.

For more information about multi-tenant deployments, see the Deep Security Help Center.

Enable multi-tenancy

Before you can interact with tenants, you need to enable multi-tenancy on Deep Security Manager. You must use the UI to enable multi-tenancy.

Create and configure a tenant

Create a tenant and configure the runtime aspects of the account:

  • Which security modules are visible to them in Deep Security Manager
  • Which database server to use (if Deep Security Manager uses multiple databases)
  • Locale and location details

To create a tenant using a client library, you create a Tenant object, set the property values, and then use a TenantsApi object to create the tenant on Deep Security Manager. One of the Tenant object properties is an Administrator object with, at a minimum, the user name, password, and email address defined. When the tenant is created, the administrator account is created on the tenant, and you use the account’s credentials to log into the tenant.

When creating a tenant, the following administrator account properties are persisted: the user name, password, time format, timezone, role, and all boolean properties. All other properties are ignored.

Example: Create a tenant

Python
def create_tenant(client, configuration, api_version, api_exception, account_name):
    """ Creates a tenant on the primary Deep Security Manager.

    :param client: The Deep Security API modules.
    :param configuration: Configuration object to pass to the client.
    :param api_version: The version of the API to use.
    :param api_exception: The Deep Security API exception module.
    :param account_name: The account name to use for the tenant.
    :return: A TenantsApi object that contains the new tenant.
    """

    # Define the administrator account
    admin = client.Administrator()
    admin.username = "TenantAdmin"
    admin.password = "Pas$w0rd"
    admin.email_address = "example@email.com"
    admin.receive_notifications = "false"
    admin.role_id = 1

    # Create a tenant
    tenant = client.Tenant(administrator=admin)

    # Set the visible modules
    modules = client.Tenant.modules_visible = ["anti-malware", "firewall", "intrusion-prevention"]
    tenant.modules_visible = modules

    # Set the account name
    tenant.name = account_name

    # Set the locale and description
    tenant.locale = "en-US"
    tenant.description = "Test tenant."

    # Create the tenant on Deep Security Manager
    try:
        tenants_api = client.TenantsApi(client.ApiClient(configuration))
        return tenants_api.create_tenant(tenant, api_version, confirmation_required=False)

    except api_exception as e:
        return "Exception: " + str(e)
JavaScript
/*
* Creates a tenant.
* @param {object} api The api module.
* @param {String} accountName The account name to use for the tenant.
* @param {String} apiVersion The api version to use.
* @return {Promise} A promise that contains the new tentant.
*/
exports.createTenant = function (api, accountName, apiVersion) {
  return new Promise((resolve, reject) => {
    // Tenant object
    const tenant = new api.Tenant();

    // Set the visible modules
    tenant.modulesVisible = [
      api.Tenant.ModulesVisibleEnum["anti-malware"],
      api.Tenant.ModulesVisibleEnum.firewall,
      api.Tenant.ModulesVisibleEnum["intrusion-prevention"]
    ];

    // Set the account name
    tenant.name = accountName;

    // Define the administrator account
    const admin = new api.Administrator();
    admin.username = "MasterAdmin";
    admin.password = "P@55word";
    admin.emailAddress = "example@email.com";
    tenant.administrator = admin;

    // Set the locale and description
    tenant.locale = api.Tenant.LocaleEnum["en-US"];
    tenant.description = "Test tenant.";

    // Creates the tenant
    const createTenant = () => {
      const tenantsApi = new api.TenantsApi();
      return tenantsApi.createTenant(tenant, apiVersion, {
        confirmationRequired: "false",
        asynchronous: "true"
      });
    };

    createTenant()
      .then(newTenant => {
        resolve(newTenant);
      })
      .catch(error => {
        reject(error);
      });
  });
};
Java
/*
 * Creates a tenant on the primary Deep Security Manager
 * @param activationCode The activation code for the tenant if required.
 * @param admin An Administrator object that contains credentials.
 * @return The new tenant.
 */
public static Tenant createTenant(String accountName) {
    // Create and configure a Tenant object
    Tenant tenant = new Tenant();

    // Set module visibility
    List<ModulesVisibleEnum> modules = new ArrayList<ModulesVisibleEnum>();
    modules.add(ModulesVisibleEnum.ANTI_MALWARE);
    modules.add(ModulesVisibleEnum.FIREWALL);
    modules.add(ModulesVisibleEnum.INTRUSION_PREVENTION);

    // Administrator account
    Administrator admin = new Administrator();
    admin.setUsername("MasterAdmin");
    admin.setPassword("P@55word");
    admin.setEmailAddress("bad@email.com");

    tenant.setName(accountName);
    tenant.setLocale(Tenant.LocaleEnum.EN_US);
    tenant.setDescription("Test tenant.");
    tenant.setAdministrator(admin);
    tenant.setModulesVisible(modules);

    // Add the tenant to the manager
    TenantsApi tenantsApi = new TenantsApi();
    try {
        tenant = tenantsApi.createTenant(tenant, true, false, true, "v1");
    } catch (ApiException e) {
        e.printStackTrace();
    }
    return tenant;
}

For information about authenticating API calls, see Authenticate with Deep Security Manager.

Authenticate with a tenant

To authenticate with a tenant you need to create a tenant API key and use the key to configure an ApiClient object.

Example: Create a tenant API key

Create an API key for a tenant so that you can use the API to automate tasks on the tenant. You use the primary manager to create the tenant key, so to perform the operation you authenticate with the primary manager. When the tenant key is created, it appears in the Deep Security Manager of the tenant account.

If you do not set the roleID for the key, the key is provided full access.

Python
tenant_id = 6
api_version = "v1"

# Create an API key
key = client.ApiKey()
key.key_name = "Temporary Key"
key.role_id = 1
key.locale = "en-US"
key.time_zone = "Asia/Tokyo"

# Generate the secret key for the tenant
tenants_api = deepsecurity.TenantsApi()
generated_key = tenants_api.generate_tenant_api_secret_key(tenant_id, key, api_version)
JavaScript
// Creates an API key
const createKey = () => {
  // ApiKey properties
  const key = new api.ApiKey();
  key.keyName = "Temporary Key";
  key.roleID = 1;
  key.locale = api.ApiKey.LocaleEnum["en-US"];
  key.timeZone = "Asia/Tokyo";
  const tenantsApi = new api.TenantsApi();
  return tenantsApi.generateTenantApiSecretKey(tenantID, key, apiVersion);
};
Java
// Create the key object
ApiKey key = new ApiKey();
key.setKeyName("Temporary Key");
key.setRoleID(1);
key.setLocale(ApiKey.LocaleEnum.EN_US);
key.setTimeZone("Asia/Tokyo");
// Add the key to Deep Security Manager
TenantsApi tenantsApi = new TenantsApi();
try {
    key = tenantsApi.generateTenantApiSecretKey(tenantID, key, "v1");
} catch (ApiException e) {
    e.printStackTrace();
}

Example: Configure an ApiClient object for a tenant

Configure the ApiClient to use the secret key of the tenant’s API key and then send requests to the Deep Security Manager of the tenant. From the secret key, the manager determines which tenant you are targeting.

After you configure the ApiClient, all calls are authenticated using the tenant’s API key and the calls target the associated tenant. After you are done interacting with the tenant and you want to make calls to the primary tenant, configure the ApiClient to use an API key for the primary tenant and then make the calls.

Python
tenant_client = deepsecurity.ApiClient()
tenant_client.configuration = deepsecurity.Configuration()
tenant_client.configuration.api_key['api-secret-key'] = tenant_key.secret_key
JavaScript
// Configure the ApiClient for connecting to the tenant
const tenantClient = api.ApiClient.instance;
const defaultAuthentication = tenantClient.authentications["DefaultAuthentication"];
defaultAuthentication.apiKey = tenantKey.secretKey;
Java
ApiClient tenantClient = Configuration.getDefaultApiClient();
ApiKeyAuth DefaultAuthentication = (ApiKeyAuth) tenantClient.getAuthentication("DefaultAuthentication");
DefaultAuthentication.setApiKey(tenantKey.getSecretKey());

Example: Obtain Intrusion Prevention states of tenant computers

The following example creates a tenant API key and uses the key to obtain Intrusion Prevention states of the tenant computers.

Tenant keys expire 6 hours after creation by default.

Python
def get_ip_states_for_tenant(client, configuration, api_version, api_exception, tenant_id):
    """ Obtains the running state of the Intrusion Prevention module for a tenant's computers.

    :param client: The Deep Security API modules.
    :param configuration: Configuration object to pass to the client.
    :param api_version: The version of the API to use.
    :param api_exception: The Deep Security API exception module.
    :param tenant_id: The ID of the tenant.
    :return: A dictionary that contains computer IDs and the module running state.
    """

    primary_key = configuration.api_key['api-secret-key']

    # Create an API key
    key = client.ApiKey()
    key.key_name = "Temporary Key for getting IP states from tenant computers"
    key.role_id = 1
    key.locale = "en-US"
    key.time_zone = "Asia/Tokyo"

    try:
        # Check that the tenant is in the 'active' state
        import time
        while True:
            state = client.TenantsApi(client.ApiClient(configuration)).describe_tenant(tenant_id, api_version).tenant_state
            if state == 'active':
                break
            time.sleep(5)

        # Generate the secret key for the tenant
        tenants_api = client.TenantsApi(client.ApiClient(configuration))
        generated_key = tenants_api.generate_tenant_api_secret_key(tenant_id, key, api_version)

        # Add the secret key to the configuration
        configuration.api_key['api-secret-key'] = generated_key.secret_key

        # Get a list of tenant computers
        computers_api = client.ComputersApi(client.ApiClient(configuration))
        computers_list = computers_api.list_computers(api_version)

        # Find the Intrusion Prevention state for each computer
        computer_ip_states = {}
        for computer in computers_list.computers:
            computer_ip_states[computer.id] = computer.intrusion_prevention.state

        # Delete an ApiKey from the tenant
        api_keys_api = client.APIKeysApi(client.ApiClient(configuration))
        api_keys_api.delete_api_key(generated_key.id, api_version)

        # Reset the API key to the primary key
        configuration.api_key['api-secret-key'] = primary_key

        return computer_ip_states

    except api_exception as e:
        return "Exception: " + str(e)
JavaScript
/*
* Obtains the running state of the Intrusion Prevention module for a tenant's computers.
* @param {object} api The api module.
* @param {Number} tenantID The ID of the tenant.
* @param {String} apiVersion The api version to use.
* @return {Promise} A promise that contains computer IDs and the module running state.
*/
exports.getIPStatesForTenant = function (api, tenantID, apiVersion) {
  return new Promise((resolve, reject) => {
    // Stores the Intrusion Prevention states
    const computerIPStates = [];

    // Creates an API key
    const createKey = () => {
      // ApiKey properties
      const key = new api.ApiKey();
      key.keyName = "Temporary Key";
      key.roleID = 1;
      key.locale = api.ApiKey.LocaleEnum["en-US"];
      key.timeZone = "Asia/Tokyo";

      const tenantsApi = new api.TenantsApi();
      return tenantsApi.generateTenantApiSecretKey(tenantID, key, apiVersion);
    };

    // Gets a list of tenant computers
    const getComputers = apiClient => {
      const computersApi = new api.ComputersApi(apiClient);
      return computersApi.listComputers(apiVersion, { overrides: "false" });
    };

    // Deletes an ApiKey from a tenant
    const deleteKey = (apiClient, keyID) => {
      const apiKeysApi = new api.APIKeysApi();
      apiKeysApi.deleteApiKey(keyID, apiVersion).catch(error => {
        console.log(error);
      });
    };

    // Configure the ApiClient for connecting to the tenant
    const tenantClient = api.ApiClient.instance;
    const defaultAuthentication = tenantClient.authentications["DefaultAuthentication"];
    let tenantKey;

    createKey()
      .then(newKey => {
        tenantKey = newKey;
        defaultAuthentication.apiKey = newKey.secretKey;
        return getComputers(tenantClient);
      })
      .then(computers => {
        // Get the state of Intrusion Prevention module for each computer
        for (let i = 0; i < computers.computers.length; i++) {
          computerIPStates[i] = {
            ID: computers.computers[i].ID,
            IpState: computers.computers[i].intrusionPrevention.state
          };
        }
        deleteKey(tenantClient, tenantKey.ID);
        resolve(computerIPStates);
      })
      .catch(error => {
        reject(error);
      });
  });
};
Java
/*
 * Retrieves the state of the intrusion prevention module for a tenant's
 * computers
 * @param tenantID The ID of the tenant.
 * @return A HashMap that uses the computer ID as the key and the intrusion
 * prevention state as the value.
 */
public static HashMap<Integer, IntrusionPreventionComputerExtension.StateEnum> getIPStatesForTenant(Integer tenantID) {

    HashMap<Integer, IntrusionPreventionComputerExtension.StateEnum> computerIPStates = new HashMap<Integer, IntrusionPreventionComputerExtension.StateEnum>();
    // Create the key object
    ApiKey key = new ApiKey();
    key.setKeyName("Temporary Key");
    key.setRoleID(1);
    key.setLocale(ApiKey.LocaleEnum.EN_US);
    key.setTimeZone("Asia/Tokyo");
    // Add the key to Deep Security Manager
    TenantsApi tenantsApi = new TenantsApi();
    try {
        key = tenantsApi.generateTenantApiSecretKey(tenantID, key, "v1");

        // Configure the APIClient using the new key's secret
        ApiClient tenantClient = Configuration.getDefaultApiClient();
        ApiKeyAuth DefaultAuthentication = (ApiKeyAuth) tenantClient.getAuthentication("DefaultAuthentication");
        DefaultAuthentication.setApiKey(key.getSecretKey());

        // Get the computers and find the states
        ComputersApi tnComputerApi = new ComputersApi(tenantClient);
        Computers computers;

        computers = tnComputerApi.listComputers(false, "v1");
        for (Computer computer : computers.getComputers()) {
            computerIPStates.put(computer.getID(), computer.getIntrusionPrevention().getState());
        }
        // Delete the tenant key
        ApiKeysApi tnApiKeysApi = new ApiKeysApi(tenantClient);
        tnApiKeysApi.deleteApiKey(key.getID(), "v1");
    } catch (ApiException e) {
        e.printStackTrace();
    }
    return computerIPStates;
}

Example: configure policies for tenants

Create and configure policies for tenants in the same way that you do for the primary Deep Security Manager, except that you use a tenant API key for authentication. The following example creates an API key for a tenant and then uses the key to configure an ApiClient object. The client interacts with the tenant’s Deep Security Manager.

For more information about using the API to work with policies, see Create and Configure Policies.

Python
def add_policy_to_tenant(client, configuration, api_version, api_exception, policy, tenant_id):
    """ Adds a policy to a tenant.

    :param client: The Deep Security API modules.
    :param configuration: Configuration object to pass to the client.
    :param api_version: The version of the API to use.
    :param api_exception: The Deep Security API exception module.
    :param policy: The policy to add to the tenant.
    :param tenant_id: The ID of the tenant.
    :return: A PoliciesApi object that contains the new tenant.
    """

    primary_key = configuration.api_key['api-secret-key']

    # Create an API key
    key = client.ApiKey()
    key.key_name = "Temporary key for adding policy to a tenant"
    key.role_id = 1
    key.locale = "en-US"
    key.timeZone = "Asia/Tokyo"

    try:
        # Check that the tenant is in the 'active' state
        import time
        while True:
            state = client.TenantsApi(client.ApiClient(configuration)).describe_tenant(tenant_id, api_version).tenant_state
            if state == 'active':
                break
            time.sleep(5)

        # Generate the secret key for the tenant
        tenants_api = client.TenantsApi(client.ApiClient(configuration))
        generated_key = tenants_api.generate_tenant_api_secret_key(tenant_id, key, api_version)

        # Add the secret key to the configuration
        configuration.api_key['api-secret-key'] = generated_key.secret_key

        # Add the policy
        tenant_policies_api = client.PoliciesApi(client.ApiClient(configuration))
        tenant_client_with_policy = tenant_policies_api.create_policy(policy, api_version, overrides=False)

        # Delete an ApiKey from the tenant
        api_keys_api = client.APIKeysApi(client.ApiClient(configuration))
        api_keys_api.delete_api_key(generated_key.id, api_version)

        # Reset the API key to the primary key
        configuration.api_key['api-secret-key'] = primary_key

        return tenant_client_with_policy

    except api_exception as e:
        return "Exception: " + str(e)
JavaScript
/*
* Adds a policy to a tenant.
* @param {object} api The api module.
* @param {Object} policy The policy to add to the tenant.
* @param {Number} tenantID The ID of the tenant.
* @param {String} apiVersion The api version to use.
* @return {Promise} A promise that contains the new policy.
*/
exports.addPolicyToTenant = function (api, policy, tenantID, apiVersion) {
  return new Promise((resolve, reject) => {
    // Creates an API key
    const createKey = () => {
      // ApiKey properties
      const key = new api.ApiKey();
      key.keyName = "Test Key";
      key.roleID = 1;
      key.locale = api.ApiKey.LocaleEnum["en-US"];
      key.timeZone = "Asia/Tokyo";
      const tenantsApi = new api.TenantsApi();
      return tenantsApi.generateTenantApiSecretKey(tenantID, key, apiVersion);
    };

    // Adds a policy to the tenant
    const addPolicy = apiClient => {
      const policiesApi = new api.PoliciesApi(apiClient);
      return policiesApi.createPolicy(policy, apiVersion, { overrides: false });
    };

    // Deletes an ApiKey from a tenant
    const deleteKey = (apiClient, keyID) => {
      const apiKeysApi = new api.APIKeysApi();
      apiKeysApi.deleteApiKey(keyID, apiVersion).catch(error => {
        console.log(error);
      });
    };

    // ApiClient for connecting to the tenant
    const tenantClient = api.ApiClient.instance;
    const DefaultAuthentication = tenantClient.authentications["DefaultAuthentication"];
    let tenantKey;
    createKey()
      .then(newKey => {
        tenantKey = newKey;
        DefaultAuthentication.apiKey = newKey.secretKey;
        return addPolicy(tenantClient);
      })
      .then(newPolicy => {
        deleteKey(tenantClient, tenantKey.ID);
        resolve(newPolicy);
      })
      .catch(error => {
        reject(error);
      });
  });
};
Java
/*
 * Adds a policy to a tenant
 * @param dsmClient An ApiClient object for the primary manager.
 * @param policy The Policy to add to the tenant.
 * @param tenandID The ID of the tenant.
 * @return The created policy.
 */
public static Policy addTenantPolicy(Policy policy, Integer tenantID) {
    // Create an API key for the tenant
    TenantsApi tenantsApi = new TenantsApi();
    ApiKey tenantKey = new ApiKey();
    tenantKey.setKeyName("Tenant Key");
    tenantKey.setRoleID(1);
    try {
        tenantKey = tenantsApi.generateTenantApiSecretKey(tenantID, tenantKey, "v1");

        // Configure an ApiClient object for the tenant
        ApiClient tenantClient = Configuration.getDefaultApiClient();
        ApiKeyAuth DefaultAuthentication = (ApiKeyAuth) tenantClient.getAuthentication("DefaultAuthentication");
        DefaultAuthentication.setApiKey(tenantKey.getSecretKey());

        // Add the policy
        PoliciesApi tnPoliciesApi = new PoliciesApi(tenantClient);
        policy = tnPoliciesApi.createPolicy(policy, false, "v1");

        // Delete the tenant key
        ApiKeysApi tnApiKeysApi = new ApiKeysApi(tenantClient);
        tnApiKeysApi.deleteApiKey(tenantKey.getID(), "v1");

    } catch (ApiException e) {
        e.printStackTrace();
    }
    return policy;
}

Iterate over tenants

Iterate over your Active tenants and their computers when you need to perform an operation on all computers. For example, peform the following steps to create a report that details the protection status of all computers of all tenants:

  1. Search for Active tenants. Create a search filter and then use a TenantsApi object to obtain a list of Tenant objects. You use an API key of the primary Deep Security Manager to authenticate this request.
  2. For each tenant, create (or retrieve from storage) an API key.
  3. For each tenant, retrieve all computers. Use a ComputersApi object, and authenticate using the tenant key.
  4. Perform operations on each computer.

Example: Obtain intrusion prevention rules for all computers of active tenants

The following example iterates over the computers of each active tenant to obtain a list of Intrusion Prevention rules that are applied to each computer.

Python
def get_ip_rules_for_tenant_computers(client, configuration, api_version, api_exception):
    """ Obtains the IDs of the Intrusion Prevention rules that are assigned to each tenant's computers.

    :param client: The Deep Security API modules.
    :param configuration: Configuration object to pass to the client.
    :param api_version: The version of the API to use.
    :param api_exception: The Deep Security API exception module.
    :return: A dictionary of tenants IDs that contains a dictionary of computer IDs with the IP rules they are using.
    """

    tenant_rules = {}
    primary_key = configuration.api_key['api-secret-key']

    try:
        tenants_api = client.TenantsApi(client.ApiClient(configuration))
        tenants_list = tenants_api.list_tenants(api_version)

        for tenant in tenants_list.tenants:
            print("Processing tenant " + str(tenant.id))

            #  Check that the tenant is in the 'active' or 'pending-deletion' state
            import time
            while True:
                state = client.TenantsApi(client.ApiClient(configuration)).describe_tenant(tenant.id, api_version).tenant_state
                if state == 'active' or state == 'pending-deletion':
                    break
                time.sleep(5)

            # Create an API key
            key = client.ApiKey()
            key.key_name = "Temporary Key for getting IP rules from tenant computers"
            key.role_id = 1
            key.locale = "en-US"
            key.time_zone = "Asia/Tokyo"

            # Generate the secret key for the tenant
            tenants_api = client.TenantsApi(client.ApiClient(configuration))
            generated_key = tenants_api.generate_tenant_api_secret_key(tenant.id, key, api_version)

            # Add the secret key to the configuration
            configuration.api_key['api-secret-key'] = generated_key.secret_key

            # Create a ComputersApi object for the tenant
            computers_api = client.ComputersApi(client.ApiClient(configuration))

            # Get a list of computers for the tenant
            computers_list = computers_api.list_computers(api_version)

            # For the tenant, get the IP rules for all computers
            computer_ip_rules = {}
            for computer in computers_list.computers:
                computer_ip_rules[computer.id] = computer.intrusion_prevention.rules

            # Delete the ApiKey from the tenant
            api_keys_api = client.APIKeysApi(client.ApiClient(configuration))
            api_keys_api.delete_api_key(generated_key.id, api_version)
            tenant_rules[tenant.id] = computer_ip_rules

            # Reset the API key to the primary key
            configuration.api_key['api-secret-key'] = primary_key

        return tenant_rules

    except api_exception as e:
        return "Exception: " + str(e)
JavaScript
/*
* Obtains the IDs of the Intrusion Prevention rules that are assigned to each tenant's computers.
* Care must be taken to ensure that ApiClient uses the correct Api Key
* when iterating tenants and calling asynchronous functions.
* @param {object} api The api module.
* @param {String} apiVersion The api version to use.
* @return {Promise} A promise that contains, for each tenant, computer IDs and the rule IDs.
*/
exports.getIpRulesForTenantComputers = function (api, apiVersion, secretKey) {
  return new Promise((resolve, reject) => {
    let tenantRules, tenantKeys;
    const keyPromises = [];
    const rulePromises = [];
    const deleteKeyPromises = [];

    // Search for active tenants
    const tenantsApi = new api.TenantsApi();

    // Search criteria
    const searchCriteria = new api.SearchCriteria();
    searchCriteria.fieldName = "tenantState";
    searchCriteria.choiceTest = api.SearchCriteria.ChoiceTestEnum.equal;
    searchCriteria.choiceValue = "active";

    // Search filter
    const searchFilter = new api.SearchFilter();
    searchFilter.searchCriteria = [searchCriteria];

    // Search options
    const searchOptions = {
      searchFilter: searchFilter,
      overrides: false
    };

    // Perform the search
    tenantsApi.searchTenants(apiVersion, searchOptions)
      .then(tenants => {
        const tenantsList = tenants.tenants;

        // Create an API Key for each tenant
        // Store each promise in an array
        for (let i = 0; i < tenantsList.length; i++) { keyPromises.push(createKey(tenantsList[i].ID, api, apiVersion)); } // Continue when all promises are resolved return Promise.all(keyPromises); }) .then(keyObjects => {
        tenantKeys = keyObjects;
        // For each tenant, get the IP rules for all computers
        // Store each promise in an array
        keyObjects.forEach(keyObject => {
          rulePromises.push(getComputers(keyObject.apiKey, keyObject.tenantID, api, apiVersion));
        });
        //Continue when all promises are resolved
        return Promise.all(rulePromises);
      })
      .then(ruleListObjects => {
        tenantRules = ruleListObjects;
        // Delete each tenant key
        // Store each promise in an array
        tenantKeys.forEach(tenantKey => {
          deleteKeyPromises.push(deleteKey(tenantKey.apiKey, api, apiVersion));
        });
        // Continue when all promises are resolved
        return Promise.all(deleteKeyPromises);
      })
      .then(() => {
        // Configure ApiClient to use the primary tenant's API Key before returning
        const apiClient = api.ApiClient.instance;
        const DefaultAuthentication = apiClient.authentications["DefaultAuthentication"];
        DefaultAuthentication.apiKey = secretKey;

        // Return the rule IDs
        resolve(tenantRules);
      })
      .catch(error => {
        reject(error);
      });
  });
};


// ### PRIVATE FUNCTIONS

// Creates an API key for a tenant
function createKey(tenantID, api, apiVersion) {
  return new Promise((resolve, reject) => {
    // ApiKey properties
    const key = new api.ApiKey();
    key.keyName = "Temporary sKey";
    key.roleID = 1;
    key.locale = api.ApiKey.LocaleEnum["en-US"];
    key.timeZone = "Asia/Tokyo";

    // Create the key
    const tenantsApi = new api.TenantsApi();
    tenantsApi.generateTenantApiSecretKey(tenantID, key, apiVersion)
      .then(key => {
        // Return an object that contains the key and the tenant ID
        resolve({ tenantID: tenantID, apiKey: key });
      })
      .catch(error => {
        reject(error);
      });
  });
}

// Gets a list of tenant computers and then gets the Intrusion Prevention rule IDs for each computer
function getComputers(tenantKey, tenantID, api, apiVersion) {
  return new Promise((resolve, reject) => {
    const computerIPRules = []; //Stores the rule ID's

    // Configure ApiClient
    const tenantClient = api.ApiClient.instance;
    const DefaultAuthentication = tenantClient.authentications["DefaultAuthentication"];
    DefaultAuthentication.apiKey = tenantKey.secretKey;

    // Get the computers from the tenant
    const computersApi = new api.ComputersApi();
    computersApi.listComputers(apiVersion, { overrides: "false" })
      .then(computers => {
        // Get the Intrusion Prevention rules for each computer
        for (let i = 0; i < computers.computers.length; i++) { // Store as objects that contain the computer ID and the rule IDs computerIPRules.push( { ID: computers.computers[i].ID, IpRules: computers.computers[i].intrusionPrevention.ruleIDs }); } // Return an object that contains the tenant ID and the array of computer and rule IDs resolve({ tenantID: tenantID, IPRules: computerIPRules }); }) .catch(error => {
        reject(error);
      });
  });
}

// Deletes an ApiKey from a tenant
function deleteKey(tenantKey, api, apiVersion) {
  // Configure ApiClient;
  const tenantClient = api.ApiClient.instance;
  const DefaultAuthentication = tenantClient.authentications["DefaultAuthentication"];
  DefaultAuthentication.apiKey = tenantKey.secretKey;
  // Delete the key
  const apiKeysApi = new api.APIKeysApi();
  return apiKeysApi.deleteApiKey(tenantKey.ID, apiVersion);
}
Java
/*
 * Retrieves the Intrusion Prevention rules that are applied to all computers of
 * all tenants.
 * @return A HashMap object that uses the tenant ID as the key, and a HashMap of
 * rules that are applied to the computers.
 */

public static HashMap<Integer, HashMap<Integer, ArrayList<Integer>>> getTenantRules() {
    // Key is tenant ID. Value is a list of computer rule IDs
    HashMap<Integer, HashMap<Integer, ArrayList<Integer>>> tenantMap = new HashMap<Integer, HashMap<Integer, ArrayList<Integer>>>();
    // Key is computer ID. Value is a list of rule IDs
    HashMap<Integer, ArrayList<Integer>> computerRules = new HashMap<Integer, ArrayList<Integer>>();

    //Obtain connection properties from local properties file
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("com/trendmicro/deepsecurity/docs/Resources/example.properties");
    Properties properties = new Properties();
    try {
        properties.load(input);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String primarySecretKey = properties.getProperty("secretkey");
    String primaryURL = properties.getProperty("url");

    //Configure the ApiClient
    ApiClient apiClient = Configuration.getDefaultApiClient();
    apiClient.setBasePath(primaryURL);
    ApiKeyAuth DefaultAuthentication = (ApiKeyAuth) apiClient.getAuthentication("DefaultAuthentication");
    DefaultAuthentication.setApiKey(primarySecretKey);

    //Search for Active tenants 
    SearchCriteria searchCriteria = new SearchCriteria();
    searchCriteria.setFieldName("tenantState");
    searchCriteria.setChoiceValue("active");
    searchCriteria.setChoiceTest(SearchCriteria.ChoiceTestEnum.EQUAL);

    //Search filter
    SearchFilter searchFilter = new SearchFilter();
    searchFilter.setMaxItems(1);
    searchFilter.addSearchCriteriaItem(searchCriteria);
    
    TenantsApi tenantsApi = new TenantsApi();
    try {
        Tenants tenants = tenantsApi.searchTenants(searchFilter, "v1");
        
        //Iterate the tenants
        for (Tenant tenant : tenants.getTenants()) {
            System.out.println("Processing tenant " + tenant.getID());

            // For each tenant create an api key
            ApiKey tenantKey = new ApiKey();
            tenantKey.setKeyName("Temporary Key");
            tenantKey.setRoleID(1);
            tenantKey.setLocale(ApiKey.LocaleEnum.EN_US);
            tenantKey.setTimeZone("Asia/Tokyo");
            // Add the key to Deep Security Manager
            tenantKey = tenantsApi.generateTenantApiSecretKey(tenant.getID(), tenantKey, "v1");

            // Configure the ApiClient to use the tenant's secret key
            DefaultAuthentication.setApiKey(tenantKey.getSecretKey());

            // Create a ComputersApi object for the tenant
            ComputersApi tnComputersApi = new ComputersApi();
            // Iterate over the tenant computers
            Computers tenantComputers = tnComputersApi.listComputers(false, "v1");
            for (Computer tenantComputer : tenantComputers.getComputers()) {
                IntrusionPreventionComputerExtension intrusionPeventionComputerExtension = tenantComputer.getIntrusionPrevention();
                ArrayList<Integer> ruleIds = (ArrayList<Integer>) intrusionPeventionComputerExtension.getRuleIDs();
                computerRules.put(tenantComputer.getID(), ruleIds);
            }
            tenantMap.put(tenant.getID(), computerRules);

            // Delete the tenant key
            ApiKeysApi tnApiKeysApi = new ApiKeysApi();
            tnApiKeysApi.deleteApiKey(tenantKey.getID(), "v1");
            tenantKey = null;
            System.out.println("Done tenant " + tenant.getID());

            //Configure the ApiClient to use the primary tenant's Secret Key
            DefaultAuthentication.setApiKey(primarySecretKey);
        }
    } catch (ApiException e) {
        e.printStackTrace();
    }
    return tenantMap;
}