Iterate Over Tenants

Iterate over your active tenants and their computers when you need to perform an operation on all computers. For example, perform the following steps to create a report that details the protection status of all computers of active 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.

For information about searching, see Search for Resources. For more information about creating API keys for tenants, see Authenticate and Interact with a Tenant.

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
View source
tenants_api = api.TenantsApi(api.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' state
    state = api.TenantsApi(api.ApiClient(configuration)).describe_tenant(tenant.id, api_version).tenant_state
    if state == 'active':
        # Create an API key
        key = api.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 = api.TenantsApi(api.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

        # Include Intrusion Prevention information in the retrieved Computer objects
        expand = api.Expand(api.Expand.intrusion_prevention)

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

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

        # 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.rule_ids

        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
JavaScript
View source
const keyPromises = [];
const rulePromises = [];

// 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 => {
    // 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 => {
    // 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(ruleListObjects);
  })
  .catch(error => {
    reject(error);
  });
Java
View source
// Key is tenant ID. Value is a list of computer rule IDs
Map<Integer, Map<Integer, ArrayList<Integer>>> tenantMap = new HashMap<>();

// Key is computer ID. Value is a list of rule IDs
Map<Integer, ArrayList<Integer>> computerRules = new HashMap<>();

// Obtain connection properties from local properties file
Properties properties = new Properties();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try (InputStream input = classLoader.getResourceAsStream("com/trendmicro/deepsecurity/docs/Resources/example.properties")) {
    properties.load(input);

    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.addSearchCriteriaItem(searchCriteria);

    TenantsApi tenantsApi = new TenantsApi();
    Tenants tenants = tenantsApi.searchTenants(searchFilter, apiVersion);

    // Iterate the tenants
    for (Tenant tenant : tenants.getTenants()) {

        // Create an api key for the tenant
        ApiKey tenantKey = new ApiKey();
        tenantKey.setKeyName("Temporary Key");
        tenantKey.setRoleID(Integer.valueOf(1));
        tenantKey.setLocale(ApiKey.LocaleEnum.EN_US);
        tenantKey.setTimeZone("Asia/Tokyo");

        // Add the key to Deep Security Manager
        tenantKey = tenantsApi.generateTenantApiSecretKey(tenant.getID(), tenantKey, apiVersion);

        // 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();

        // Include Intrusion Prevention information in the returned Computer objects
        Expand expand = new Expand(Expand.OptionsEnum.INTRUSION_PREVENTION);

        // Iterate over the tenant computers
        Computers tenantComputers = tnComputersApi.listComputers(expand.list(), Boolean.FALSE, apiVersion);
        for (Computer tenantComputer : tenantComputers.getComputers()) {
            IntrusionPreventionComputerExtension intrusionPeventionComputerExtension = tenantComputer.getIntrusionPrevention();
            computerRules.put(tenantComputer.getID(), (ArrayList<Integer>)intrusionPeventionComputerExtension.getRuleIDs());
        }
        tenantMap.put(tenant.getID(), computerRules);
        // Configure the ApiClient to use the primary tenant's Secret Key
        defaultAuthentication.setApiKey(primarySecretKey);
    }
    return tenantMap;
}

Also see the Search Tenants and List Computers operations in the API Reference.