LAB 60 ‐ AI ‐ Extract capacity related decision making parameters for compute family in CSV & also to object storage - DevWithNehaCloud/Oracle-Cloud-Infrastructure-wiki GitHub Wiki
python script
import oci
import csv
# ============================================================
# OCI AUTHENTICATION
# ============================================================
# Uses OCI config file (~/.oci/config)
config = oci.config.from_file()
# OCI clients
identity = oci.identity.IdentityClient(config)
compute = oci.core.ComputeClient(config)
virtual_network = oci.core.VirtualNetworkClient(config)
# Object Storage is NOT required right now because
# we have not created the bucket yet.
#
# Later, when the bucket is created, uncomment:
#
# object_storage = oci.object_storage.ObjectStorageClient(config)
# namespace = object_storage.get_namespace().data
# Get tenancy OCID
tenancy_id = config["tenancy"]
# ============================================================
# OBJECT STORAGE CONFIGURATION - CURRENTLY COMMENTED
# ============================================================
# Uncomment these later after creating the bucket.
#
# bucket_name = "YOUR_BUCKET_NAME"
# object_name = "compute_capacity_inventory.csv"
# ============================================================
# GET ALL COMPARTMENTS
# ============================================================
compartments = [
{
"id": tenancy_id,
"name": "Tenancy Root"
}
]
compartment_response = oci.pagination.list_call_get_all_results(
identity.list_compartments,
tenancy_id,
compartment_id_in_subtree=True,
access_level="ANY"
)
for compartment in compartment_response.data:
if compartment.lifecycle_state == "ACTIVE":
compartments.append({
"id": compartment.id,
"name": compartment.name
})
print(f"Total compartments scanned: {len(compartments)}")
# ============================================================
# COUNTERS
# ============================================================
total_instances = 0
running_instances = 0
stopped_instances = 0
public_instances = 0
private_instances = 0
rows = []
# ============================================================
# SCAN ALL COMPARTMENTS
# ============================================================
for compartment in compartments:
compartment_id = compartment["id"]
compartment_name = compartment["name"]
print(f"Scanning compartment: {compartment_name}")
instances = oci.pagination.list_call_get_all_results(
compute.list_instances,
compartment_id
).data
for instance in instances:
# ----------------------------------------------------
# INSTANCE LIFECYCLE STATE
# ----------------------------------------------------
lifecycle_state = instance.lifecycle_state
# Currently TERMINATED instances are excluded.
#
# If you want TERMINATED instances also in the report
# later, remove/comment the following two lines.
#
if lifecycle_state == "TERMINATED":
continue
# ----------------------------------------------------
# INSTANCE COUNTERS
# ----------------------------------------------------
total_instances += 1
if lifecycle_state == "RUNNING":
running_instances += 1
elif lifecycle_state == "STOPPED":
stopped_instances += 1
# ====================================================
# CAPACITY PARAMETERS
# ====================================================
# Instance Shape
# Example: VM.Standard.E4.Flex
shape = instance.shape
# ----------------------------------------------------
# OCPU AND MEMORY
# ----------------------------------------------------
# These values are mainly applicable to Flex shapes.
ocpus = ""
memory_gb = ""
if instance.shape_config:
if instance.shape_config.ocpus:
ocpus = instance.shape_config.ocpus
if instance.shape_config.memory_in_gbs:
memory_gb = instance.shape_config.memory_in_gbs
# ====================================================
# AVAILABILITY DOMAIN
# ====================================================
availability_domain = instance.availability_domain
# ====================================================
# FAULT DOMAIN
# ====================================================
fault_domain = instance.fault_domain
# ====================================================
# PUBLIC / PRIVATE IP
# ====================================================
public_ip = ""
private_ip = ""
vnic_attachments = oci.pagination.list_call_get_all_results(
compute.list_vnic_attachments,
compartment_id,
instance_id=instance.id
).data
for attachment in vnic_attachments:
vnic = virtual_network.get_vnic(
attachment.vnic_id
).data
private_ip = vnic.private_ip
if vnic.public_ip:
public_ip = vnic.public_ip
break
# ----------------------------------------------------
# CLASSIFY PUBLIC / PRIVATE
# ----------------------------------------------------
if public_ip:
access_type = "Public"
public_instances += 1
else:
access_type = "Private"
private_instances += 1
# ====================================================
# ADD DATA TO CSV
# ====================================================
rows.append([
compartment_name,
instance.display_name,
lifecycle_state,
shape,
ocpus,
memory_gb,
availability_domain,
fault_domain,
access_type,
private_ip,
public_ip
])
# ============================================================
# CREATE CSV FILE
# ============================================================
# ============================================================
# CREATE CSV FILE
# ============================================================
csv_file = "compute_capacity_inventory.csv"
with open(
csv_file,
"w",
newline="",
encoding="utf-8-sig" # Excel-friendly UTF-8 CSV
) as file:
writer = csv.writer(
file,
delimiter=",",
quoting=csv.QUOTE_MINIMAL
)
# CSV HEADERS
writer.writerow([
"Compartment",
"Instance Name",
"Lifecycle State",
"Shape",
"OCPU",
"Memory (GB)",
"Availability Domain",
"Fault Domain",
"Access Type",
"Private IP",
"Public IP"
])
writer.writerows(rows)
print(f"\nCSV generated successfully: {csv_file}")
# ============================================================
# DISPLAY SUMMARY
# ============================================================
print("\n==============================================")
print(" OCI COMPUTE CAPACITY INVENTORY")
print("==============================================")
print(f"Total Instances : {total_instances}")
print(f"Running Instances : {running_instances}")
print(f"Stopped Instances : {stopped_instances}")
print(f"Public Instances : {public_instances}")
print(f"Private Instances : {private_instances}")
print(f"\nCSV generated successfully: {csv_file}")
# ============================================================
# OBJECT STORAGE UPLOAD - CURRENTLY COMMENTED
# ============================================================
# Later, after creating the Object Storage bucket,
# uncomment this entire section.
#
# print("\nUploading CSV to Object Storage...")
#
# try:
#
# with open(csv_file, "rb") as file:
#
# object_storage.put_object(
# namespace_name=namespace,
# bucket_name=bucket_name,
# object_name=object_name,
# put_object_body=file
# )
#
# print("CSV uploaded successfully!")
# print(f"Bucket : {bucket_name}")
# print(f"Object : {object_name}")
#
# except Exception as e:
#
# print("\nObject Storage upload failed.")
# print("Please check:")
# print("1. Bucket name")
# print("2. OCI authentication")
# print("3. IAM permissions")
# print("4. Object Storage namespace")
#
# print(f"\nError: {e}")
# ============================================================
# SCRIPT COMPLETED
# ============================================================
print("\n==============================================")
print(" SCRIPT COMPLETED")
print("==============================================")
Now this is the script that save your csv file to object storage bucket
(first create your object storage bucket in console then pass that bucket name in the script)
import oci
import csv
# ============================================================
# OCI AUTHENTICATION
# ============================================================
# Uses OCI config file (~/.oci/config)
config = oci.config.from_file()
# OCI clients
identity = oci.identity.IdentityClient(config)
compute = oci.core.ComputeClient(config)
virtual_network = oci.core.VirtualNetworkClient(config)
# Object Storage client
object_storage = oci.object_storage.ObjectStorageClient(config)
# Object Storage Namespace
namespace = object_storage.get_namespace().data
# ------------------------------------------------------------
# OBJECT STORAGE CONFIGURATION
# ------------------------------------------------------------
# IMPORTANT:
# Bucket names cannot contain spaces.
# Use the bucket name created in OCI Console.
bucket_name = "compute-capacity-inventory"
# Object name = CSV file name inside Object Storage
object_name = "compute_capacity_inventory.csv"
# ============================================================
# GET TENANCY OCID
# ============================================================
tenancy_id = config["tenancy"]
# ============================================================
# GET ALL COMPARTMENTS
# ============================================================
compartments = [
{
"id": tenancy_id,
"name": "Tenancy Root"
}
]
compartment_response = oci.pagination.list_call_get_all_results(
identity.list_compartments,
tenancy_id,
compartment_id_in_subtree=True,
access_level="ANY"
)
for compartment in compartment_response.data:
if compartment.lifecycle_state == "ACTIVE":
compartments.append({
"id": compartment.id,
"name": compartment.name
})
print(f"Total compartments scanned: {len(compartments)}")
# ============================================================
# COUNTERS
# ============================================================
total_instances = 0
running_instances = 0
stopped_instances = 0
public_instances = 0
private_instances = 0
rows = []
# ============================================================
# SCAN ALL COMPARTMENTS
# ============================================================
for compartment in compartments:
compartment_id = compartment["id"]
compartment_name = compartment["name"]
print(f"Scanning compartment: {compartment_name}")
instances = oci.pagination.list_call_get_all_results(
compute.list_instances,
compartment_id
).data
for instance in instances:
# ----------------------------------------------------
# INSTANCE LIFECYCLE STATE
# ----------------------------------------------------
lifecycle_state = instance.lifecycle_state
# Currently TERMINATED instances are excluded.
#
# If you want TERMINATED instances also in the report
# later, remove/comment the following two lines.
#
if lifecycle_state == "TERMINATED":
continue
# ----------------------------------------------------
# INSTANCE COUNTERS
# ----------------------------------------------------
total_instances += 1
if lifecycle_state == "RUNNING":
running_instances += 1
elif lifecycle_state == "STOPPED":
stopped_instances += 1
# ====================================================
# CAPACITY PARAMETERS
# ====================================================
# Instance Shape
# Example:
# VM.Standard.E4.Flex
# VM.Standard.E5.Flex
shape = instance.shape
# ----------------------------------------------------
# OCPU AND MEMORY
# ----------------------------------------------------
# These values are mainly applicable to Flex shapes.
ocpus = ""
memory_gb = ""
if instance.shape_config:
if instance.shape_config.ocpus:
ocpus = instance.shape_config.ocpus
if instance.shape_config.memory_in_gbs:
memory_gb = instance.shape_config.memory_in_gbs
# ====================================================
# AVAILABILITY DOMAIN
# ====================================================
availability_domain = instance.availability_domain
# ====================================================
# FAULT DOMAIN
# ====================================================
fault_domain = instance.fault_domain
# ====================================================
# PUBLIC / PRIVATE IP
# ====================================================
public_ip = ""
private_ip = ""
vnic_attachments = oci.pagination.list_call_get_all_results(
compute.list_vnic_attachments,
compartment_id,
instance_id=instance.id
).data
for attachment in vnic_attachments:
vnic = virtual_network.get_vnic(
attachment.vnic_id
).data
private_ip = vnic.private_ip
if vnic.public_ip:
public_ip = vnic.public_ip
break
# ----------------------------------------------------
# CLASSIFY PUBLIC / PRIVATE
# ----------------------------------------------------
if public_ip:
access_type = "Public"
public_instances += 1
else:
access_type = "Private"
private_instances += 1
# ====================================================
# ADD DATA TO CSV
# ====================================================
rows.append([
compartment_name,
instance.display_name,
lifecycle_state,
shape,
ocpus,
memory_gb,
availability_domain,
fault_domain,
access_type,
private_ip,
public_ip
])
# ============================================================
# CREATE CSV FILE
# ============================================================
csv_file = "compute_capacity_inventory.csv"
# utf-8-sig makes the CSV more Excel-friendly
with open(
csv_file,
"w",
newline="",
encoding="utf-8-sig"
) as file:
writer = csv.writer(
file,
delimiter=",",
quoting=csv.QUOTE_MINIMAL
)
# --------------------------------------------------------
# CSV HEADERS
# --------------------------------------------------------
writer.writerow([
"Compartment",
"Instance Name",
"Lifecycle State",
"Shape",
"OCPU",
"Memory (GB)",
"Availability Domain",
"Fault Domain",
"Access Type",
"Private IP",
"Public IP"
])
# Write all instance records
writer.writerows(rows)
# ============================================================
# DISPLAY SUMMARY
# ============================================================
print("\n==============================================")
print(" OCI COMPUTE CAPACITY INVENTORY")
print("==============================================")
print(f"Total Instances : {total_instances}")
print(f"Running Instances : {running_instances}")
print(f"Stopped Instances : {stopped_instances}")
print(f"Public Instances : {public_instances}")
print(f"Private Instances : {private_instances}")
print(f"\nCSV generated successfully: {csv_file}")
# ============================================================
# UPLOAD CSV TO OBJECT STORAGE
# ============================================================
print("\n==============================================")
print(" OBJECT STORAGE UPLOAD")
print("==============================================")
try:
# --------------------------------------------------------
# Open CSV file in binary mode
# --------------------------------------------------------
with open(csv_file, "rb") as file:
object_storage.put_object(
namespace_name=namespace,
bucket_name=bucket_name,
object_name=object_name,
put_object_body=file
)
print("\nCSV uploaded successfully to Object Storage!")
print(f"Namespace : {namespace}")
print(f"Bucket : {bucket_name}")
print(f"Object : {object_name}")
except Exception as e:
print("\nObject Storage upload failed.")
print("\nPlease check the following:")
print("1. Bucket name is correct")
print("2. Bucket exists in the correct tenancy")
print("3. OCI authentication is working")
print("4. User/API key has Object Storage permissions")
print("5. Bucket is in the correct tenancy")
print(f"\nError: {e}")
# ============================================================
# SCRIPT COMPLETED
# ============================================================
print("\n==============================================")
print(" SCRIPT COMPLETED")
print("==============================================")
- run that script in the oci code editor
python compute_capacity_inventory.py
- now check the csv file in console (object storage bucket)
you can download your csv file from here
flow:
OCI Compartments ↓ Compute Instances ↓ Capacity Details ↓ compute_capacity_inventory.csv ↓ Object Storage ↓ compute-capacity-inventory bucket