Creating a dynamic group

Objective

To create a dynamic group of entities.

A dynamic group contains a set of entities discovered by filter criteria. In this case, the script will create a group of all virtual machines which reside on a specific host. As virtual machines are added and removed from the host, the membership of this group will reflect those changes.

The script will use the /search endpoint to get the unique ID of the host using its display name, and then retrieve a list of expected virtual machines to verify against. The script then creates the criteria list and inserts that value into the rest of the payload data before creating the group and verifying that the membership is as expected.

Prerequisites

In order to create a dynamic group, you must have the following information:

  • The display name of the host

    The entity type you will use for this group

    The IP address and login credentials for a Turbonomic instance

Related endpoints

This recipe uses information from the following endpoints:

Script setup

To set up the script, provide values from your environment for the following:

  • ip

    The IP of your Turbonomic instance.

  • username

    The username for the account Turbonomic will use to access the API.

  • password

    The password for the account Turbonomic will use to access the API.

  • host_name

    The display name of the host whose virtual machines will be added to the group.

  • group_name

    The display name for the group. This name will appear in the user interface.

Authentication

The first step of any script is to authenticate to your Turbonomic instance, retrieve the authentication token and store it for use with subsequent calls. To authenticate, this script uses the values you set for ip, username, and password. For more detail, see the Authentication Recipe.

API Request: https://{ip}/vmturbo/rest/login

Get expected initial membership

After it logs in, the displays a list of virtual machines that reside on the host. These will be the group members.

The script uses the /search endpoint and retrieves the EntityApiDTO for the host. Using the consumers parameter, you can see each entity that purchases resources from this host. The script lists the consumers with a className that matches the entity type.

Sample Request: GET https://{ip}/api/v3/search?q={host_name}&types=PhysicalMachine'&detail_type=entity'

Create the filter criterion

To create a dynamic group, you pass filter criteria to identify matching entities. You pass these criteria as an array. For this script, you pass a single criterion in the array.

Example criteria_list:


[
  {
    "expType":"RXEQ",
    "expVal":"host_name",
    "filterType":"vmsByPMName",
    "caseSensitive":"false"
  }
]
                
            

Construct the input DTO and create the group

The script will take the criterion parameter and use it to construct the GroupApiDTO, with the following parameters:

  • isStatic

    When true, the created group is static. The script sets this parameter to false.

  • displayName

    The display name for the group. This name will appear in the user interface. The script sets this parameter

  • memberUuidList

    For a dynamic group, pass an empty array.

  • criteriaList

    The filtering criteria used to determine group membership. The script sets this parameter equal to the criteria_list variable.

  • groupType

    The entity type of the group members. The script sets this parameter equal to the group_entity_type variable.

API Request: POST https://{ip}/api/v3/groups/

The response to this request will be the GroupApiDTO for the created group.

Sample Response:


{
  "uuid":"285126581114848",
  "displayName":"TestGrp2",
  "className":"Group",
  "membersCount":3,
  "entitiesCount":3,
  "groupType":"VirtualMachine",
  "severity":"CRITICAL",
  "environmentType":"ONPREM",
  "isStatic":false,
  "logicalOperator":"AND",
  "criteriaList":[
    {
      "expVal":"hp-esx119.eng.vmturbo.com",
      "expType":"RXEQ",
      "filterType":"vmsByPMName",
      "caseSensitive":false,
      "entityType":null,
      "singleLine":false
    }
  ],
  "memberUuidList":[
    "73943582577376",
    "73943582577568",
    "73943582577744"
  ],
  "temporary":false,
  "activeEntitiesCount":2,
  "cloudType":"UNKNOWN",
  "memberTypes":[
    "VirtualMachine"
  ],
  "entityTypes":[
    "VirtualMachine"
  ],
  "groupClassName":"GroupApiDTO"
}
            

Verify the group

To verify that the group was created successfully, the script uses the returned UUID to get the group data via the /groups endpoint. If the request gets the group, the membership of the group should match what was printed to the console in the Get Expected Initial Membership portion of the script, assuming that no virtual machines have been added or removed since that time.

If the group does not exist for the given UUID, the API returns the request status 404, with the message, Group not found: <Passed_UUID>. This indicates that the script failed to create the group.

API Request: https://{ip}/api/v3/groups/{group_uuid}

You might choose to only use a subset of the provided response. For example, this script prints the displayName and UUID for each group member.

Sample Script Response:


Group Members:
                
Display name: DC26-P02-03
OID: 73943582577376
Display name: DC26-P02-02
OID: 73943582577568
Display name: DC26-P02-01
OID: 73943582577744
            

Script example


#
# Commandline args: platformIP, username, pwd, group_name, entity_type, host_name
# EXAMPLE: ./entity_changes.py 10.10.123.456 MyUser MyPwd MyTestGroup VirtualMachine MyHost
#
import json
import requests
import urllib3
import re

import sys
sys.path.append('../login') #This makes login visible...
import login


#
# Make sure you have the correct count of arguments.
#
if len(sys.argv) != 7:
	print("Incorrect arguments list.")
	sys.exit()

#
# Get the args into well named vars, and also authenticate.
#
ip = sys.argv[1]
group_name = sys.argv[4]
entity_type = sys.argv[5]
host_name = sys.argv[6]

token = login.get_cookie(ip, sys.argv[2], sys.argv[3])
authHeader = {'cookie': token}

#
# Get Expected Initial Membership
#
response = requests.get(
    f'https://{ip}/api/v3/search?q={host_name}&types=PhysicalMachine'
    f'&detail_type=entity',
    headers=authHeader, verify=False)
get_vms_response_json = json.loads(response.text)

print(f'CONSUMERS: {get_vms_response_json[0]["consumers"]}')
print(f'The {entity_type} members of this dynamic group will be:')
for entity in get_vms_response_json[0]['consumers']:
	if entity['className'] == entity_type:
		print(entity)

#
# Create the filter criterion
#
criterion = {}
criterion['expType'] = "RXEQ"
criterion['expVal'] = host_name
criterion['filterType'] = "vmsByPMName"
criterion['caseSensitive'] = "false"
	
#
# Construct the Input DTO and Create the Group
#
group_input_dto = {}
group_input_dto['isStatic'] = 'false'
group_input_dto['displayName'] = group_name
group_input_dto['memberUuidList'] = []
group_input_dto['criteriaList'] = [criterion]
group_input_dto['groupType'] = entity_type

response = requests.post(
    f'https://{ip}/api/v3/groups', headers=authHeader, json=group_input_dto, verify=False, stream=True)
group_creation_response_json = json.loads(response.text)
group_uuid = group_creation_response_json['uuid']

#
# Verify the group
#
response = requests.get(
    f'https://{ip}/api/v3/groups/{group_uuid}/entities', headers=authHeader, verify=False)
group_members_response_json = json.loads(response.text)

# Print a list of group members
print('\nGROUP MEMBERS:')
for item in group_members_response_json:
    print('Display name: ' + item['displayName'])
    print('OID: ' + item['uuid'])