jramacha
jramacha

Reputation: 117

How can I run Pyvmomi scripts based on vSphere alarms on the VCSA

I need to trigger a script through vsphere for specific events, say if an ESXi host crashed. Wanted to do it using pyvmomi, prefer not to poll the vcenter and rather have an alarm trigger a script. http://www.vcritical.com/2009/10/powershell-prevents-datastore-emergencies/

I looked at this as well https://pubs.vmware.com/vsphere-4-esx-vcenter/index.jsp#com.vmware.vsphere.dcadmin.doc_41/vc_client_help/working_with_alarms/c_running_commands_as_alarm_actions.html

But I wanted to know if we can achieve using pyvmomi? Thanks

Upvotes: 1

Views: 3057

Answers (2)

s06er
s06er

Reputation: 1

I just went through a similar exercise with vSphere 7. To capture all possible alarm variables provided by vCenter, use a bash script first. Most variables are not exported as environment vars, so they’re not readily callable from python on the VCSA. I ended up executing a generic bash script via the vSphere alarm definition’s script trigger, then passing all alarm variables from bash by calling a subsequent python script at the end of the bash script. Here’s a list of all the vars you can capture from a bash shell: https://docs.vmware.com/en/VMware-vSphere/6.7/com.vmware.vsphere.monitoring.doc/GUID-5F5932FA-71FA-473E-8776-92B00742D566_copy.html

In python, you can then leverage PyVmomi to connect back to the vCenter ServiceInstance for remediation execution. VCSA’s have PyVmomi modules stored in the VMWARE_PYTHON_PATH variable, so don’t go launching a python shell thinking you’ll be able to import everything you need without providing sys or init with the PyVmomi package path.

As the previous poster mentioned, you should probably run remediation scripts via another compute resource like vRO, a Linux server, or better yet an API call to AWS API Gateway to trigger a lambda or something. Good luck!!

Upvotes: 0

Michael Rice
Michael Rice

Reputation: 8204

First a disclaimer: It is not recommended that you add additional software to the VCSA, especially that which would increase the load on the machine. Doing so is not supported by VMWare to my knowledge and it could introduce stability issues into your VCSA so do so at your own risk and if you are worried check with your VMWare account team before making any changes.

That being said... This is possible to do. Since you would want to do this using the VCSA which runs on a SLES Linux box it will be very simple to do because it already has both Python and pyVmomi on it. This will also work on 6.5 once it comes out even though the underlying OS is changing from SLES to Photon. The process I describe below will work on 5.5, 6.0, and 6.5 in the same way.

  1. Write the script you want to run when the alarm you will be creating triggers, and place it on the VCSA in /root Be sure to set the the execution bit on the script using chmod a+x script.py

  2. Create the alarm in vCenter that matches the condition you are trying to monitor for. An existing Alarm Definition may exist but you will need to create your own because you can not modify the default alarms.

  3. In the Actions pane for the Alarm Definition select "Run a command".

  4. In the configuration box put the full path to the executable script that you want to run. /root/script.py and save the alarm.

Now when your alarm is triggered your script will run. If you have problems or think it is not working you can find a log file on the VCSA that can highlight what might be happening: /var/log/vmware/vpxd/vpxd.log

I have created a very crude example to show you how to get started with your script.

#!/usr/bin/python
#   Copyright 2016 Michael Rice <[email protected]>
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

from __future__ import print_function
import os
import ssl
import sys
import requests

# This is where VMWare keeps the pyVmomi and other libraries
sys.path.extend(os.environ['VMWARE_PYTHON_PATH'].split(';'))

from pyVim import connect
from pyVmomi import vim
requests.packages.urllib3.disable_warnings()
# this is to ignore SSL verification which is helpful for self signed certs
try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context
USER_NAME = "YOUR USER"
PASSWORD = "YOUR PASS"
HOST = "YOUR HOST"
PORT = "443"
service_instance = connect.SmartConnect(host=HOST,
                                        user=USER_NAME,
                                        pwd=PASSWORD,
                                        port=int(PORT))

root_folder = service_instance.content.rootFolder
# again crude example here. use the logging module instead
with open("/var/log/my_script_log_file.txt", 'a') as f:
    print(root_folder.name, file=f)
    for var, val in os.environ.items():
        # When an alarm is triggered and run a lot of environment variables are set. 
        # This will list them all with their values.
        if var.startswith("VMWARE_ALARM"):
            print("{} = {}".format(var, val), file=f)
    print("##########", file=f)
connect.Disconnect(service_instance)

Upvotes: 0

Related Questions