I am trying to use following script to get the disk type but only getting the type persistent but not if its SSD or any other type. any idea how to geet the sctual disk type and not just persistent?
import subprocess
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from datetime import datetime
from io import StringIO
import csv
from googleapiclient import discovery
# Function to send an email with CSV attachment
def sendmail(csv_content):
msg = MIMEMultipart()
my_address = "xxxxxxxxxxxx"
app_generated_password = "xxxxxxxxxxx"
msg['Subject'] = "GCP Instances Report"
msg["From"] = my_address
msg['To'] = "xxxxxxxxxxxx"
msg.attach(MIMEText("Please find the attached GCP Instances Report.", 'html'))
msg.attach(MIMEApplication(csv_content, Name="gcp_instances_report.csv"))
try:
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
smtp.login(my_address, app_generated_password)
print("Sending mail")
smtp.send_message(msg)
print("Mail has been sent")
except smtplib.SMTPAuthenticationError as e:
print(f"Authentication failed. Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
# Function to retrieve GCP instance details using the Google Cloud API
def get_instance_details(project_id):
service = discovery.build('compute', 'v1')
request = service.instances().aggregatedList(project=project_id)
response = request.execute()
instances = []
for zone, zone_instances in response.get('items', {}).items():
if 'instances' in zone_instances:
for instance in zone_instances['instances']:
# Retrieve CPU and memory details from the machineType property
machine_type = instance.get('machineType', '')
cpu, memory = extract_cpu_memory(machine_type)
instance['cpu'] = cpu
instance['memory'] = memory
instances.append(instance)
return instances
# Function to extract CPU and memory information from machineType
def extract_cpu_memory(machine_type):
parts = machine_type.split('-')
if len(parts) >= 2:
cpu_info = parts[1]
memory_info = parts[2] if len(parts) >= 3 else ''
else:
cpu_info = ''
memory_info = ''
return cpu_info, memory_info
# Function to get boot disk image information and disk type
def get_boot_disk_info(instance):
boot_disks = instance.get('disks', [])
image_info_list = []
disk_type_list = []
for boot_disk in boot_disks:
if 'licenses' in boot_disk:
licenses = boot_disk['licenses']
for license_url in licenses:
parts = license_url.split('/')
if parts:
image_info_list.append(parts[-1])
if 'type' in boot_disk:
disk_type = boot_disk['type']
disk_type_list.append(disk_type)
image_info = ', '.join(image_info_list)
disk_type_info = ', '.join(disk_type_list)
return image_info, disk_type_info
# Get the current date and time
date_time = datetime.now().strftime("%Y-%m-%d %H-%M")
# Initialize an array to store results
results = []
# Define CSV column headers
csv_headers = [
"ProjectID", "InstanceName", "Description", "IPAddress", "Subnet",
"VPC", "Zone", "MachineType", "CPUs", "CPUP latform", "Image", "Memory", "DiskType"
]
# Get the list of Google Cloud projects
gcp_projects = subprocess.run("gcloud projects list --format='value(projectId)'", stdout=subprocess.PIPE, text=True, shell=True).stdout.splitlines()
# Loop through each Google Cloud project
for project_id in gcp_projects:
instances = get_instance_details(project_id)
for instance in instances:
instance_name = instance.get('name', '')
description = instance.get('description', '')
network_interfaces = instance.get('networkInterfaces', [])
zone = instance.get('zone', '').split('/')[-1]
machine_type = instance.get('machineType', '').split('/')[-1]
cpu_platform = instance.get('cpuPlatform', '')
memory = instance.get('memoryMb', '') # Retrieve memory information from memoryMb property
# Check if the instance has any boot disks
if 'disks' in instance:
image, disk_type = get_boot_disk_info(instance)
else:
image = ''
disk_type = ''
# Get the first network interface (if available)
if network_interfaces:
network_interface = network_interfaces[0]
ip_address = network_interface.get('networkIP', '')
subnet = network_interface.get('subnetwork', '').split('/')[-1]
vpc = network_interface.get('network', '').split('/')[-1]
else:
ip_address = subnet = vpc = ''
# Retrieve CPU and memory information
cpu, _ = extract_cpu_memory(machine_type) # Memory information is already retrieved
# Extract the number of CPUs from the CPU information
num_cpus = cpu.split('vCPUs')[0].strip() if 'vCPUs' in cpu else ''
instance_dict = {
"ProjectID": project_id,
"InstanceName": instance_name,
"Description": description,
"IPAddress": ip_address,
"Subnet": subnet,
"VPC": vpc,
"Zone": zone,
"MachineType": machine_type,
"CPUs": num_cpus,
"CPUP latform": cpu_platform,
"Image": image,
"Memory": memory,
"DiskType": disk_type # Add the DiskType field
}
results.append(instance_dict)
# Write the total number of instances processed
print(f"Total Instances processed: {len(results)}")
# Create a CSV-formatted string from the results
csv_content = StringIO()
csv_writer = csv.DictWriter(csv_content, fieldnames=csv_headers)
csv_writer.writeheader()
csv_writer.writerows(results)
csv_content = csv_content.getvalue()
# Send the email with the CSV attachment
sendmail(csv_content)
print("Script execution completed.")
```