Skip to content

vmware esxi monitoring

wouyang edited this page Nov 23, 2020 · 1 revision

Healthbot iAgent module can be used with User Defined Function(UDF) to get information from VMware vCenter.

1. Create device profile and device group for vCenter

vendor type: vcenter or esxi
vcenterProfile Save and Deploy addDeviceGroup Save and Deploy

2. Create a rule to get information from vCenter

2.1 Upload Files

From Healthbot Rule creation GUI, you can upload UDF required files vcenter.yml and vcenter.py and commit and deploy.

2.2 Add Sensor

createRule1 sensor name: vcenter
sensor type: iagent
File: vcenter.yml
Table: vCenterTable
Frequency: 60s

2.3 Add Fields

add the name, ip and mac in the fields createRuleFields1

createRuleFields2

createRuleFields3

2.4 Use Trigger to print out information

e.g.
name $name mac address $mac ip address $ip createRuleTrigger

Save and Deploy

3. Create a playbook

createPlaybook Save and Deploy createPlaybookInstance start an instance of playbook

4. Check if the information is correctly displayed

vcenterDisplay

Trouble shooting

if the vcenter task is not showing up in the schedule, execute "salt '*' state.apply" and check again

root@b697bba7ec15:/jfit/salt# salt '*' schedule.list
vcenter_vcenter:
    ----------
    schedule:
        ----------
root@b697bba7ec15:/jfit/salt# salt '*' state.apply
vcenter_vcenter:
----------
          ID: vcenter.yml vCenterTable
    Function: schedule.present
      Result: True
     Comment: Adding new job vcenter.yml vCenterTable to schedule
     Started: 17:15:00.959313
    Duration: 182.557 ms
     Changes:

Summary for vcenter_vcenter
------------
Succeeded: 1
Failed:    0
------------
Total states run:     1
Total run time: 182.557 ms
root@b697bba7ec15:/jfit/salt# salt '*' schedule.list
vcenter_vcenter:
    schedule:
      vcenter.yml vCenterTable:
        args:
        - vCenterTable
        - vcenter.yml
        - /jfit/salt/_tables
        enabled: true
        function: iagent.run
        jid_include: true
        maxrunning: 1
        name: vcenter.yml vCenterTable
        return_config: vcenter:vcenter
        returner: iagent_influxdb
        run_on_start: true
        seconds: 60
        splay: 2
salt '*' test.ping
salt '*' vsphere.list_default_vsan_policy --out=json
cd /jfit/salt/
cd _tables/
vi vsan.yml
cd _modules/
vi vsan.py
salt '*' saltutil.sync_modules
salt '*' vsan.run
cat ../_tables/vsan.yml
salt '*' iagent.run VSANTable vsan.yml /jfit/salt/_tables/
salt '*' state.apply
      vsan.yml VSANTable:
        args:
        - VSANTable
        - vsan.yml
        - /jfit/salt/_tables
        enabled: true
        function: iagent.run
        jid_include: true
        maxrunning: 1
        name: vsan.yml VSANTable
        return_config: test:vcenter
        returner: iagent_influxdb
        run_on_start: true
        seconds: 30
        splay: 2

salt '*' schedule.list

salt '*' saltutil.sync_modules

def print_sls():
  return __pillar__

salt '*' vmmac.print_sls

test_vcenter:
    ----------
    proxy:
        ----------
        encoded_password:
            $9$0P-WBhSKM8xNVvWgJGjPfO1RhSeM87-db
        mechanism:
            userpass
        port:
            443
        proxytype:
            vcenter
        username:
            administrator@tme-vcenter.local
        vcenter:
            10.105.5.200

salt '*' vmmac.run

root@ea114bda5221:/jfit/salt/_tables# cat vmmac.yml
VMMACTable:
    udf: vmmac

UDF

from __future__ import print_function

from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim

import argparse
import atexit
import getpass
import ssl
from junossecure.junos_secure import junos_decode

def GetVMs(content):

    vm_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                      [vim.VirtualMachine],
                                                      True)
    obj = [vm for vm in vm_view.view]
    vm_view.Destroy()
    return obj


def run():
   host = __pillar__["proxy"]["vcenter"]
   user= __pillar__["proxy"]["username"]
   pwd = junos_decode(__pillar__["proxy"]["encoded_password"])
   port = __pillar__["proxy"]["port"]

   context = None
   if hasattr(ssl, '_create_unverified_context'):
      context = ssl._create_unverified_context()
   si = SmartConnect(host=host,
                     user=user,
                     pwd=pwd,
                     port=port,
                     sslContext=context)
   if not si:
       print("Could not connect to the specified host using specified "
             "username and password")
       return -1

   atexit.register(Disconnect, si)

   content = si.RetrieveContent()
   vms = GetVMs(content)
   vm_list = []
   for vm in vms:
       print(" ")
       #print(vm.summary)
       #print("####end of vm######")
       if vm.summary.guest != None:
         ip = vm.summary.guest.ipAddress
         name = vm.summary.config.name
       #print("Name       : ", name)
       #print("IP         : ", ip)
       if vm.config != None:
         #print("########vm config name######")
         #print(vm.config)
         for device in vm.config.hardware.device:
           #if (device.key >= 4000) and (device.key < 5000):
             #print("########device######")
             #print(type(device))
             #print(device)
             if hasattr(device, 'macAddress'):
               mac = device.macAddress
               #print("MAC        : ", mac)
       vm_list.append({'tags': {"name": name}, "fields": {"ip": ip, "mac": mac}})
   return vm_list

def print_sls():
  return __pillar__

UDF using vsphere connect

root@ea114bda5221:/jfit/salt/_modules# cat vmmac.py
from __future__ import print_function

from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim

import argparse
import atexit
import getpass
import ssl
#from junossecure.junos_secure import junos_decode

def GetVMs(content):

    vm_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                      [vim.VirtualMachine],
                                                      True)
    obj = [vm for vm in vm_view.view]
    vm_view.Destroy()
    return obj


def run():
   context = None
   if hasattr(ssl, '_create_unverified_context'):
      context = ssl._create_unverified_context()
   si = __salt__["vsphere.get_service_instance_via_proxy"]()
   if not si:
       print("Could not connect to the specified host using specified "
             "username and password")
       return -1

   content = si.RetrieveContent()
   vms = GetVMs(content)
   vm_list = []
   for vm in vms:
       print(" ")
       #print(vm.summary)
       #print("####end of vm######")
       if vm.summary.guest != None:
         ip = vm.summary.guest.ipAddress
         name = vm.summary.config.name
       #print("Name       : ", name)
       #print("IP         : ", ip)
       if vm.config != None:
         #print("########vm config name######")
         #print(vm.config)
         for device in vm.config.hardware.device:
           #if (device.key >= 4000) and (device.key < 5000):
             #print("########device######")
             #print(type(device))
             #print(device)
             if hasattr(device, 'macAddress'):
               mac = device.macAddress
               #print("MAC        : ", mac)
       vm_list.append({'tags': {"name": name}, "fields": {"ip": ip, "mac": mac}})
   return vm_list

Other

root@8acca7a66f83:/# salt '*' vsphere.list_default_vsan_policy --out=json
{
    "test_vcenter": {
        "name": "vSAN Default Storage Policy",
        "description": "Storage policy used as default for vSAN datastores",
        "resource_type": "STORAGE",
        "subprofiles": [
            {
                "name": "VSAN sub-profile",
                "force_provision": null,
                "capabilities": [
                    {
                        "namespace": "VSAN",
                        "id": "hostFailuresToTolerate",
                        "setting": {
                            "type": "scalar",
                            "value": 1
                        }
                    },
                    {
                        "namespace": "VSAN",
                        "id": "stripeWidth",
                        "setting": {
                            "type": "scalar",
                            "value": 1
                        }
                    },
                    {
                        "namespace": "VSAN",
                        "id": "forceProvisioning",
                        "setting": {
                            "type": "scalar",
                            "value": false
                        }
                    },
                    {
                        "namespace": "VSAN",
                        "id": "proportionalCapacity",
                        "setting": {
                            "type": "scalar",
                            "value": 0
                        }
                    },
                    {
                        "namespace": "VSAN",
                        "id": "cacheReservation",
                        "setting": {
                            "type": "scalar",
                            "value": 0
                        }
                    }
                ]
            }
        ]
    }
}
root@8acca7a66f83:/jfit/salt/_modules# cat vsan.py
def run():
   op =  __salt__["vsphere.list_default_vsan_policy"]()

   req = []

   for item in  op["subprofiles"][0]["capabilities"]:
      req.append({'tags': {"id": item["id"]}, 'fields': {'ns': item["namespace"]}})
   return req