Examples Overview
UCMDB Python REST Library Examples
This directory contains practical scripts demonstrating how to use the ucmdb_rest library to automate common UCMDB tasks.
Setup & Authentication
All examples in this directory use a shared credentials.json file for authentication.
- Copy
credentials.json.exampletocredentials.json. - Update the values with your server details and credentials:
{
"user": "admin",
"password": "your_password",
"server": "ucmdb-server.example.com",
"port": 8443,
"ssl_validation": false
}
Available Examples
Data Management
add_cis.py: Demonstrates how to push new CIs and Relationships into UCMDB.* — View on GitHubdelete_cis.py: Shows how to remove specific CIs from UCMDB using their UCMDB IDs. — View on GitHubsearch_and_expose_ci.py: Uses the powerfulsearch_by_labelfunction to find CIs matching a pattern (e.g. %Server%) and retrieve specific attributes in one request. — View on GitHub
Discovery and Troubleshooting
get_recon_rule.py: Displays the identification rule (reconciliation rule) for a specific CI Type and decodes the Base64ruleXmlfor easy reading. — View on GitHubquery_topology.py: Executes a named TQL or View and retrieves the resulting topology map. — View on GitHub
System Reporting
initialize_get_version.py: A simple 'Hello World' script to test the connection and display UCMDB Server information. — View on GitHubshow_content_packs.py: Displays the version and deployment status of Content Packs. — View on GitHubshow_license_report.py: Displays an audit of the licence consumption breaking down by unit type. — View on GitHub
Utility Scripts
Get Server Version
View Source Code
import logging
import os
import urllib3
from ucmdb_rest import UCMDBAuthError, UCMDBServer
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
"""
Use case: I need to get the version information from UCMDB?
"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("Delete CI example")
def main():
try:
script_dir = os.path.dirname(__file__)
cred_path = os.path.join(script_dir,'credentials.json')
client = UCMDBServer.from_json(cred_path)
logger.info(f"Connected to UCMDB Version: {client.server_version}")
try:
version = client.system.getUCMDBVersion()
version_data = version.json()
print(f'Product: {version_data["productName"]}')
print(f'Server Version: {version_data["fullServerVersion"]}')
print(f'Content Pack: {version_data["contentPackVersion"]}')
print(f'Server Build: {version_data["serverBuildNumber"]}')
print(f'My server version from the client: {client.server_version}')
print(version_data)
except Exception as e:
logger.critical(f"An unexpected error occurred: {e}", exc_info=True)
except UCMDBAuthError as e:
logger.error(f"Authentication failed: {e}")
if __name__ == "__main__":
main()
Show License Summary
View Source Code
import logging
import os
import urllib3
from ucmdb_rest import UCMDBServer
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
"""
Use Case: Display the license report
"""
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger("license_report")
def main():
script_dir = os.path.dirname(__file__)
cred_path = os.path.join(script_dir,'credentials.json')
client = UCMDBServer.from_json(cred_path)
try:
logger.info(f"Generating License Audit for {client.server}...\n")
response = client.system.getLicenseReport()
data = response.json()
used = float(data.get('usedUnit', 0))
total = float(data.get('totalLicenseUnit', 0))
days_left = data.get('remainingDays', 'N/A')
print("=" * 50)
print(f"{'UCMDB LICENSE EXECUTIVE SUMMARY':^50}")
print("=" * 50)
print(f"License Units Used: {used:>10}")
print(f"Total Capacity: {total:>10}")
print(f"Days Until Expiry: {days_left:>10}")
if used > total:
print(f"\n*** WARNING: LICENSE OVER-CONSUMPTION BY {round(used - total, 2)} UNITS ***")
print("=" * 50)
types = ['Server', 'Workstation', 'Network', 'Storage', 'Docker']
print(f"\n{'Unit Type':<20} | {'Full':<10} | {'Basic':<10}")
print("-" * 50)
for t in types:
f_val = data.get(f'full{t}Count', 0)
b_val = data.get(f'basic{t}Count', 0)
print(f"{t:<20} | {f_val:<10} | {b_val:<10}")
if 'licenseDetailsCollection' in data:
print("\n" + "=" * 50)
print(f"{'INSTALLED LICENSE KEYS':^50}")
print("=" * 50)
for lic in data['licenseDetailsCollection']:
print(f"Description: {lic.get('description')}")
print(f"Capacity: {lic.get('capacity')} Units")
print(f"Expires: {lic.get('formatExpirationDate')}")
print("-" * 50)
except Exception as e:
logger.error(f"Failed to generate license report: {e}")
if __name__ == "__main__":
main()