auto vm create

mail@pastecode.io avatar
unknown
python
4 months ago
2.7 kB
4
Indexable
# -*- coding: utf-8 -*-

import oci
import time

# Konfiguracja OCI
config = oci.config.from_file("~/.oci/config") 
compute_client = oci.core.ComputeClient(config)

# Parametry VM
compartment_id = ""
shape = "VM.Standard.A1.Flex"
image_id = ""
subnet_id = ""
ssh_key = ""

def create_instance_in_ad(ad_name):
    try:
       
        identity_client = oci.identity.IdentityClient(config)
        list_ad_response = identity_client.list_availability_domains(compartment_id)
        availability_domain = next((ad for ad in list_ad_response.data if ad.name.endswith(ad_name)), None)
        
        if not availability_domain:
            print(f"Availability domain {ad_name} nie istnieje")
            return False

        # Get the image OCID for Oracle Linux 8
        image_id = get_oracle_linux_8_image_id(compute_client, compartment_id)

        instance_details = oci.core.models.LaunchInstanceDetails(
            availability_domain=availability_domain.name,
            compartment_id=compartment_id,
            shape="VM.Standard.A1.Flex",
            shape_config=oci.core.models.LaunchInstanceShapeConfigDetails(
                ocpus=3,
                memory_in_gbs=23
            ),
            source_details=oci.core.models.InstanceSourceViaImageDetails(image_id=image_id),
            create_vnic_details=oci.core.models.CreateVnicDetails(subnet_id=subnet_id),
            metadata={"ssh_authorized_keys": ssh_key},
            display_name="ceres"  #nazwa instancji
        )
        response = compute_client.launch_instance(instance_details)
        print("VM 'ceres' stworzona w AD", ad_name, ":", response.data)
        return True
    except oci.exceptions.ServiceError as e:
        print("Blad tworzenia vm w AD", ad_name, ":", e)
        if "Out of capacity" in str(e):
            print("Brak miejsca w AD", ad_name)
            return False
        return False

def get_oracle_linux_8_image_id(compute_client, compartment_id):
    images = compute_client.list_images(
        compartment_id,
        operating_system="Oracle Linux",
        operating_system_version="8"
    ).data
    
    for image in images:
        if "aarch64" in image.display_name.lower() and "8" in image.display_name:
            return image.id
    
    raise Exception("Oracle Linux 8 image for ARM not found")

def main():
    ad_names = ["AD-1", "AD-2", "AD-3"]
    while True:
        for ad_name in ad_names:
            if create_instance_in_ad(ad_name):
                return
        print("Brak zasobów we wszystkich dostępnych domenach. Próba ponownie za 5 minut...")
        time.sleep(300)

if __name__ == "__main__":
    main()
Leave a Comment