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

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

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

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

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

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

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

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

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

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

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

  • compute.addresses.create בכתובת ה-IP
  • compute.addresses.createInternal בכתובת ה-IP
  • compute.networks.list ברשת
  • compute.subnetworks.use ברשת המשנה
  • compute.subnetworks.list ברשת המשנה

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

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

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

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

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

סוג כתובת ה-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 הבאות בהתאם לסוג המחסנית:

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

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

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

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

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

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

המסוף

  1. נכנסים לדף כתובות IP במסוף Google Cloud .

    לדף כתובות ה-IP

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

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

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

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

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

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

gcloud

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

כדי לשמור כתובת IPv4 או IPv6 חיצונית סטטית:

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

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

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

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

    gcloud compute addresses create ADDRESS_NAME \
       --region=REGION
    

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

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

    • כדי להקצות באופן אוטומטי כתובת IPv6 חיצונית אזורית מתת-רשת, מציינים את הערך IPV6 בדגל --ip-version:
    gcloud compute addresses create ADDRESS_NAME \
        --region=REGION \
        --subnet=SUBNET_NAME \
        --ip-version=IPV6 \
        --endpoint-type=ENDPOINT_TYPE
    
    • כדי לשמור כתובת IPv6 חיצונית אזורית ספציפית מרשת משנה, צריך לציין את הדגל --addresses. אל תכללו את הדגל --ip-version:
    gcloud compute addresses create ADDRESS_NAME \
        --region=REGION \
        --subnet=SUBNET_NAME \
        --endpoint-type=ENDPOINT_TYPE \
        --addresses=IPV6_ADDRESS
    

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

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

      בטווחי כתובות ה-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 אזורית, מפעילים את ה-method האזורית addresses.insert:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/addresses
    

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

    {
      "name": "ADDRESS_NAME"
    }
    

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

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

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/addresses
    

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

    {
      "name": "ADDRESS_NAME"
    }
    
  • לכתובות IPv6 סטטיות גלובליות, מפעילים את ה-method‏ globalAddresses.insert:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/addresses
    

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

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

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

  • לכתובות IPv6 סטטיות אזוריות, מפעילים את השיטה addresses.insert:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/addresses
    

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

    {
      "name": "ADDRESS_NAME",
      "ipVersion": "IPV6",
      "ipv6EndpointType": "ENDPOINT_TYPE",
      "networkTier": "IPV6_NETWORK_TIER",
      "subnetwork": "SUBNET",
      "address": "IPV6_ADDRESS"
    }
    

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

    • ‫ENDPOINT_TYPE: סוג נקודת הקצה, VM או NETLB.
    • ‫IPV6_NETWORK_TIER: רמת שירות הרשת של רשת המשנה. יכול להיות STANDARD (גרסת טרום-השקה (Preview)) או PREMIUM.
    • ‫SUBNET: רשת המשנה של הפרויקט.
    • ‫IPV6_ADDRESS: כתובת ה-IPv6 שרוצים לשמור, שצריכה להיות טווח כתובות IPv6 בגודל /96 מרשת המשנה. אם לא מציינים כתובת IP, המערכת מקצה אותה באופן אוטומטי.

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

    כדי לראות את התוצאה, משתמשים ב-method ‏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 חיצונית זמנית לכתובת שמורה לא גורם ל- Google Cloud להשמיט חבילות שנשלחות למכונה הווירטואלית. הנתון הזה כולל חבילות שנשלחות למכונה הווירטואלית באופן ישיר או באמצעות מאזן עומסים.

המסוף

  1. נכנסים לדף IP addresses.

    לדף כתובות ה-IP

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

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 אזורית זמנית לכתובת קבועה, צריך להפעיל את ה-method‏ addresses.insert:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/addresses

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

POST https://compute.googleapis.com/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 במסוף Google Cloud .

    לדף כתובות ה-IP

  2. לוחצים על כתובות 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 אזוריות, מפעילים את ה-method‏ addresses.list:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/addresses
    

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

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

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

    GET https://compute.googleapis.com/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 במסוף Google Cloud .

    לדף כתובות ה-IP

  2. לוחצים על כתובות 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.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/addresses/ADDRESS_NAME
    

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

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

    GET https://compute.googleapis.com/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 כדי לשחרר אותה.

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

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

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

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

המסוף

  1. נכנסים לדף כתובות IP במסוף Google Cloud .

    לדף כתובות ה-IP

  2. לוחצים על כתובות IP חיצוניות.

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

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

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

    אם האפשרות הזו לא מופיעה, לוחצים על התפריט More actions () בסרגל התפריטים העליון ובוחרים באפשרות Release static address מהרשימה.

gcloud

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

gcloud compute addresses delete ADDRESS_NAME

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

API

  • כדי לשחרר כתובת IPv4 או IPv6 אזורית, מפעילים את ה-method‏ addresses.delete:

    DELETE https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/addresses/ADDRESS_NAME
    

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

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

    DELETE https://compute.googleapis.com/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.")

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