Как я могу создать виртуальную машину Google Cloud на Python, используя шаблон экземпляра Google Cloud с зарезервированнPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Как я могу создать виртуальную машину Google Cloud на Python, используя шаблон экземпляра Google Cloud с зарезервированн

Сообщение Anonymous »

Мой код может создавать виртуальные машины из шаблона экземпляра. Однако мне нужно использовать зарезервированный региональный IP-адрес.
Я создал региональный IP-адрес с помощью CLI следующим образом:
gcloud compute addresses create test-regional-ip --region europe-north1 --project=sindre-dev

Я перечисляю IP-адреса и вижу IP:
gcloud compute addresses list --project=sindre-dev

Результат.
NAME ADDRESS/RANGE TYPE PURPOSE NETWORK REGION SUBNET STATUS
test-regional-ip 35.228.123.45 EXTERNAL europe-north1 RESERVED

Теперь, когда я пытаюсь установить региональный IP-адрес в своем скрипте с помощью
external_ip = "35.228.123.45" и запустил его, то получаю следующую ошибку:

TypeError: неправильный тип аргумента для встроенной операции
< /blockquote>
Может ли кто-нибудь помочь мне создать виртуальную машину из шаблона экземпляра с региональным IP-адресом с помощью Python?
create_instance_from_template()
from google.cloud import compute_v1

from src.routes.run_fw_engagements.c_instance_template.helpers.wait_for_extended_operation import \
wait_for_extended_operation

def create_instance_from_template(
project_id: str,
zone: str,
instance_name: str,
instance_template_url: str,
external_ip: str = None) -> compute_v1.Instance:
"""
Creates a Compute Engine VM instance from an instance template and optionally assigns an external IP.

Args:
project_id: ID or number of the project you want to use.
zone: Name of the zone you want to check, for example: us-west3-b
instance_name: Name of the new instance.
instance_template_url: URL of the instance template used for creating the new instance.
It can be a full or partial URL.
external_ip: (Optional) External IP address to be assigned to the instance.

Returns:
Instance object.
"""
instance_client = compute_v1.InstancesClient()

# Initialize the instance resource with a name
instance_resource = compute_v1.Instance(name=instance_name)

# Construct the request for instance insertion
instance_insert_request = compute_v1.InsertInstanceRequest(
project=project_id,
zone=zone,
instance_resource=instance_resource, # Assign the instance resource here
)
instance_insert_request.source_instance_template = instance_template_url

# Check if an external IP was provided
if external_ip:
# Define the network interface with the external IP
network_interface = compute_v1.NetworkInterface()

# Create the AccessConfig for the external IP
print(f"Creating AccessConfig with external_ip: {external_ip}")
access_config = compute_v1.AccessConfig(
name="External NAT",
type_=compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT,
# Instead of directly setting nat_ip, we do it through initialization
)

# Assign the nat_ip directly to the access_config after initialization
access_config.nat_ip = external_ip # Ensure this is a string

# Assign the access config to the network interface
network_interface.access_configs = [access_config]

# Set the network interface to the instance resource
instance_resource.network_interfaces = [network_interface]

# Call the API to create the instance
operation = instance_client.insert(instance_insert_request)

# Wait for the operation to complete
wait_for_extended_operation(operation, "instance creation")

# Return the created instance details
return instance_client.get(project=project_id, zone=zone, instance=instance_name)

if __name__ == '__main__':
# Example usage
project_id = "sindre-dev"
zone = "europe-north1-a"
instance_name = "gno-collector-1"
instance_template_url = f"https://www.googleapis.com/compute/v1/p ... e_name}-v1"
external_ip = "35.228.123.45"

create_instance_from_template(
project_id=project_id,
zone=zone,
instance_name=instance_name,
instance_template_url=instance_template_url,
external_ip=external_ip,
)

wait_for_extended_operation()
from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation

def wait_for_extended_operation(
operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
"""
Waits for the extended (long-running) operation to complete.

If the operation is successful, it will return its result.
If the operation ends with an error, an exception will be raised.
If there were any warnings during the execution of the operation
they will be printed to sys.stderr.

Args:
operation: a long-running operation you want to wait on.
verbose_name: (optional) a more verbose name of the operation,
used only during error and warning reporting.
timeout: how long (in seconds) to wait for operation to finish.
If None, wait indefinitely.

Returns:
Whatever the operation.result() returns.

Raises:
This method will raise the exception received from `operation.exception()`
or RuntimeError if there is no exception set, but there is an `error_code`
set for the `operation`.

In case of an operation taking longer than `timeout` seconds to complete,
a `concurrent.futures.TimeoutError` will be raised.
"""
result = operation.result(timeout=timeout)

if operation.error_code:
print(
f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
file=sys.stderr,
flush=True,
)
print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
raise operation.exception() or RuntimeError(operation.error_message)

if operation.warnings:
print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
for warning in operation.warnings:
print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

return result


Подробнее здесь: https://stackoverflow.com/questions/790 ... le-cloud-i
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»