hetznercloud / hcloud-python

A Python library for the Hetzner Cloud API
MIT License
291 stars 43 forks source link

Is there any way to link server_types with locations? #384

Closed DravenJohnson closed 5 months ago

DravenJohnson commented 7 months ago

Bug Report

Current Behavior

We have an API wrapper, which create instance from the client.servers.create(). And it takes:

We were using cx21 to test but then we noticed the API will throw error if cx21 isn unavailable in certain locations, like "Hillsboro US"

Input Code

instance = client.servers.create(
          name="test-server"
          server_type=client.server_types.get_by_name('cx21')
          location=random.choice(client.locations.get_all())
)

Expected behavior/code It works for some location like fsn1 because in this location, cx21 type exist. But for something in US, only cpx21 available.

I read through the doc i didn't see anywhere I can link (or get) the available server_types based on location.

Environment

Not Related

Possible Solution

add another function like client.sever_type.get_by_location()?

Additional context/Screenshots N/A

apricote commented 7 months ago

Hey @DravenJohnson,

the available server types are available through the Datacenter API endpoint (Location <- Datacenter -> Server Types): https://hcloud-python.readthedocs.io/en/stable/api.clients.datacenters.html#hcloud.datacenters.domain.DatacenterServerTypes

https://docs.hetzner.cloud/#datacenters-get-all-datacenters

Some untested pseudo-code:

server_type = client.server_types.get_by_name('cx21')
datacenter = random.choice(
  [
    dc for dc in client.datacenters.get_all() if any(
      available_type.id == server_type.id for available_type in dc.server_types.available
    )
  ]
)
instance = client.servers.create(
          name="test-server"
          server_type=server_type
          datacenter=datacenter
)

By comparing the IDs of the server types, we can avoid additional API requests to get the name of each server type in the check. (available_type.id == server_type.id)

Please note, that it is possible, that a server type is temporarily unavailable in all locations/datacenters.

DravenJohnson commented 6 months ago

Thanks, we noticed that.

So technically, when creating a new server, we just have to pick one of the following right?

I can use datacenter instead of location

Also datacenter include a datacenter.location.country which is the country code we currently using in location.country.

jooola commented 5 months ago

So technically, when creating a new server, we just have to pick one of the following right?

Yes.

Closing as completed, feel free to ask again if you think something is missing.