Skip to content

Commit e868a2c

Browse files
Asset Service VMware Assets API script
Asset service VMware Assets API py script. Create VMware VM group, get VM group by Id.
1 parent 4efd392 commit e868a2c

2 files changed

Lines changed: 178 additions & 10 deletions

File tree

recipes/python/assets/README.md

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
### NetBackup Assets Service API Code Samples
1+
### NetBackup Asset Service API Code Samples
22

33
This directory contains Python scripts demonstrating the use of NetBackup Asset Service APIs.
44

@@ -10,19 +10,38 @@ The samples are provided only for reference and not meant for production use.
1010

1111
Prerequisites:
1212
- NetBackup 8.3 or higher
13-
- Python 3.5 or higher (the script has been tested with Python 3.8)
14-
- Python modules: `requests`.
15-
13+
- Python 3.5 or higher
14+
- Python modules: `requests`
1615

1716
The following are the commands to run the scripts (should be run from the parent directory of this 'assets' directory).
1817

19-
- get_vmware_assets:
20-
`python -Wignore -m assets.get_vmware_assets -nbserver <server> -username <username> -password <password> -domainName <domainName> -domainType <domainType> [-assetsFilter <filter>]`
18+
- get_vmware_assets (Get VMs or VM Groups):
19+
20+
`python -Wignore -m assets.get_vmware_assets -nbserver <server> -username <username> -password <password> -domainName <domainName> -domainType <domainType> [-assetType <vm|vmGroup>] [-assetsFilter <filter>]`
21+
22+
The script uses the NetBackup Asset Service API to get the VMware workload assets - VMs or VM groups (filtered by the given filter if specified). It prints the following details (delimited by tab): For assetType 'vm' - VM display name, Instance Id, vCenter and the protection plan names that the VM is protected by. For assetType 'vmGroup' - VM group name, VM server, group filter criteria and the protection plan names.
23+
24+
The assetType option can be either vm or vmGroup. Default is 'vm' if not specified.
25+
The assetsFilter option can be used to filter the assets returned. The filter criteria should be in OData format (refer to the NetBackup API documentation for more details). If not specified, the script will get all the assets. Redirect the script output to a file to avoid printing the details on the terminal.
26+
27+
Examples:
28+
- Gets all VMs: `python -Wignore -m assets.get_vmware_assets -nbserver localhost -username user -password password -domainName domain -domainType NT > vm_assets.txt`
29+
30+
- Get the VMs that match the given filter: `python -Wignore -m assets.get_vmware_assets -nbserver localhost -username user -password password -domainName domain -domainType NT -assetsFilter "contains(commonAssetAttributes/displayName, 'backup')" > vm_assets.txt`
2131

22-
The script uses the NetBackup Asset Service API to get the VMware workload assets (filtered by the given filter if specified). It prints the details (delimited by tab) such as asset display name, instance Id, vCenter and the plan names that the asset is protected by.
32+
- Get all VM Groups: `python -Wignore -m assets.get_vmware_assets -nbserver localhost -username user -password password -domainName domain -domainType NT -assetType vmGroup > vm_groups.txt`
2333

24-
Note: _The assetsFilter option can be used to filter the assets returned. It should be in OData format (refer to the NetBackup API documentation). It is optional. If not specified the script will print all the VM assets. Redirect the script output to a file to avoid printing the details on the terminal._
34+
- Get the VM Groups that match the given filter: `python -Wignore -m assets.get_vmware_assets -nbserver localhost -username user -password password -domainName domain -domainType NT -assetType vmGroup -assetsFilter "contains(commonAssetAttributes/displayName, 'backup')"`
35+
2536

26-
Examples: `python -Wignore -m assets.get_vmware_assets -nbserver localhost -username user -password password -domainName domain -domainType NT > vm_assets.txt`
37+
- create_vmware_asset_group (Create VM group and get the VM group by Id):
2738

28-
`python -Wignore -m assets.get_vmware_assets -nbserver localhost -username user -password password -domainName domain -domainType NT -assetsFilter "contains(commonAssetAttributes/displayName, 'backup')" > vm_assets.txt`
39+
`python -Wignore -m assets.create_vmware_asset_group -nbserver <server> -username <username> -password <password> -domainName <domainName> -domainType <domainType> -vmGroupName <name> -vmServer <for example, vCenter> [-vmGroupFilter <filter criteria>]`
40+
41+
The script uses the NetBackup Asset Service API to create VM group and get the VM group details using its asset id. The vmGroupFilter option specifies the filter criteria (in OData format) for the VMs to be included in the group. If it is empty or not specified, all the VMs in the given VM server are included in the group.
42+
If the VM group is created, the script gets the VM group by its asset id and prints the details.
43+
44+
Examples:
45+
- Create VM group with no filter: `python -Wignore -m assets.create_vmware_asset_group -nbserver localhost -username user -password password -domainName domain -domainType NT -vmGroupName vmGroup1 -vmServer vcenter1`
46+
47+
- Create VM group with filter: `python -Wignore -m assets.create_vmware_asset_group -nbserver localhost -username user -password password -domainName domain -domainType NT -vmGroupName vmGroup2 -vmServer vcenter2 -vmGroupFilter "contains(commonAssetAttributes/displayName, 'backup')"`
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
## The script can be run with Python 3.5 or higher version.
2+
## The script requires 'requests' library to make the API calls. The library can be installed using the command: pip install requests.
3+
4+
import argparse
5+
import requests
6+
import time
7+
import login.login_api as login_api
8+
9+
def get_usage():
10+
return ("\nThe command should be run from the parent directory of the 'assets' directory:\n"
11+
"python -Wignore -m assets.create_vmware_asset_group -nbserver <server> -username <username> -password <password> -domainName "
12+
"<domainName> -domainType <domainType> -vmGroupName <name> -vmServer <for example, a vCenter> [-vmGroupFilter <filter criteria>]\n"
13+
"Optional argument: vmGroupFilter - Filter criteria (in OData format) to include VMs in the group. "
14+
"If not specified, all the VMs in the given VM server are included in the group.\n")
15+
16+
parser = argparse.ArgumentParser(usage = get_usage())
17+
parser.add_argument('-nbserver', required=True)
18+
parser.add_argument('-username', required=True)
19+
parser.add_argument('-password', required=True)
20+
parser.add_argument('-domainName', required=True)
21+
parser.add_argument('-domainType', required=True)
22+
parser.add_argument('-vmGroupName', required=True)
23+
parser.add_argument('-vmServer', required=True)
24+
parser.add_argument('-vmGroupFilter', default="")
25+
args = parser.parse_args()
26+
27+
nbserver = args.nbserver
28+
username = args.username
29+
password = args.password
30+
domainName = args.domainName
31+
domainType = args.domainType
32+
vmGroupName = args.vmGroupName
33+
vmServer = args.vmServer
34+
vmGroupFilter = args.vmGroupFilter
35+
36+
base_url = "https://" + nbserver + "/netbackup"
37+
asset_service_url = base_url + "/asset-service/queries/"
38+
content_type = content_type = "application/vnd.netbackup+json;version=4.0"
39+
40+
def create_vm_group():
41+
vm_group_create_response = requests.post(asset_service_url, headers=headers, json=vm_group_create_request, verify=False)
42+
43+
if vm_group_create_response.status_code != 201:
44+
print("\nAPI returned status code {}. Response: {}".format(vm_group_create_response.status_code,
45+
vm_group_create_response.json()))
46+
raise SystemExit("\nScript ended.\n")
47+
48+
print ("\nRequest to create VM group has been posted.")
49+
50+
vm_group_create_query_id = vm_group_create_response.json()['data']['id']
51+
vm_group_create_status_response = None
52+
vm_group_create_status = "IN_PROGRESS"
53+
status_check_count = 0
54+
55+
while vm_group_create_status == "IN_PROGRESS":
56+
time.sleep(2)
57+
print("\nChecking the status of the request...")
58+
vm_group_create_status_query = requests.get(asset_service_url + vm_group_create_query_id, headers=headers, verify=False)
59+
60+
vm_group_create_status_response = vm_group_create_status_query.json()
61+
62+
if vm_group_create_status_query.status_code != 200:
63+
print("\nAPI returned status code: {}. Response: {}".format(vm_group_create_status_response.status_code,
64+
vm_group_create_status_response))
65+
raise SystemExit("\nScript ended.\n")
66+
67+
vm_group_create_status = vm_group_create_status_response['data'][0]['attributes']['status']
68+
69+
print("\nStatus:", vm_group_create_status)
70+
71+
status_check_count += 1
72+
if status_check_count >= 10:
73+
print("\nRequest to create the VM group is still being processed. Exiting status check.")
74+
break
75+
76+
print("\nAPI Response for the VM group create request: ", vm_group_create_status_response)
77+
78+
vm_group_id_uri = ""
79+
if vm_group_create_status == 'SUCCESS':
80+
print("\nVM group created.")
81+
vm_group_id_uri = vm_group_create_status_response['data'][0]['attributes']['workItemResponses'][0]['links']['self']['href']
82+
83+
return vm_group_id_uri
84+
85+
86+
def getAssetById(vm_group_id_uri):
87+
vm_group_get_response = requests.get(base_url + vm_group_id_uri, headers=headers, verify=False)
88+
89+
if vm_group_get_response.status_code != 200:
90+
print("\nAPI returned status code: {}. Response: {}".format(vm_group_get_response.status_code,
91+
vm_group_get_response.json))
92+
raise SystemExit("\nCound not get the VM group by the given ID. Script ended.\n")
93+
94+
print("\nGet VM group API response: ", vm_group_get_response.json())
95+
96+
97+
print("\nExecuting the script...")
98+
99+
jwt = login_api.perform_login(base_url, username, password, domainName, domainType)
100+
101+
vm_group_create_request = {
102+
"data": {
103+
"type": "query",
104+
"attributes": {
105+
"queryName": "create-or-update-assets",
106+
"workloads": [ "vmware" ],
107+
"parameters": {
108+
"objectList": [
109+
{
110+
"correlationId": "1",
111+
"type": "vmwareGroupAsset",
112+
"assetGroup": {
113+
"description": "VM group created from sample script using API",
114+
"assetType": "vmGroup",
115+
"filterConstraint": "",
116+
"oDataQueryFilter": "true",
117+
"commonAssetAttributes": {
118+
"displayName": "",
119+
"workloadType": "vmware",
120+
"detection": {
121+
"detectionMethod": "MANUAL"
122+
}
123+
}
124+
}
125+
}
126+
]
127+
}
128+
}
129+
}
130+
}
131+
132+
asset_group_req = vm_group_create_request['data']['attributes']['parameters']['objectList'][0]['assetGroup']
133+
asset_group_req['commonAssetAttributes']['displayName'] = vmGroupName
134+
asset_group_req['filterConstraint'] = vmServer
135+
if vmGroupFilter:
136+
asset_group_req['oDataQueryFilter'] = vmGroupFilter
137+
138+
139+
headers = {'Content-Type': content_type, 'Authorization': jwt}
140+
141+
print("\nCreating VM group...")
142+
143+
vm_group_id_uri = create_vm_group()
144+
145+
if vm_group_id_uri:
146+
print("\nGetting the VM group by id: ", vm_group_id_uri)
147+
getAssetById(vm_group_id_uri)
148+
149+
print("\nScript completed.\n")

0 commit comments

Comments
 (0)