שמירת כתובת IP חיצונית סטטית

אפשר לשמור כתובות IP חיצוניות סטטיות. אפשר גם להציג ולשחרר את כתובות ה-IP החיצוניות הסטטיות השמורות. כדי להקצות כתובת IP חיצונית סטטית למכונה וירטואלית (VM), אפשר לעיין במאמר בנושא הגדרת כתובות IP חיצוניות סטטיות.

כתובות IP חיצוניות יכולות להיות סטטיות או זמניות. אם מכונה וירטואלית דורשת כתובת IP חיצונית קבועה שלא משתנה, אפשר לקבל כתובת IP חיצונית סטטית. אתם יכולים לשמור כתובות IP חיצוניות חדשות או להפוך כתובות IP חיצוניות ארעיות קיימות לכתובות קבועות.

אם אתם צריכים כתובת IP פנימית סטטית, כדאי לעיין במאמר בנושא שמירת כתובת IP פנימית סטטית.

בדף הזה מוסבר איך לשמור כתובות IP חיצוניות סטטיות ממאגר כתובות ה-IP החיצוניות של Google. מידע על שמירת כתובות IP חיצוניות סטטיות שיובאו באמצעות העברת כתובות IP משלכם (BYOIP) זמין במאמר בנושא העברת כתובות IP משלכם.

לפני שמתחילים

התפקידים הנדרשים

כדי לקבל את ההרשאות שנדרשות לניהול כתובות IP סטטיות ולשריין אותן, צריך לבקש מהאדמין להקצות לכם ב-IAM את התפקיד אדמין רשת של Compute (roles/compute.networkAdmin) בפרויקט. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

זהו תפקיד מוגדר מראש שכולל את ההרשאות שנדרשות להזמנה ולניהול של כתובות IP סטטיות. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

כדי לנהל כתובות IP סטטיות, נדרשות ההרשאות הבאות:

  • compute.addresses.create on the IP address
  • compute.addresses.createInternal on the IP address
  • compute.networks.list ברשת
  • compute.subnetworks.use ברשת המשנה
  • compute.subnetworks.list ברשת המשנה

יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.

מידע על כתובות IP חיצוניות סטטיות

כתובת IP חיצונית סטטית היא משאב ששומר כתובת IP לשימוש של משאבים אחרים בפרויקט. כתובת שמורה נשארת קבועה וזמינה ללקוחות ולשירותים שלכם עד שתחליטו לבטל את השמירה שלה. אפשר גם להפוך כתובת IP חיצונית ארעית לכתובת IP חיצונית סטטית.

מידע נוסף זמין במאמר בנושא כתובות IP.

בטבלה הבאה מפורטות כתובות ה-IP החיצוניות הסטטיות שנתמכות על ידיCloud de Confiance.

סוג כתובת ה-IP משאב טווח כתובות IP מקור משויך עם
כתובות IPv4 חיצוניות אזוריות מכונות וירטואליות ומאזני עומסים אזוריים /32 מאגר כתובות ה-IP החיצוניות של Google או כתובות שיובאו באמצעות BYOIP פרויקט
כתובות IPv6 חיצוניות אזוריות מכונות וירטואליות ומאזני עומסים אזוריים נתמכים /96 טווח כתובות IPv6 חיצוניות של רשת המשנה, שיכול להיות ממאגר כתובות ה-IP החיצוניות של Google או מיובא באמצעות BYOIP תת-רשת
כתובות IPv4 חיצוניות גלובליות מאזני עומסים גלובליים /32 מאגר כתובות ה-IP החיצוניות של Google או כתובות שיובאו באמצעות BYOIP פרויקט
כתובות IPv6 חיצוניות גלובליות מאזני עומסים גלובליים /64 מאגר כתובות ה-IP החיצוניות של Google פרויקט

רשימה של מאזני עומסים אזוריים וגלובליים זמינה במאמר סיכום של סוגי מאזני עומסים.

כתובות IP חיצוניות שמוקצות למכונה וירטואלית נמצאות באותו מארח פיזי כמו המכונה הווירטואלית, ובאותו אזור כמו המכונה הווירטואלית לכל המטרות, כולל ניתוב וחביון. זה נכון ללא קשר למידע על מיקום גיאוגרפי באינטרנט.

מגבלות

  • רק משאב אחד בכל פעם יכול להשתמש בכתובת IP חיצונית סטטית.

  • אין דרך לבדוק אם כתובת IP היא סטטית או זמנית אחרי שהיא הוקצתה למשאב. אפשר להשוות את כתובת ה-IP לרשימה של כתובות IP חיצוניות סטטיות ששמורות לפרויקט הזה. משתמשים בפקודת המשנה gcloud compute addresses list כדי לראות רשימה של כתובות IP חיצוניות סטטיות שזמינות לפרויקט.

  • לכל מכונה וירטואלית יכולים להיות כמה ממשקי רשת, ולכל ממשק יכולות להיות מוקצות כתובות IP מהסוגים הבאים, בהתאם לסוג המערך שלו:

    • ממשקי IPv4 בלבד:
      • כתובת IPv4 פנימית (חובה)
      • כתובת IPv4 חיצונית (אופציונלי)
    • ממשקי מחסנית כפולה (IPv4 ו-IPv6):
      • כתובת IPv4 פנימית (חובה)
      • כתובת IPv4 חיצונית (אופציונלי)
      • /96 טווח כתובות IPv6, פנימי או חיצוני, אבל לא שניהם (חובה)
    • ממשקי IPv6 בלבד:
      • /96 טווח כתובות IPv6, פנימי או חיצוני, אבל לא שניהם (חובה)
  • אי אפשר לבטל את ההקצאה של כתובת IPv6 חיצונית למכונה וירטואלית עם ממשק רשת IPv6 בלבד, או לשנות אותה. עם זאת, אתם יכולים להפוך כתובת IP חיצונית ארעית של משאב לכתובת IP חיצונית סטטית, כך שהכתובת תישאר שמורה גם אחרי שהמשאב יימחק.

  • אי אפשר לשנות את השם של כתובת IP סטטית.

הערה: ממשקי רשת יכולים לקבל תנועה מ כללי העברה מרובים, שעשויים לשרת כתובות IP חיצוניות אחרות. כל מספר של כתובות IP חיצוניות יכול להפנות לממשק רשת באמצעות כללי ההעברה האלה, אבל לכל ממשק רשת אפשר להקצות רק כתובת IPv4 חיצונית אחת וטווח כתובות IPv6 חיצוני אחד /96.

מידע נוסף על איזון עומסים וכללי העברה זמין במאמרי העזרה בנושא איזון עומסים.

שמירת כתובת IP חיצונית סטטית חדשה

אחרי ששומרים את הכתובת, מקצים אותה למכונה וירטואלית חדשה בזמן היצירה שלה או למכונה וירטואלית קיימת.

המסוף

  1. נכנסים לדף IP addresses במסוף Cloud de Confiance .

    מעבר אל כתובות IP

  2. לוחצים על שמירת כתובת IP חיצונית סטטית.
  3. בשדה Name, מזינים שם לכתובת ה-IP.
  4. מציינים אם מסלול שירות הרשת הוא Premium או Standard. שמירת כתובת IPv6 סטטית נתמכת רק במסלול פרימיום.
  5. מציינים אם זו כתובת IPv4 או IPv6.
  6. מציינים אם כתובת ה-IP הזו היא אזורית או גלובלית.
    • אם אתם מזמינים כתובת IP סטטית למאזן עומסים גלובלי, בוחרים באפשרות Global ואז לוחצים על Reserve.
    • אם אתם שומרים כתובת IP סטטית למכונה וירטואלית או למאזן עומסים אזורי, בוחרים באפשרות אזורי ואז בוחרים את האזור שבו רוצים ליצור את הכתובת.
  7. אם אתם שומרים כתובת IPv6 חיצונית אזורית, אתם צריכים לבחור גם את הפרטים הבאים:

    • Network: רשת ה-VPC
    • רשת משנה: רשת המשנה שממנה יוקצו כתובת IPv6 אזורית סטטית
    • טווח IPv6 סטטי: כדי לציין טווח כתובות IPv6 חיצוני סטטי לשמירה, בוחרים באפשרות אני רוצה לבחור, ואז מזינים טווח כתובות IPv6 מותאם אישית /96 מתוך טווח כתובות ה-IPv6 החיצוני של תת-הרשת /64. אחרת, המערכת מקצה לכם באופן אוטומטי טווח כתובות IPv6 חיצוניות סטטיות בתת-הרשת.

      בטווחים של רשתות משנה חיצוניות של IPv6 שסופקו על ידי Google, כתובות ה-IP של מכונות וירטואליות צריכות להיות מהחצי הראשון (/65) של טווח כתובות ה-IPv6 החיצוניות של רשת המשנה /64, וכתובות ה-IP של איזון עומסים צריכות להיות מהחצי השני (/65). מידע נוסף זמין במאמר בנושא מפרטים של IPv6 חיצוני.

    • סוג נקודת הקצה: בוחרים באפשרות VM instance (מכונת VM) או באפשרות External passthrough Network Load Balancer (מאזן עומסי רשת חיצוני להעברת סיגנל ללא שינוי).

  8. אופציונלי: אם אתם שומרים את כתובת ה-IP החיצונית הסטטית למכונה וירטואלית, ברשימה Attached to בוחרים מכונה וירטואלית לצירוף כתובת ה-IP.

  9. לוחצים על שמירה כדי לשמור את כתובת ה-IP.

gcloud

כדי לשמור כתובת IP חיצונית סטטית, משתמשים בפקודה gcloud compute addresses create.

כדי לשמור כתובת IPv4 או IPv6 חיצונית סטטית, פועלים לפי ההוראות הבאות:

  • כדי לשמור כתובת IP חיצונית גלובלית:

    gcloud compute addresses create ADDRESS_NAME \
      --global \
      --ip-version=IP_VERSION
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ADDRESS_NAME: השם שרוצים לשייך לכתובת הזו.
    • IP_VERSION: גרסת ה-IP, ‏ IPv4 או IPv6.
  • כדי לשמור כתובת IPv4 חיצונית אזורית:

    gcloud compute addresses create ADDRESS_NAME \
       --region=REGION
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ADDRESS_NAME: השם שרוצים לשייך לכתובת הזו.
    • REGION: אזור של כתובת ה-IP.
  • כדי לשמור כתובת IPv6 חיצונית אזורית:

    gcloud compute addresses create ADDRESS_NAME \
       --region=REGION \
       --subnet=SUBNET_NAME \
       --ip-version=IPV6 \
       --endpoint-type=ENDPOINT_TYPE  \
       --addresses=IPV6_ADDRESS
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ADDRESS_NAME: השם שרוצים לשייך לכתובת הזו.
    • REGION: אזור של כתובת ה-IP.
    • SUBNET_NAME: רשת המשנה שממנה תוקצה כתובת ה-IPv6 האזורית הסטטית. לתת-הרשת צריך להיות טווח כתובות IPv6 חיצוניות שהוקצה.
    • ENDPOINT_TYPE: לכתובות IPv6 חיצוניות אזוריות, מציינים את סוג נקודת הקצה, VM או NETLB.
    • IPV6_ADDRESS: כתובת ה-IPv6 שרוצים לשריין, שחייבת להיות /96 טווח כתובות IPv6 מרשת המשנה. אם לא מציינים כתובת IPv6, המערכת מקצה כתובת IPv6 באופן אוטומטי.

      בטווחים של רשתות משנה חיצוניות של IPv6 שסופקו על ידי Google, כתובות ה-IP של מכונות וירטואליות צריכות להיות מהחצי הראשון (/65) של טווח כתובות ה-IPv6 החיצוניות של רשת המשנה /64, וכתובות ה-IP של איזון עומסים צריכות להיות מהחצי השני (/65). מידע נוסף זמין במאמר בנושא מפרטים של IPv6 חיצוני.

כדי לראות את התוצאה, משתמשים בפקודה gcloud compute addresses describe:

gcloud compute addresses describe ADDRESS_NAME

Terraform

אתם יכולים להשתמש במשאב google_compute_address כדי ליצור כתובת IP חיצונית אזורית.

resource "google_compute_address" "default" {
  name   = "my-test-static-ip-address"
  region = "us-central1"
}

בדוגמה הבאה מוצג איך להשתמש במשאב google_compute_global_address כדי ליצור כתובת IPv6 חיצונית גלובלית:

resource "google_compute_global_address" "default" {
  project      = var.project_id # Replace this with your service project ID in quotes
  name         = "ipv6-address"
  address_type = "EXTERNAL"
  ip_version   = "IPV6"
}

API

  • כדי ליצור כתובת IPv4 אזורית, קוראים לשיטה האזורית addresses.insert:

    POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/regions/REGION/addresses
    

    גוף הבקשה צריך לכלול את הפרטים הבאים:

    {
      "name": "ADDRESS_NAME"
    }
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט של הבקשה הזו
    • REGION: שם האזור של הבקשה
    • ADDRESS_NAME: השם שרוצים לשייך לכתובת
  • לכתובות IPv4 סטטיות גלובליות, קוראים לשיטה globalAddresses.insert:

    POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/global/addresses
    

    גוף הבקשה צריך לכלול את הפרטים הבאים:

    {
      "name": "ADDRESS_NAME"
    }
    
  • כדי להקצות כתובות IPv6 סטטיות גלובליות, מתקשרים אל השיטה globalAddresses.insert:

    POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/global/addresses
    

    גוף הבקשה צריך לכלול את הפרטים הבאים:

    {
      "name": "ADDRESS_NAME",
      "ipVersion": "IPV6"
    }
    

    כדי לראות את התוצאה, משתמשים בשיטה addresses.get.

  • כדי להקצות כתובות IPv6 סטטיות אזוריות, צריך להפעיל את השיטה addresses.insert:

    POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/regions/REGION/addresses
    

    גוף הבקשה צריך לכלול את הפרטים הבאים:

    {
      "name": "ADDRESS_NAME",
      "ipVersion": "IPV6",
      "ipv6EndpointType": "VM|LB",
      "networkTier": "PREMIUM",
      "subnetwork": "SUBNET"
      "address": "IPV6_ADDRESS"
    }
    

    מחליפים את מה שכתוב בשדות הבאים:

    • SUBNET: רשת המשנה של הפרויקט.
    • IPV6_ADDRESS: כתובת ה-IPv6 שרוצים לשריין, שחייבת להיות /96 טווח כתובות IPv6 מרשת המשנה. אם לא מציינים כתובת IP, המערכת מקצה כתובת IP באופן אוטומטי.

      בטווחים של רשתות משנה חיצוניות של IPv6 שסופקו על ידי Google, כתובות ה-IP של מכונות וירטואליות צריכות להיות מהחצי הראשון (/65) של טווח כתובות ה-IPv6 החיצוניות של רשת המשנה /64, וכתובות ה-IP של איזון עומסים צריכות להיות מהחצי השני (/65). מידע נוסף זמין במאמר בנושא מפרטים של IPv6 חיצוני.

    כדי לראות את התוצאה, משתמשים בשיטה addresses.get.

המשך

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	"cloud.google.com/go/compute/apiv1/computepb"
)

// reserveNewRegionalExternal reserves a new regional external IP address in Google Cloud Platform.
func reserveNewRegionalExternal(w io.Writer, projectID, region, addressName string, isPremium bool) (*computepb.Address, error) {
	// projectID := "your_project_id"
	// region := "europe-central2"
	// addressName := "your_address_name"
	// isPremium := true
	ctx := context.Background()

	networkTier := computepb.AccessConfig_STANDARD.String()
	if isPremium {
		networkTier = computepb.AccessConfig_PREMIUM.String()
	}

	address := &computepb.Address{
		Name:        &addressName,
		NetworkTier: &networkTier,
	}

	client, err := compute.NewAddressesRESTClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewAddressesRESTClient: %w", err)
	}
	defer client.Close()

	req := &computepb.InsertAddressRequest{
		Project:         projectID,
		Region:          region,
		AddressResource: address,
	}

	op, err := client.Insert(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to reserve regional address: %w", err)
	}

	err = op.Wait(ctx)
	if err != nil {
		return nil, fmt.Errorf("waiting for the regional address reservation operation to complete: %w", err)
	}

	addressResult, err := client.Get(ctx, &computepb.GetAddressRequest{
		Project: projectID,
		Region:  region,
		Address: addressName,
	})
	if err != nil {
		return nil, fmt.Errorf("unable to get reserved regional address: %w", err)
	}

	fmt.Fprintf(w, "Regional address %v reserved: %v", addressName, addressResult.GetAddress())

	return addressResult, err
}

// reserveNewGlobalExternal reserves a new global external IP address in Google Cloud Platform.
func reserveNewGlobalExternal(w io.Writer, projectID, addressName string, isV6 bool) (*computepb.Address, error) {
	// projectID := "your_project_id"
	// addressName := "your_address_name"
	// isV6 := false
	ctx := context.Background()
	ipVersion := computepb.Address_IPV4.String()
	if isV6 {
		ipVersion = computepb.Address_IPV6.String()
	}

	address := &computepb.Address{
		Name:      &addressName,
		IpVersion: &ipVersion,
	}

	client, err := compute.NewGlobalAddressesRESTClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewGlobalAddressesRESTClient: %w", err)
	}
	defer client.Close()

	req := &computepb.InsertGlobalAddressRequest{
		Project:         projectID,
		AddressResource: address,
	}

	op, err := client.Insert(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to reserve global address: %w", err)
	}

	err = op.Wait(ctx)
	if err != nil {
		return nil, fmt.Errorf("waiting for the global address reservation operation to complete: %w", err)
	}

	addressResult, err := client.Get(ctx, &computepb.GetGlobalAddressRequest{
		Project: projectID,
		Address: addressName,
	})
	if err != nil {
		return nil, fmt.Errorf("unable to get reserved global address: %w", err)
	}

	fmt.Fprintf(w, "Global address %v reserved: %v", addressName, addressResult.GetAddress())

	return addressResult, nil
}

Java


import com.google.cloud.compute.v1.Address;
import com.google.cloud.compute.v1.Address.AddressType;
import com.google.cloud.compute.v1.Address.IpVersion;
import com.google.cloud.compute.v1.Address.NetworkTier;
import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.GlobalAddressesClient;
import com.google.cloud.compute.v1.InsertAddressRequest;
import com.google.cloud.compute.v1.InsertGlobalAddressRequest;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ReserveNewExternalAddress {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Address name you want to use.
    String addressName = "your-address-name";
    // 'IPV4' or 'IPV6' depending on the IP version. IPV6 if True.
    boolean ipV6 = false;
    // 'STANDARD' or 'PREMIUM' network tier. Standard option available only in regional ip.
    boolean isPremium = false;
    // region (Optional[str]): The region to reserve the IP address in, if regional.
    // Must be None if global.
    String region = null;

    reserveNewExternalIpAddress(projectId, addressName, ipV6, isPremium, region);
  }

  // Reserves a new external IP address in the specified project and region.
  public static List<Address> reserveNewExternalIpAddress(String projectId, String addressName,
                                                          boolean ipV6, boolean isPremium,
                                                          String region)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {

    String ipVersion = ipV6 ? IpVersion.IPV6.name() : IpVersion.IPV4.name();
    String networkTier = !isPremium && region != null
            ? NetworkTier.STANDARD.name() : NetworkTier.PREMIUM.name();

    Address.Builder address = Address.newBuilder()
            .setName(addressName)
            .setAddressType(AddressType.EXTERNAL.name())
            .setNetworkTier(networkTier);

    // Use global client if no region is specified
    if (region == null) {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (GlobalAddressesClient client = GlobalAddressesClient.create()) {
        address.setIpVersion(ipVersion);

        InsertGlobalAddressRequest addressRequest = InsertGlobalAddressRequest.newBuilder()
                .setProject(projectId)
                .setRequestId(UUID.randomUUID().toString())
                .setAddressResource(address.build())
                .build();

        client.insertCallable().futureCall(addressRequest).get(30, TimeUnit.SECONDS);

        return Lists.newArrayList(client.list(projectId).iterateAll());
      }
    } else {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (AddressesClient client = AddressesClient.create()) {
        address.setRegion(region);

        InsertAddressRequest addressRequest = InsertAddressRequest.newBuilder()
                .setProject(projectId)
                .setRequestId(UUID.randomUUID().toString())
                .setAddressResource(address.build())
                .setRegion(region)
                .build();

        client.insertCallable().futureCall(addressRequest).get(30, TimeUnit.SECONDS);

        return Lists.newArrayList(client.list(projectId, region).iterateAll());
      }
    }
  }
}

Python

from typing import Optional

from google.cloud.compute_v1.services.addresses.client import AddressesClient
from google.cloud.compute_v1.services.global_addresses import GlobalAddressesClient
from google.cloud.compute_v1.types import Address


def reserve_new_external_ip_address(
    project_id: str,
    address_name: str,
    is_v6: bool = False,
    is_premium: bool = False,
    region: Optional[str] = None,
):
    """
    Reserves a new external IP address in the specified project and region.

    Args:
    project_id (str): Your Google Cloud project ID.
    address_name (str): The name for the new IP address.
    is_v6 (bool): 'IPV4' or 'IPV6' depending on the IP version. IPV6 if True.
    is_premium (bool): 'STANDARD' or 'PREMIUM' network tier. Standard option available only in regional ip.
    region (Optional[str]): The region to reserve the IP address in, if regional. Must be None if global.

    Returns:
    None
    """

    ip_version = "IPV6" if is_v6 else "IPV4"
    network_tier = "STANDARD" if not is_premium and region else "PREMIUM"

    address = Address(
        name=address_name,
        address_type="EXTERNAL",
        network_tier=network_tier,
    )
    if not region:  # global IP address
        client = GlobalAddressesClient()
        address.ip_version = ip_version
        operation = client.insert(project=project_id, address_resource=address)
    else:  # regional IP address
        address.region = region
        client = AddressesClient()
        operation = client.insert(
            project=project_id, region=region, address_resource=address
        )

    operation.result()

    print(f"External IP address '{address_name}' reserved successfully.")

קידום של כתובת IP חיצונית זמנית

אם למכונה הווירטואלית יש כתובת IP חיצונית ארעית ואתם רוצים להקצות את כתובת ה-IP לפרויקט באופן קבוע, אתם יכולים להפוך את כתובת ה-IP החיצונית הארעית לכתובת IP חיצונית סטטית. קידום של כתובת IP חיצונית זמנית לכתובת שמורה לא גורם להפסקת חבילות שנשלחות למכונה הווירטואלית. Cloud de Confiance כולל מנות שנשלחות למכונה הווירטואלית ישירות או באמצעות איזון עומסים.

המסוף

  1. עוברים לדף כתובות IP.

    מעבר אל כתובות IP

  2. לוחצים על External IP addresses (כתובות IP חיצוניות).
  3. אופציונלי: בשדה מסנן, מחפשים את כתובת ה-IP הזמנית שרוצים לקדם.
  4. בתפריט More actions () של כתובת ה-IP שרוצים להפוך לכתובת IP סטטית, בוחרים באפשרות Promote to static IP address.
  5. מזינים שם לכתובת ה-IP הסטטית החדשה ולוחצים על שמירה.

gcloud

כדי להפוך כתובת IPv4 או IPv6 חיצונית סטטית לכתובת קבועה:

  • כדי להפוך כתובת IPv4 חיצונית ארעית לכתובת IPv4 חיצונית סטטית, צריך לציין את כתובת ה-IP החיצונית הארעית באמצעות הדגל --addresses עם הפקודה compute addresses create. משתמשים בדגל region כדי להפוך כתובת IP אזורית ארעית לכתובת קבועה, או בדגל global כדי להפוך כתובת IP גלובלית ארעית לכתובת קבועה.

    gcloud compute addresses create ADDRESS_NAME --addresses=IP_ADDRESS \
        [--region=REGION | --global]
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ADDRESS_NAME: השם שרוצים לשייך לכתובת הזו.
    • IP_ADDRESS: כתובת ה-IP שרוצים לקדם.
    • REGION: האזור שאליו שייכת כתובת ה-IP האזורית.
  • כדי להפוך כתובת IPv6 חיצונית אזורית ארעית לכתובת IPv6 חיצונית אזורית סטטית, צריך לספק את כתובת ה-IP החיצונית הארעית באמצעות הדגל --addresses עם הפקודה gcloud compute addresses create.

    gcloud compute addresses create ADDRESS_NAME \
      --region=REGION \
      --addresses=IPV6_ADDRESS \
      --prefix-length=96
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ADDRESS_NAME: שם של משאב כתובת ה-IP.
    • REGION: האזור של משאב כתובת ה-IPv6.
    • IPV6_ADDRESS: כתובת ה-IPv6 שאתם מקדמים.

API

כדי לקדם כתובת IP אזורית זמנית, צריך להפעיל את השיטה addresses.insert:

POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/regions/REGION/addresses

כדי לקדם כתובת IP גלובלית זמנית, שולחים בקשת POST ל-URI הבא:

POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/global/addresses

מציינים את הערכים של השדות הנדרשים בגוף הבקשה:

  • עבור כתובות IPv4, גוף הבקשה צריך לכלול את השדות הבאים:

    {
      "name": "ADDRESS_NAME",
      "address": "IPV4_ADDRESS"
      "addressType": "EXTERNAL"
    }
    
  • בכתובות IPv6, גוף הבקשה צריך לכלול את השדות הבאים:

    {
      "name": "ADDRESS_NAME",
      "address": "IPV6_ADDRESS"
      "prefixLength": 96
      "addressType": "EXTERNAL"
    }
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ADDRESS_NAME: השם שרוצים לשייך לכתובת הזו
    • IPV4_ADDRESS|IPV6_ADDRESS: כתובת ה-IPv4 או ה-IPv6 שרוצים לקדם
    • REGION: האזור שאליו שייכת כתובת ה-IPv4 או ה-IPv6
    • PROJECT_ID: מזהה הפרויקט של הבקשה הזו

המשך

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// promoteEphemeralAddress promotes an ephemeral IP address to a reserved static external IP address.
func promoteEphemeralAddress(w io.Writer, projectID, region, ephemeralIP, addressName string) error {
	// projectID := "your_project_id"
	// region := "europe-central2"
	// ephemeral_ip := "214.123.100.121"
	ctx := context.Background()

	client, err := compute.NewAddressesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewAddressesRESTClient: %w", err)
	}
	defer client.Close()

	addressResource := &computepb.Address{
		Name:        proto.String(addressName),
		AddressType: proto.String("EXTERNAL"),
		Address:     proto.String(ephemeralIP),
	}

	req := &computepb.InsertAddressRequest{
		Project:         projectID,
		Region:          region,
		AddressResource: addressResource,
	}

	op, err := client.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to insert address promoted: %v", err)
	}

	// Wait for the operation to complete
	err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("failed to complete promotion operation: %v", err)
	}

	fmt.Fprintf(w, "Ephemeral IP %s address promoted successfully", ephemeralIP)
	return nil
}

Java


import com.google.cloud.compute.v1.Address;
import com.google.cloud.compute.v1.Address.AddressType;
import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.InsertAddressRequest;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class PromoteEphemeralIp {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Region where the VM and IP is located.
    String region = "your-region-id";
    // Ephemeral IP address to promote.
    String ephemeralIp = "your-ephemeralIp";
    // Name of the address to assign.
    String addressName = "your-addressName";

    promoteEphemeralIp(projectId, region, ephemeralIp, addressName);
  }

  // Promote ephemeral IP found on the instance to a static IP.
  public static List<Address> promoteEphemeralIp(String projectId, String region,
                                                 String ephemeralIp, String addressName)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (AddressesClient client = AddressesClient.create()) {
      Address addressResource = Address.newBuilder()
              .setName(addressName)
              .setRegion(region)
              .setAddressType(AddressType.EXTERNAL.name())
              .setAddress(ephemeralIp)
              .build();

      InsertAddressRequest addressRequest = InsertAddressRequest.newBuilder()
              .setRegion(region)
              .setProject(projectId)
              .setAddressResource(addressResource)
              .setRequestId(UUID.randomUUID().toString())
              .build();

      client.insertCallable().futureCall(addressRequest).get(30, TimeUnit.SECONDS);

      return Lists.newArrayList(client.list(projectId, region).iterateAll());
    }
  }
}

Python

import uuid

from google.cloud.compute_v1 import AddressesClient
from google.cloud.compute_v1.types import Address


def promote_ephemeral_ip(project_id: str, ephemeral_ip: str, region: str):
    """
    Promote ephemeral IP found on the instance to a static IP.

    Args:
        project_id (str): Project ID.
        ephemeral_ip (str): Ephemeral IP address to promote.
        region (str): Region where the VM and IP is located.
    """
    addresses_client = AddressesClient()

    # Create a new static IP address using existing ephemeral IP
    address_resource = Address(
        name=f"ip-reserved-{uuid.uuid4()}",  # new name for promoted IP address
        region=region,
        address_type="EXTERNAL",
        address=ephemeral_ip,
    )
    operation = addresses_client.insert(
        project=project_id, region=region, address_resource=address_resource
    )
    operation.result()

    print(f"Ephemeral IP {ephemeral_ip} has been promoted to a static IP.")

כתובת ה-IP החיצונית נשארת מצורפת למכונה הווירטואלית גם אחרי שהיא הועברה לכתובת IP חיצונית סטטית. אם אתם צריכים להקצות את כתובת ה-IP החיצונית הסטטית החדשה למשאב אחר, אתם צריכים לבטל את ההקצאה של כתובת ה-IP החיצונית הסטטית מהמכונה הווירטואלית הקיימת.

הצגת רשימה של כתובות IP חיצוניות סטטיות

כדי להציג רשימה של כתובות IP חיצוניות סטטיות ששמרתם לפרויקט, פועלים לפי השלבים הבאים.

המסוף

  1. נכנסים לדף IP addresses במסוף Cloud de Confiance .

    מעבר אל כתובות IP

  2. לוחצים על External IP addresses (כתובות IP חיצוניות).

gcloud

משתמשים בפקודה gcloud compute addresses list:

  • כדי לראות את כל כתובות ה-IP, משתמשים בפקודה הבאה:

    gcloud compute addresses list
  • כדי לראות רשימה של כל כתובות ה-IP הגלובליות, משתמשים בפקודה הבאה:

    gcloud compute addresses list --global
  • כדי להציג רשימה של כל כתובות ה-IP האזוריות באזור מסוים, משתמשים בפקודה הבאה:

    gcloud compute addresses list \
        --regions=REGION
    

    מחליפים את REGION באזור שרוצים להציג את הכתובות שלו. אפשר לציין כתובות של כמה אזורים באמצעות רשימה של שמות אזורים מופרדים בפסיקים:

    gcloud compute addresses list \
        --regions=REGION1,REGION2,..REGION_n_
    

API

  • כדי להציג רשימה של כתובות IPv4 או IPv6 אזוריות, קוראים לשיטה addresses.list:

    GET https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/regions/REGION/addresses
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט של הבקשה הזו
    • REGION: שם האזור של הבקשה
  • כדי להציג רשימה של כל הכתובות בכל האזורים, קוראים לשיטה addresses.aggregatedList:

    GET https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/aggregated/addresses
    
  • כדי להציג רשימה של כתובות IPv4 או IPv6 גלובליות, קוראים לשיטה globalAddresses.list:

    GET https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/global/addresses
    

    מחליפים את מה שכתוב בשדות הבאים:

    PROJECT_ID: מזהה הפרויקט של הבקשה הזו

המשך

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	"google.golang.org/api/iterator"

	"cloud.google.com/go/compute/apiv1/computepb"
)

// listRegionalExternal retrieves list external IP addresses in Google Cloud Platform region.
func listRegionalExternal(w io.Writer, projectID, region string) ([]*computepb.Address, error) {
	// projectID := "your_project_id"
	// region := "europe-west3"

	ctx := context.Background()
	// Create the service client.
	addressesClient, err := compute.NewAddressesRESTClient(ctx)
	if err != nil {
		return nil, err
	}
	defer addressesClient.Close()

	// Build the request.
	req := &computepb.ListAddressesRequest{
		Project: projectID,
		Region:  region,
	}

	// List the addresses.
	it := addressesClient.List(ctx, req)

	// Iterate over the results.
	var addresses []*computepb.Address
	for {
		address, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, err
		}
		addresses = append(addresses, address)
	}

	// Print the addresses.
	fmt.Fprint(w, "Fetched addresses: \n")
	for _, address := range addresses {
		fmt.Fprintf(w, "%s\n", *address.Name)
	}

	return addresses, nil
}

// listGlobalExternal retrieves list external global IP addresses in Google Cloud Platform.
func listGlobalExternal(w io.Writer, projectID string) ([]*computepb.Address, error) {
	// projectID := "your_project_id"

	ctx := context.Background()
	// Create the service client.
	addressesClient, err := compute.NewGlobalAddressesRESTClient(ctx)
	if err != nil {
		return nil, err
	}
	defer addressesClient.Close()

	// Build the request.
	req := &computepb.ListGlobalAddressesRequest{
		Project: projectID,
	}

	// List the addresses.
	it := addressesClient.List(ctx, req)

	// Iterate over the results.
	var addresses []*computepb.Address
	for {
		address, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, err
		}
		addresses = append(addresses, address)
	}

	// Print the addresses.
	fmt.Fprint(w, "Fetched addresses: \n")
	for _, address := range addresses {
		fmt.Fprintf(w, "%s\n", *address.Name)
	}

	return addresses, nil
}

Java


import com.google.cloud.compute.v1.Address;
import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.GlobalAddressesClient;
import com.google.cloud.compute.v1.ListAddressesRequest;
import com.google.cloud.compute.v1.ListGlobalAddressesRequest;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class ListStaticExternalIp {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Region where the VM and IP is located.
    String region = "your-region-id";

    listStaticExternalIp(projectId, region);
  }

  // Lists all static external IP addresses, either regional or global.
  public static List<Address> listStaticExternalIp(String projectId, String region)
          throws IOException {
    // Use regional client if a region is specified
    if (region != null) {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (AddressesClient client = AddressesClient.create()) {
        ListAddressesRequest request = ListAddressesRequest.newBuilder()
                .setProject(projectId)
                .setRegion(region)
                .build();

        return Lists.newArrayList(client.list(request).iterateAll());
      }
    } else {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (GlobalAddressesClient client = GlobalAddressesClient.create()) {
        ListGlobalAddressesRequest request = ListGlobalAddressesRequest.newBuilder()
                .setProject(projectId)
                .build();

        return Lists.newArrayList(client.list(request).iterateAll());
      }
    }
  }
}

Python

from typing import List, Optional

from google.cloud.compute_v1.services.addresses.client import AddressesClient
from google.cloud.compute_v1.services.global_addresses import GlobalAddressesClient
from google.cloud.compute_v1.types import Address


def list_static_ip_addresses(
    project_id: str, region: Optional[str] = None
) -> List[Address]:
    """
    Lists all static external IP addresses, either regional or global.

    Args:
    project_id (str): project ID.
    region (Optional[str]): The region of the IP addresses if regional. None if global.

    Returns:
    List[Address]: A list of Address objects containing details about the requested IPs.
    """
    if region:
        # Use regional client if a region is specified
        client = AddressesClient()
        addresses_iterator = client.list(project=project_id, region=region)
    else:
        # Use global client if no region is specified
        client = GlobalAddressesClient()
        addresses_iterator = client.list(project=project_id)

    return list(addresses_iterator)  # Convert the iterator to a list to return

תיאור של כתובת IP חיצונית סטטית

כדי לקבל מידע על כתובת IP חיצונית סטטית, פועלים לפי השלבים הבאים.

המסוף

  1. נכנסים לדף IP addresses במסוף Cloud de Confiance .

    מעבר אל כתובות IP

  2. לוחצים על External IP addresses (כתובות IP חיצוניות).

  3. לוחצים על כתובת ה-IP שרוצים לקבל עליה מידע נוסף.

gcloud

משתמשים בפקודה gcloud compute addresses describe. מחליפים את ADDRESS_NAME בשם של כתובת ה-IP החיצונית שרוצים לתאר.

  • כדי להקצות כתובת IPv4 או IPv6 גלובלית, משתמשים בפקודה הבאה:

    gcloud compute addresses describe ADDRESS_NAME --global
  • כדי להקצות כתובת IPv4 או IPv6 אזורית, משתמשים בפקודה הבאה:

    gcloud compute addresses describe ADDRESS_NAME --region=REGION

API

  • כדי לתאר כתובת IPv4 או IPv6 אזורית, קוראים לשיטה addresses.get:

    GET https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/regions/REGION/addresses/ADDRESS_NAME
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט של הבקשה
    • REGION: שם האזור של הבקשה
    • ADDRESS_NAME: השם של כתובת ה-IP
  • כדי לתאר כתובת IPv4 או IPv6 גלובלית, קוראים לשיטה globalAddresses.get:

    GET https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/global/addresses/ADDRESS_NAME
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט של הבקשה
    • ADDRESS_NAME: השם של כתובת ה-IP

המשך

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	"cloud.google.com/go/compute/apiv1/computepb"
)

// getExternalAddress retrieves the external IP address of the given address.
func getRegionalExternal(w io.Writer, projectID, region, addressName string) (*computepb.Address, error) {
	// projectID := "your_project_id"
	// region := "europe-west3"
	// addressName := "your_address_name"

	ctx := context.Background()
	addressesClient, err := compute.NewAddressesRESTClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewAddressesRESTClient: %w", err)
	}
	defer addressesClient.Close()

	req := &computepb.GetAddressRequest{
		Project: projectID,
		Region:  region,
		Address: addressName,
	}

	address, err := addressesClient.Get(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to get address: %w", err)
	}

	fmt.Fprintf(w, "Regional address %s has external IP address: %s\n", addressName, address.GetAddress())

	return address, nil
}

func getGlobalExternal(w io.Writer, projectID, addressName string) (*computepb.Address, error) {

	ctx := context.Background()
	globalAddressesClient, err := compute.NewGlobalAddressesRESTClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewGlobalAddressesRESTClient: %w", err)
	}
	defer globalAddressesClient.Close()

	req := &computepb.GetGlobalAddressRequest{
		Project: projectID,
		Address: addressName,
	}

	address, err := globalAddressesClient.Get(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to get address: %w", err)
	}

	fmt.Fprintf(w, "Global address %s has external IP address: %s\n", addressName, address.GetAddress())

	return address, nil
}

Java


import com.google.cloud.compute.v1.Address;
import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.GetAddressRequest;
import com.google.cloud.compute.v1.GetGlobalAddressRequest;
import com.google.cloud.compute.v1.GlobalAddressesClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class GetStaticIpAddress {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Region where the VM and IP is located.
    String region = "your-region-id";
    // Name of the address to assign.
    String addressName = "your-addressName";

    getStaticIpAddress(projectId, region, addressName);
  }

  // Retrieves a static external IP address, either regional or global.
  public static Address getStaticIpAddress(String projectId, String region, String addressName)
          throws IOException {
    // Use regional client if a region is specified
    if (region != null) {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (AddressesClient client = AddressesClient.create()) {
        GetAddressRequest request = GetAddressRequest.newBuilder()
                .setProject(projectId)
                .setRegion(region)
                .setAddress(addressName)
                .build();

        return client.get(request);
      }
    } else {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (GlobalAddressesClient client = GlobalAddressesClient.create()) {
        GetGlobalAddressRequest request = GetGlobalAddressRequest.newBuilder()
                .setProject(projectId)
                .setAddress(addressName)
                .build();

        return client.get(request);
      }
    }
  }
}

Python

from typing import Optional

from google.cloud.compute_v1.services.addresses.client import AddressesClient
from google.cloud.compute_v1.services.global_addresses import GlobalAddressesClient
from google.cloud.compute_v1.types import Address


def get_static_ip_address(
    project_id: str, address_name: str, region: Optional[str] = None
) -> Address:
    """
    Retrieves a static external IP address, either regional or global.

    Args:
    project_id (str): project ID.
    address_name (str): The name of the IP address.
    region (Optional[str]): The region of the IP address if it's regional. None if it's global.

    Raises: google.api_core.exceptions.NotFound: in case of address not found

    Returns:
    Address: The Address object containing details about the requested IP.
    """
    if region:
        # Use regional client if a region is specified
        client = AddressesClient()
        address = client.get(project=project_id, region=region, address=address_name)
    else:
        # Use global client if no region is specified
        client = GlobalAddressesClient()
        address = client.get(project=project_id, address=address_name)

    return address

שחרור כתובת IP חיצונית סטטית

אם כבר אין לכם צורך בכתובת IPv4 או IPv6 חיצונית סטטית, אתם יכולים למחוק את משאב כתובת ה-IP כדי לבטל את ההקצאה של כתובת ה-IP.

אם אתם משתמשים במסוף Cloud de Confiance , תוכלו לבטל הקצאה של כתובת IP סטטית רק אם היא לא נמצאת בשימוש של משאב אחר.

אם אתם משתמשים ב-CLI של gcloud או ב-API, אתם יכולים לבטל הקצאה של כתובת IP גם אם היא בשימוש של משאב אחר.

  • אם כתובת ה-IP לא נמצאת בשימוש של משאב, היא מוחזרת למאגר של כתובות IP חיצוניות זמינות.

  • אם כתובת ה-IP נמצאת בשימוש של משאב, היא תישאר משויכת למשאב עד שהוא יימחק.

המסוף

  1. נכנסים לדף IP addresses במסוף Cloud de Confiance .

    מעבר אל כתובות IP

  2. לוחצים על External IP addresses (כתובות IP חיצוניות).

  3. אופציונלי: בשדה Filter, מזינים static ואז בוחרים באפשרות Static : Type מהרשימה הנפתחת.

  4. בוחרים את כתובת ה-IP החיצונית הקבועה שרוצים לבטל את ההקצאה שלה.

  5. לוחצים על External IP addresses.

    אם האפשרות הזו לא מופיעה, לוחצים על תפריט פעולות נוספות () בסרגל התפריטים העליון, ואז בוחרים באפשרות שחרור כתובת סטטית מהרשימה.

gcloud

משתמשים בפקודה compute addresses delete:

gcloud compute addresses delete ADDRESS_NAME

מחליפים את ADDRESS_NAME בשם של כתובת ה-IPv4 או ה-IPv6 שרוצים לבטל את ההקצאה שלה.

API

  • כדי לבטל הקצאה של כתובת IPv4 או IPv6 אזורית, קוראים לשיטה addresses.delete:

    DELETE https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/regions/REGION/addresses/ADDRESS_NAME
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט של הבקשה הזו
    • REGION: שם האזור של הבקשה
    • ADDRESS_NAME: השם של כתובת ה-IP
  • כדי לבטל הקצאה של כתובת IPv4 או IPv6 גלובלית, קוראים לשיטה globalAddresses.delete:

    DELETE https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/global/addresses/ADDRESS_NAME
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ADDRESS_NAME: השם של כתובת ה-IP
    • PROJECT_ID: מזהה הפרויקט של הבקשה הזו

המשך

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	"cloud.google.com/go/compute/apiv1/computepb"
)

// releaseRegionalStaticExternal releases a static regional external IP address.
func releaseRegionalStaticExternal(w io.Writer, projectID, region, addressName string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// addressName := "your_address_name"

	ctx := context.Background()
	addressesClient, err := compute.NewAddressesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewAddressesRESTClient: %w", err)
	}
	defer addressesClient.Close()

	req := &computepb.DeleteAddressRequest{
		Project: projectID,
		Region:  region,
		Address: addressName,
	}

	op, err := addressesClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to release static external IP address: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Static external IP address released\n")

	return nil
}

// releaseGlobalStaticExternal releases a static global external IP address.
func releaseGlobalStaticExternal(w io.Writer, projectID, addressName string) error {
	// projectID := "your_project_id"
	// addressName := "your_address_name"

	ctx := context.Background()
	addressesClient, err := compute.NewGlobalAddressesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGlobalAddressesRESTClient: %w", err)
	}
	defer addressesClient.Close()

	req := &computepb.DeleteGlobalAddressRequest{
		Project: projectID,
		Address: addressName,
	}

	op, err := addressesClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to release static external IP address: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Static external IP address released\n")

	return nil
}

Java


import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.DeleteAddressRequest;
import com.google.cloud.compute.v1.DeleteGlobalAddressRequest;
import com.google.cloud.compute.v1.GlobalAddressesClient;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ReleaseStaticAddress {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // The region to reserve the IP address in, if regional. Must be None if global
    String region = "your-region =";
    // Name of the address to release.
    String addressName = "your-addressName";

    releaseStaticAddress(projectId, addressName, region);
  }

  // Releases a static external IP address that is currently reserved.
  // This action requires that the address is not being used by any forwarding rule.
  public static void releaseStaticAddress(String projectId, String addressName, String region)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    Operation operation;
    // Use global client if no region is specified
    if (region == null) {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (GlobalAddressesClient client = GlobalAddressesClient.create()) {
        DeleteGlobalAddressRequest request = DeleteGlobalAddressRequest.newBuilder()
                .setProject(projectId)
                .setAddress(addressName)
                .build();

        operation = client.deleteCallable().futureCall(request).get(30, TimeUnit.SECONDS);
      }
    } else {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (AddressesClient client = AddressesClient.create()) {
        DeleteAddressRequest request = DeleteAddressRequest.newBuilder()
                .setProject(projectId)
                .setRegion(region)
                .setAddress(addressName)
                .build();

        operation = client.deleteCallable().futureCall(request).get(30, TimeUnit.SECONDS);
      }
    }
    if (operation.hasError()) {
      System.out.printf("Can't release external IP address '%s'. Caused by : %s",
              addressName, operation.getError());
    }
    System.out.printf("External IP address '%s' released successfully.", addressName);
  }
}

Python

from typing import Optional

from google.cloud.compute_v1.services.addresses.client import AddressesClient
from google.cloud.compute_v1.services.global_addresses import GlobalAddressesClient


def release_external_ip_address(
    project_id: str,
    address_name: str,
    region: Optional[str] = None,
) -> None:
    """
    Releases a static external IP address that is currently reserved.
    This action requires that the address is not being used by any forwarding rule.

    Args:
        project_id (str): project ID.
        address_name (str): name of the address to release.
        region (Optional[str]): The region to reserve the IP address in, if regional. Must be None if global.


    """
    if not region:  # global IP address
        client = GlobalAddressesClient()
        operation = client.delete(project=project_id, address=address_name)
    else:  # regional IP address
        client = AddressesClient()
        operation = client.delete(
            project=project_id, region=region, address=address_name
        )

    operation.result()
    print(f"External IP address '{address_name}' released successfully.")

המאמרים הבאים