Skip to content

Instantly share code, notes, and snippets.

@acheong08
Created June 28, 2023 15:54
Show Gist options
  • Save acheong08/3f0a062bcd880d36dd854bd26f68f66e to your computer and use it in GitHub Desktop.
Save acheong08/3f0a062bcd880d36dd854bd26f68f66e to your computer and use it in GitHub Desktop.

Based on: https://hitrov.medium.com/resolving-oracle-cloud-out-of-capacity-issue-and-getting-free-vps-with-4-arm-cores-24gb-of-a3d7e6a027a8

apply.py

You can find details like subnet and compartment ID by viewing the request made from browser

import oci
import time

COMPARTMENT_ID = (
    ""
)

SUBNET_ID = ""

RSA_KEY = "<cat .ssh/id_rsa.pub>"

IMAGE_ID = "ocid1.image.oc1.ap-singapore-1.aaaaaaaaidfeccyuickxn6fmuse6yba452cv7gy32yql2n4k3pgpcbfoq4qq"
# Create a default config using DEFAULT profile in default location
# Refer to
# https://docs.oracle.com/en-us/iaas/Content/API/Concepts/sdkconfig.htm#SDK_and_CLI_Configuration_File
# for more info
config = oci.config.from_file(file_location="./config")

# Create a service client
compute = oci.core.ComputeClient(config)
counter = 0
# Create instance in a loop until successful
while True:
    counter += 1
    availability_domain = "pdFk:AP-SINGAPORE-1-AD-1"
    print("try number", counter)
    try:
        # Create instance
        response = compute.launch_instance(
            launch_instance_details=oci.core.models.LaunchInstanceDetails(
                availability_domain=availability_domain,
                compartment_id=COMPARTMENT_ID,
                shape="VM.Standard.A1.Flex",
                subnet_id=SUBNET_ID,
                metadata={"ssh_authorized_keys": RSA_KEY},
                create_vnic_details=oci.core.models.CreateVnicDetails(
                    assign_public_ip=True,
                    assign_private_dns_record=True,
                    subnet_id=SUBNET_ID,
                ),
                shape_config=oci.core.models.LaunchInstanceShapeConfigDetails(
                    ocpus=4, memory_in_gbs=24
                ),
                source_details=oci.core.models.InstanceSourceViaImageDetails(
                    source_type="image",
                    image_id=IMAGE_ID,
                ),
                display_name="DutiV6",
            )
        )
        instance_id = response.data.id

        # Verify instance is available
        while True:
            instance = compute.get_instance(instance_id).data
            if instance.lifecycle_state == "RUNNING":
                print(f"Instance {instance_id} is running!")
                break

            print(instance)
            time.sleep(10)  # wait before checking again

        break  # exit the while loop when the instance is successfully created and running
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        time.sleep(10)  # wait before trying again
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment