Learning Objectives

VMware Repository on GitHub

  • See how a single Python script can orchestrate inventory, lifecycle, reporting, health checks, and notifications in VMware.
  • Understand the power of modular, well-commented code for real enterprise use.
  • Learn new scripting patterns, error handling, logging, and integration best practices.
  • Visualize the workflow and adapt it to your needs.

My Personal Repository on GitHub

By the end of this article, you will:


Prerequisites

  • Completed Articles 1–10 (you’re comfortable with PowerCLI, Python, and VMware scripting basics).
  • Python 3.x, PowerCLI, pandas, and requests modules installed.
  • Permissions for VM management, PowerShell script execution, and outbound HTTP/S (for notifications).

1. Why Unlock VMware with a Python Mega-Script?

The script is modular—each block can be adapted for your environment.

  • Inventory, health, and configuration reporting
  • Bulk lifecycle operations (power on/off, snapshots, remediation)
  • Data analysis (find out-of-compliance VMs, resource usage)
  • Automated notifications, ticketing, and integrations
  • Logging and audit trails—all in a single workflow

2. How This Script Works

This example does all the following:

  • Collects a live inventory of all VMs
  • Checks for VMs with low free disk space (health check)
  • Takes a snapshot of all powered-on VMs
  • Powers off any VMs tagged as “retired”
  • Generates a CSV report and summary
  • Sends a notification (webhook) if any issues or actions are taken

While individual scripts are powerful, a well-structured Python script can orchestrate many tasks:


3. The Ultimate Python + PowerCLI Mega-Script

Below is the full script with extensive comments and instructions.
Adjust variables at the top (e.g., vCenter credentials, webhook).

import subprocess
import pandas as pd
import requests
import os
import datetime

# ====== CONFIGURATION ======
# PowerShell/PowerCLI script paths
PS_INVENTORY = r"C:Automationget_vm_inventory.ps1"
PS_HEALTH = r"C:Automationcheck_vm_health.ps1"
PS_SNAPSHOT = r"C:Automationcreate_snapshots.ps1"
PS_RETIRE = r"C:Automationpoweroff_retired_vms.ps1"

# Output and log file paths
REPORT_CSV = r"C:Automationautomation_report.csv"
LOGFILE = r"C:Automationautomation_log.txt"

# Webhook for notifications (Slack, Teams, or other)
ALERT_WEBHOOK = "<your_webhook_url>"

# vCenter credentials (for demo only—use secure credential storage in production)
VCENTER = "<vcenter-address>"
VC_USER = "<username>"
VC_PASS = "<password>"

# ========== SCRIPT START ==========

def log_message(msg):
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(LOGFILE, "a") as f:
f.write(f"{now} {msg}n")
print(f"{now} {msg}")

def run_powershell(script_path, args=None):
cmd = [
"powershell.exe",
"-ExecutionPolicy", "Bypass",
"-File", script_path
]
if args:
cmd += args
result = subprocess.run(cmd, capture_output=True, text=True, timeout=180)
log_message(f"Ran {script_path}: returncode={result.returncode}")
if result.stdout:
log_message(f"STDOUT: {result.stdout.strip()}")
if result.stderr:
log_message(f"STDERR: {result.stderr.strip()}")
return result

# 1. Collect VM Inventory
log_message("=== Step 1: Collecting VM Inventory ===")
# Create PowerShell script for inventory on the fly (could also be a separate file)
with open(PS_INVENTORY, "w") as f:
f.write(f"""
Import-Module VMware.PowerCLI
Connect-VIServer -Server {VCENTER} -User {VC_USER} -Password {VC_PASS} -ErrorAction Stop
Get-VM | Select Name, PowerState, Guest.OSFullName, @{{
N="DiskFreeGB";
E={{(Get-VMGuest $_ | Select -ExpandProperty Disks | Measure-Object -Property FreeSpaceGB -Minimum).Minimum}}
}}, @{{
N="Tags";
E={{(Get-TagAssignment $_ | Select -ExpandProperty Tag).Name -join ','}}
}} | Export-Csv -Path "{REPORT_CSV}" -NoTypeInformation
Disconnect-VIServer -Server * -Confirm:$false
""")
run_powershell(PS_INVENTORY)

# 2. Health Check: Find VMs with <10GB free disk
log_message("=== Step 2: Health Check for Low Disk Space ===")
df = pd.read_csv(REPORT_CSV)
low_disk_vms = df[df['DiskFreeGB'] < 10]
if not low_disk_vms.empty:
log_message(f"VMs with low disk space: {len(low_disk_vms)}")
else:
log_message("All VMs have sufficient free disk space.")

# 3. Take Snapshots of All Powered-On VMs
log_message("=== Step 3: Taking Snapshots of Powered-On VMs ===")
with open(PS_SNAPSHOT, "w") as f:
f.write(f"""
Import-Module VMware.PowerCLI
Connect-VIServer -Server {VCENTER} -User {VC_USER} -Password {VC_PASS}
Get-VM | Where-Object {{$_.PowerState -eq "PoweredOn"}} | ForEach-Object {{
New-Snapshot -VM $_ -Name "PythonScriptSnap_$(Get-Date -Format 'yyyyMMdd_HHmmss')" -Description "Automated snapshot from Python mega-script"
}}
Disconnect-VIServer -Server * -Confirm:$false
""")
run_powershell(PS_SNAPSHOT)

# 4. Power Off Retired VMs (tagged as "retired")
log_message("=== Step 4: Powering Off Retired VMs ===")
retired_vms = df[df['Tags'].str.contains('retired', case=False, na=False)]
if not retired_vms.empty:
with open(PS_RETIRE, "w") as f:
f.write(f"""
Import-Module VMware.PowerCLI
Connect-VIServer -Server {VCENTER} -User {VC_USER} -Password {VC_PASS}
{chr(10).join([
f'Stop-VM -VM "{row["Name"]}" -Confirm:$false'
for _, row in retired_vms.iterrows()
])}
Disconnect-VIServer -Server * -Confirm:$false
""")
run_powershell(PS_RETIRE)
log_message(f"Powered off {len(retired_vms)} retired VMs.")
else:
log_message("No retired VMs found to power off.")

# 5. Summary Reporting and Notification
summary = f"""
Automation complete.
Total VMs: {len(df)}
VMs with low disk space: {len(low_disk_vms)}
Retired VMs powered off: {len(retired_vms)}
"""
log_message(summary)

# Send webhook notification if actions or issues were found
if not low_disk_vms.empty or not retired_vms.empty:
try:
requests.post(ALERT_WEBHOOK, json={"text": summary})
log_message("Notification sent via webhook.")
except Exception as e:
log_message(f"Failed to send notification: {str(e)}")

log_message("=== VMware automation mega-script finished ===")


4. Diagram: Mega-Script Orchestration


5. Key Techniques and What You Unlock

  • Multi-task automation: Orchestrate inventory, actions, and health checks from one script.
  • Live data analysis: Find problems in real time, act on them, and document the results.
  • Self-documenting logs and CSVs: All steps are logged and auditable.
  • Seamless integration: Hook in chat, ticketing, or monitoring with one requests.post().
  • Modular code: Easily extend for compliance checks, remediation, or bulk reporting.

6. Further Reading


7. Conclusion

Adapt this script for your own environment, schedule it, and extend it as your VMware estate evolves.

Similar Posts