class Delete_Old_VMs:
    def __init__(self):
        load_dotenv()
        self.delete_note        = environ.get('DELETE_NOTE')
        self.dont_delete_note   = environ.get('DONT_DELETE_NOTE')
        self.esxi_expire_days   = environ.get('ESXI_EXPIRE_DAYS')
        self.sdk = Sdk()

    def __validate_days_type(self):
        if not self.esxi_expire_days or not self.esxi_expire_days.isdigit():
            print(" Expire days number must be postive integer")
            sys.exit(1)

    def vms_to_delete(self):

        removed_VMs             = []
        self.esxi_expire_days   = int(self.esxi_expire_days)
        vms                     = self.sdk.get_objects_Virtual_Machines()
        now                     = datetime.now(pytz.utc)
        for vm in vms:
            vm_info     = VM(vm)
            summary     = vm_info.summary()
            notes       = summary.config.annotation
            create_date = vm.config.createDate

            if create_date < datetime(2000, 1, 1, tzinfo=pytz.utc):
                continue

            if (self.delete_note and self.delete_note.lower() == notes.lower()) or \
                    (create_date < (now - timedelta(days=self.esxi_expire_days)) and (
                            not self.dont_delete_note or self.dont_delete_note.lower() not in notes.lower())):
                removed_VMs.append(vm_info)

        return removed_VMs

    def remove_vms(self, removed_VMs):
        removed_VMs_names = []
        for vm in removed_VMs:
            vm.task().delete()
            removed_VMs_names.append(vm.info()["Name"])
        return removed_VMs_names

    def run(self):
        self.__validate_days_type()
        removed_VMs         = self.vms_to_delete()
        removed_VMs_names   = self.remove_vms(removed_VMs)
        if removed_VMs_names:
            print("Removed VMs: ")
            print("=============")
            print("\n".join(removed_VMs_names))
        else:
            print("No VM was removed!")
from datetime import timedelta, datetime
from dotenv import load_dotenv
from k8_vmware.vsphere.Sdk import Sdk
from k8_vmware.vsphere.VM import VM
env_path = PurePath(__file__).parent / 'script.env'
load_dotenv(dotenv_path=env_path)
load_dotenv()
rm_note = environ.get('rm_note')
dont_rm_note = environ.get('dont_rm_note')
expire_days_no = environ.get('expire_days_no', '')
if not expire_days_no.isdigit():
    print(" Expire days number must be integer")
    sys.exit(1)
expire_days_no = int(expire_days_no)
sdk = Sdk()
vms_o = sdk.get_objects_Virtual_Machines()
removed_VMs = []
now = datetime.now(pytz.utc)
for vm_o in vms_o:
    vm = VM(vm_o)
    summary = vm.summary()
    info = vm.info()
    state = summary.runtime.powerState
    notes = summary.config.annotation
    create_date = vm_o.config.createDate
    if create_date < datetime(2000, 1, 1):
        continue
    if rm_note.lower() in notes.lower() or (
            create_date < (now - timedelta(days=expire_days_no))
            and dont_rm_note.lower() not in notes.lower()):
        if state == 'poweredOn':
Esempio n. 3
0
class VMUtils:
    """
    Contains method to start or stop VM based on input conditions.
    Required environment variables:
    VSPHERE_HOST=
    VSPHERE_USERNAME=
    VSPHERE_PASSWORD=
    mode_tag=start|shutdown
    start_shut_tag=
    not_shutdown_tag=
    """
    def __init__(self):
        self.mode_tag = environ.get("mode_tag", None)
        self.start_shut_tag = environ.get("start_shut_tag", None)
        self.not_shutdown_tag = environ.get("not_shutdown_tag", None)

        self.sdk = Sdk()

    def _get_vms(self):
        return self.sdk.get_objects_Virtual_Machines()

    def process_vm(self, vm):
        altered = False
        summary = vm.summary()
        notes = summary.config.annotation.lower()
        # print(f"Processing VM : {vm}, Note: {notes}")
        if notes:
            if self.not_shutdown_tag:
                if self.not_shutdown_tag.lower() in notes:
                    return False

            if self.start_shut_tag.lower() in notes:
                if self.mode_tag in ["start", "shutdown"]:
                    altered = vm.info()["Name"]
                    if self.mode_tag == "start":
                        print("starting..", altered)
                        try:
                            vm.power_on()
                        except Exception as ex:
                            print(str(ex))
                    else:
                        print("shutting down..", altered)
                        try:
                            vm.power_off()
                        except Exception as ex:
                            print(str(ex))

        return altered

    def process(self):
        if not self.mode_tag or not self.start_shut_tag:
            print("`mode_tag` or `start_shut_tag` is not defined on env vars")
            return

        if self.mode_tag == "" or self.start_shut_tag == "":
            print("`mode_tag` or `start_shut_tag` should not be blank")
            return

        altered_vms = []
        vms_o = self._get_vms()
        print(f"total vms : {len(vms_o)}")

        for vm_o in vms_o:
            vm = VM(vm_o)
            altered = self.process_vm(vm)
            if altered:
                altered_vms.append(altered)

        if altered_vms:
            print("Altered VMs: ")
            print("=============")
            print("\n".join(altered_vms))
        else:
            print("No VM was Altered !")
Esempio n. 4
0
class Delete_Old_VMs:
    def __init__(self):
        load_dotenv()
        self.delete_note = environ.get("DELETE_NOTE")
        self.dont_delete_note = environ.get("DONT_DELETE_NOTE")
        self.esxi_expire_days = environ.get("ESXI_EXPIRE_DAYS")
        self.sdk = Sdk()

    def validate_days_type(self):
        if not self.esxi_expire_days or not self.esxi_expire_days.isdigit():
            print(" Expire days number must be postive integer")
            return False
        return True

    def validate_notes(self):
        if not self.delete_note:
            print("DELETE_NOTE not provided")
            return False
        return True

    def vms_to_delete(self):

        removed_VMs = []
        self.esxi_expire_days = int(self.esxi_expire_days)
        vms = self.sdk.get_objects_Virtual_Machines()
        now = datetime.now(pytz.utc)
        for vm in vms:
            vm_info = VM(vm)
            summary = vm_info.summary()
            notes = summary.config.annotation.lower()
            create_date = vm.config.createDate

            if create_date < datetime(2000, 1, 1, tzinfo=pytz.utc):
                continue

            if self.dont_delete_note:
                if self.dont_delete_note.lower() in notes:
                    continue

            delete_note_match = self.delete_note.lower() == notes
            date_check = create_date < (now -
                                        timedelta(days=self.esxi_expire_days))
            if delete_note_match or date_check:
                removed_VMs.append(vm_info)

        return removed_VMs

    def remove_vms(self, removed_VMs):
        removed_VMs_names = []
        for vm in removed_VMs:
            vm.task().delete()
            removed_VMs_names.append(vm.name())
        return removed_VMs_names

    def run(self):
        if not self.validate_days_type():
            return
        if not self.validate_notes():
            return

        removed_VMs = self.vms_to_delete()
        removed_VMs_names = self.remove_vms(removed_VMs)
        if removed_VMs_names:
            print("Removed VMs: ")
            print("=============")
            print("\n".join(removed_VMs_names))
        else:
            print("No VM was removed!")