ZenDMD Tip - Removing Local Templates

From Zenoss Wiki
This is the approved revision of this page, as well as being the most recent.
Jump to: navigation, search

The following are scripts to remove local templates from components.

Simple Method

This example removes local templates from interface components:

d = find('Bell-9000D')
for i in d.os.interfaces():
    ls = i.lockStatus()
    lock_updates = 'updates' in ls
    lock_deletion = 'deletion' in ls
    send_event = i.sendEventWhenBlocked()
    if lock_updates or lock_deletion or send_event:
        i.unlock()
        commit()
        sync()
        i.removeLocalRRDTemplate()
        commit()
        sync()
        if lock_updates: i.lockFromUpdates()
        if lock_deletion: i.lockFromDeletion()
        i.sendEventWhenBlockedFlag = send_event
        commit()
        sync()
    else:
        i.removeLocalRRDTemplate()
        commit()
        sync()

If you want to remove local device (not component) templates, use:

d = find('Bell-9000D')
if d.isLocal('zDeviceTemplates'):
    d.deleteZenProperty('zDeviceTemplates')


If that doesn't work, or only removes some, use the next method.

Complex Method

This is best saved as a python script (name.py) and passed to zendmd with zendmd --script=name.py

This example removes local templates from interface components:

# THIS BELONGS IN THE HEADER
import json
import urllib
import urllib2
 
ZENOSS_INSTANCE = 'http://localhost:8080'
ZENOSS_USERNAME = 'admin'
ZENOSS_PASSWORD = 'password'
 
ROUTERS = { 'MessagingRouter': 'messaging',
            'EventsRouter': 'evconsole',
            'ProcessRouter': 'process',
            'ServiceRouter': 'service',
            'DeviceRouter': 'device',
            'NetworkRouter': 'network',
            'TemplateRouter': 'template',
            'DetailNavRouter': 'detailnav',
            'ReportRouter': 'report',
            'MibRouter': 'mib',
            'ZenPackRouter': 'zenpack' }
class ZenossAPI():
    def __init__(self, debug=False):
        """
        Initialize the API connection, log in, and store authentication cookie
        """
        # Use the HTTPCookieProcessor as urllib2 does not save cookies by default
        self.urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        if debug: self.urlOpener.add_handler(urllib2.HTTPHandler(debuglevel=1))
        self.reqCount = 1
 
        # Contruct POST params and submit login.
        loginParams = urllib.urlencode(dict(
                        __ac_name = ZENOSS_USERNAME,
                        __ac_password = ZENOSS_PASSWORD,
                        submitted = 'true',
                        came_from = ZENOSS_INSTANCE + '/zport/dmd'))
        self.urlOpener.open(ZENOSS_INSTANCE + '/zport/acl_users/cookieAuthHelper/login',
                            loginParams)
 
    def _router_request(self, router, method, data=[]):
        if router not in ROUTERS:
            raise Exception('Router "' + router + '" not available.')
 
        # Contruct a standard URL request for API calls
        req = urllib2.Request(ZENOSS_INSTANCE + '/zport/dmd/' +
                              ROUTERS[router] + '_router')
 
        # NOTE: Content-type MUST be set to 'application/json' for these requests
        req.add_header('Content-type', 'application/json; charset=utf-8')
 
        # Convert the request parameters into JSON
        reqData = json.dumps([dict(
                    action=router,
                    method=method,
                    data=data,
                    type='rpc',
                    tid=self.reqCount)])
 
        # Increment the request count ('tid'). More important if sending multiple
        # calls in a single request
        self.reqCount += 1
 
        # Submit the request and convert the returned JSON to objects
        return json.loads(self.urlOpener.open(req, reqData).read())
 
z = ZenossAPI()
# END HEADER
 
# LOOP
d = find('device')
url = d.getDeviceUrl()
for i in d.os.interfaces():
    i_name = i.name()
    uid = url + '/os/interfaces/' + i_name
    #query to see if the template is local
    result = z._router_request('TemplateRouter','getObjTemplates',[{'uid': uid}])
    #check if the template exists
    if 'data' in result['result'] and d.id in result['result']['data'][0]['definition']:
        name = result['result']['data'][0]['name']
        #delete the template
        z._router_request('TemplateRouter','removeLocalRRDTemplate',[{'templateName': name, 'uid': uid}])