יצירת מכונה מקובץ אימג' ציבורי

מכונה מכילה מנהל אתחול, מערכת קבצים לאתחול וקובץ אימג' של מערכת ההפעלה. במאמר הזה נסביר איך ליצור מכונה מקובץ אימג' ציבורי של מערכת הפעלה. אם יוצרים מכונה של Arm, צריך לבחור קובץ אימג' של מערכת הפעלה שתואם ל-Arm.

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

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

  • כשיוצרים מכונות מתמונות באמצעות Google Cloud CLI או Compute Engine API, יש מגבלה של 20 מכונות לשנייה. אם אתם צריכים ליצור מספר גדול יותר של מכונות בשנייה, בקשו שינוי במכסה של המשאב Images.
  • אם אתם משתמשים ברישיון קיים לתמונה, קראו את המאמר הבאת רישיונות משלכם.

  • אם עדיין לא עשיתם את זה, תצטרכו להגדיר אימות. אימות הוא התהליך שבו מאמתים את הזהות שלכם כדי לקבל גישה לממשקי API ולשירותים של Google Cloud . כדי להריץ קוד או דוגמאות מסביבת פיתוח מקומית, אפשר לבצע אימות ל-Compute Engine באחת מהדרכים האלה:

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

    המסוף

    כשמשתמשים במסוף Google Cloud כדי לגשת לשירותים ולממשקי ה-API של Google Cloud , לא צריך להגדיר אימות.

    gcloud

    1. התקינו את ה-CLI של Google Cloud. אחר כך, אתחלו את ה-CLI של Google Cloud באמצעות הפקודה הבאה:

      gcloud init

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  • הגדרת אזור ותחום כברירת מחדל.
  • REST

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של API בארכיטקטורת REST שבדף הזה, צריך להשתמש בפרטי הכניסה שאתם נותנים ל-CLI של gcloud.

      התקינו את ה-CLI של Google Cloud.

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

    מידע נוסף מופיע במאמר אימות לשימוש ב-REST במסמכי האימות של Google Cloud .

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

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

התפקיד שמוגדר מראש מכיל את ההרשאה compute.instances.create, שנדרשת כדי ליצור מכונה מקובץ אימג' ציבורי.

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

הצגת רשימה של קובצי אימג' ציבוריים שזמינים ב-Compute Engine

לפני שיוצרים מכונה באמצעות קובץ אימג' ציבורי, כדאי לעיין ברשימת קובצי האימג' הציבוריים שזמינים ב-Compute Engine.

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

המסוף

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

    כניסה לדף Images

gcloud

  1. מריצים את הפקודה הבאה:

    gcloud compute images list
  2. רושמים את שם התמונה או משפחת התמונות ואת שם הפרויקט שמכיל את התמונה.

  3. אופציונלי: כדי לבדוק אם קובץ האימג' תומך בתכונות של מכונה וירטואלית מוגנת, מריצים את הפקודה הבאה:

    gcloud compute images describe IMAGE_NAME \
        --project=IMAGE_PROJECT
    

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

    • ‫IMAGE_NAME: שם קובץ האימג' שרוצים לבדוק אם הוא תומך בתכונות של מכונה וירטואלית מוגנת
    • ‫IMAGE_PROJECT: הפרויקט שמכיל את קובץ האימג'

    אם התמונה תומכת בתכונות של מכונה וירטואלית מוגנת, השורה הבאה תופיע בפלט: type: UEFI_COMPATIBLE.

C#‎

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של C# במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine C# API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


using Google.Cloud.Compute.V1;
using System;
using System.Threading.Tasks;

public class ListImagesAsyncSample
{
    public async Task ListImagesAsync(
        // TODO(developer): Set your own default values for these parameters or pass different values when calling this method.
        string projectId = "your-project-id")
    {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        ImagesClient client = await ImagesClient.CreateAsync();

        // Make the request to list all non-deprecated images in a project.
        ListImagesRequest request = new ListImagesRequest
        {
            Project = projectId,
            // Listing only non-deprecated images to reduce the size of the reply.
            Filter = "deprecated.state != DEPRECATED",
            // MaxResults indicates the maximum number of items that will be returned per page.
            MaxResults = 100
        };

        // Although the MaxResults parameter is specified in the request, the sequence returned
        // by the ListAsync() method hides the pagination mechanic. The library makes multiple
        // requests to the API for you, so you can simply iterate over all the images.
        await foreach (var image in client.ListAsync(request))
        {
            // The result is an Image collection.
            Console.WriteLine($"Image: {image.Name}");
        }
    }
}

המשך

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Go במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Go API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import (
	"context"
	"fmt"
	"io"

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

// printImagesList prints a list of all non-deprecated image names available in given project.
func printImagesList(w io.Writer, projectID string) error {
	// projectID := "your_project_id"
	ctx := context.Background()
	imagesClient, err := compute.NewImagesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewImagesRESTClient: %w", err)
	}
	defer imagesClient.Close()

	// Listing only non-deprecated images to reduce the size of the reply.
	req := &computepb.ListImagesRequest{
		Project:    projectID,
		MaxResults: proto.Uint32(3),
		Filter:     proto.String("deprecated.state != DEPRECATED"),
	}

	// Although the `MaxResults` parameter is specified in the request, the iterator returned
	// by the `list()` method hides the pagination mechanic. The library makes multiple
	// requests to the API for you, so you can simply iterate over all the images.
	it := imagesClient.List(ctx, req)
	for {
		image, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s\n", image.GetName())
	}
	return nil
}

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Java במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Java API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.cloud.compute.v1.Image;
import com.google.cloud.compute.v1.ImagesClient;
import com.google.cloud.compute.v1.ImagesClient.ListPage;
import com.google.cloud.compute.v1.ListImagesRequest;
import java.io.IOException;
  // Prints a list of all non-deprecated image names available in given project.
  public static void listImages(String project) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `instancesClient.close()` method on the client to
    // safely clean up any remaining background resources.
    try (ImagesClient imagesClient = ImagesClient.create()) {

      // Listing only non-deprecated images to reduce the size of the reply.
      ListImagesRequest imagesRequest = ListImagesRequest.newBuilder()
          .setProject(project)
          .setMaxResults(100)
          .setFilter("deprecated.state != DEPRECATED")
          .build();

      // Although the `setMaxResults` parameter is specified in the request, the iterable returned
      // by the `list()` method hides the pagination mechanic. The library makes multiple
      // requests to the API for you, so you can simply iterate over all the images.
      int imageCount = 0;
      for (Image image : imagesClient.list(imagesRequest).iterateAll()) {
        imageCount++;
        System.out.println(image.getName());
      }
      System.out.printf("Image count in %s is: %s", project, imageCount);
    }
  }

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Node.js במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Node.js API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';

const compute = require('@google-cloud/compute');

async function listImages() {
  const imagesClient = new compute.ImagesClient();

  // Listing only non-deprecated images to reduce the size of the reply.
  const images = imagesClient.listAsync({
    project: projectId,
    maxResults: 3,
    filter: 'deprecated.state != DEPRECATED',
  });

  // Although the `maxResults` parameter is specified in the request, the iterable returned
  // by the `listAsync()` method hides the pagination mechanic. The library makes multiple
  // requests to the API for you, so you can simply iterate over all the images.
  for await (const image of images) {
    console.log(` - ${image.name}`);
  }
}

listImages();

PHP

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של PHP במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine PHP API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

use Google\Cloud\Compute\V1\Client\ImagesClient;
use Google\Cloud\Compute\V1\ListImagesRequest;

/**
 * Prints a list of all non-deprecated image names available in given project.
 *
 * @param string $projectId Project ID or project number of the Cloud project you want to list images from.
 *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 */
function list_all_images(string $projectId)
{
    $imagesClient = new ImagesClient();
    // Listing only non-deprecated images to reduce the size of the reply.
    $optionalArgs = ['maxResults' => 100, 'filter' => 'deprecated.state != DEPRECATED'];

    /**
     * Although the maxResults parameter is specified in the request, the iterateAllElements() method
     * hides the pagination mechanic. The library makes multiple requests to the API for you,
     * so you can simply iterate over all the images.
     */
    $request = (new ListImagesRequest())
        ->setProject($projectId)
        ->setMaxResults($optionalArgs['maxResults'])
        ->setFilter($optionalArgs['filter']);
    $pagedResponse = $imagesClient->list($request);
    print('=================== Flat list of images ===================' . PHP_EOL);
    foreach ($pagedResponse->iterateAllElements() as $element) {
        printf(' - %s' . PHP_EOL, $element->getName());
    }
}

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Python API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import google.cloud.compute_v1 as compute_v1

def print_images_list(project: str) -> str:
    """
    Prints a list of all non-deprecated image names available in given project.

    Args:
        project: project ID or project number of the Cloud project you want to list images from.

    Returns:
        The output as a string.
    """
    images_client = compute_v1.ImagesClient()
    # Listing only non-deprecated images to reduce the size of the reply.
    images_list_request = compute_v1.ListImagesRequest(
        project=project, max_results=100, filter="deprecated.state != DEPRECATED"
    )
    output = []

    # Although the `max_results` parameter is specified in the request, the iterable returned
    # by the `list()` method hides the pagination mechanic. The library makes multiple
    # requests to the API for you, so you can simply iterate over all the images.
    for img in images_client.list(request=images_list_request):
        print(f" -  {img.name}")
        output.append(f" -  {img.name}")
    return "\n".join(output)

Ruby

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Ruby במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Ruby API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


require "google/cloud/compute/v1"

# Prints a list of all non-deprecated image names available in given project.
#
# @param [String] project project ID or project number of the Cloud project you want to list images from.
def print_images_list project:
  client = ::Google::Cloud::Compute::V1::Images::Rest::Client.new

  # Make the request to list all non-deprecated images in a project.
  request = {
    project: project,
    # max_results indicates the maximum number of items that will be returned per page.
    max_results: 100,
    # Listing only non-deprecated images to reduce the size of the reply.
    filter: "deprecated.state != DEPRECATED"
  }

  # Although the `max_results` parameter is specified in the request, the iterable returned
  # by the `list` method hides the pagination mechanic. The library makes multiple
  # requests to the API for you, so you can simply iterate over all the images.
  client.list(request).each do |image|
    puts " - #{image.name}"
  end
end

REST

  1. מריצים את הפקודה הבאה:

    GET https://compute.googleapis.com/compute/v1/projects/IMAGE_PROJECT/global/images/
    
  2. רושמים את שם התמונה או משפחת התמונות ואת שם הפרויקט שמכיל את התמונה.

  3. אופציונלי: כדי לבדוק אם קובץ האימג' תומך בתכונות של מכונה וירטואלית מוגנת, מריצים את הפקודה הבאה:

    GET https://compute.googleapis.com/compute/v1/projects/IMAGE_PROJECT/global/images/IMAGE_NAME
    

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

    • ‫IMAGE_PROJECT: הפרויקט שמכיל את קובץ האימג'
    • ‫IMAGE_NAME: שם קובץ האימג' שרוצים לבדוק אם הוא תומך בתכונות של מכונה וירטואלית מוגנת

    אם התמונה תומכת בתכונות של מכונה וירטואלית מוגנת, השורה הבאה תופיע בפלט: type: UEFI_COMPATIBLE.

יצירת מכונה וירטואלית מקובץ אימג' ציבורי

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

אם יוצרים קובץ אימג' של מכונה וירטואלית מוגנת עם SSD מקומי, אי אפשר להגן על הנתונים באמצעות מעקב אחר תקינות או מודול פלטפורמה מהימנה וירטואלית (vTPM).

המסוף

  1. נכנסים לדף Create an instance במסוף Google Cloud .

    כניסה לדף Create an instance

    אם מוצגת בקשה, בוחרים את הפרויקט ולוחצים על Continue. הדף Create an instance מופיע ובו החלונית Machine configuration.

  2. בחלונית Machine configuration:

    1. בשדה Name, נותנים שם למכונה הווירטואלית. מידע נוסף זמין במאמר מוסכמות למתן שמות למשאבים.
    2. אופציונלי: בשדה Zone, בוחרים אזור למכונה הווירטואלית.

      ברירת המחדל היא כל. אם לא תשנו את בחירת ברירת המחדל הזו, Google תבחר בשבילכם אזור באופן אוטומטי על סמך סוג המכונה והזמינות.

    3. בוחרים את משפחת המכונות של ה-VM. במסוף Google Cloud יוצגו סדרות המכונות שזמינות למשפחת המכונות שבחרתם. אלה האפשרויות הזמינות למשפחת המכונות:

      • לשימוש כללי
      • אופטימיזציה של המחשוב
      • מותאמת לצריכת זיכרון גבוהה (memory-optimized)
      • אופטימיזציה של נפח האחסון
      • אופטימיזציה של הרשת
      • מעבדים גרפיים
      • יחידות TPU

    4. בעמודה Series, בוחרים את סדרת המכונות של ה-VM.

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

    5. בקטע Machine type, בוחרים את סוג המכונה של ה-VM.

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

    1. לוחצים על Change. מופיע החלונית דיסק אתחול ומוצגת הכרטיסייה Public images.
    2. ברשימה Operating system בוחרים את סוג מערכת ההפעלה.
    3. ברשימה Version בוחרים את גרסת מערכת ההפעלה.
    4. ברשימה Boot disk type, בוחרים את סוג דיסק האתחול.
    5. בשדה Size (GB) מציינים את גודל דיסק האתחול.
    6. אופציונלי: בדיסקי אתחול מסוג Hyperdisk Balanced, מציינים ערכים בשדות Provisioned IOPS ו-Provisioned throughput.
    7. אופציונלי: כדי לראות אפשרויות הגדרה מתקדמות, מרחיבים את הקטע Show advanced configurations.
    8. כדי לאשר את האפשרויות של דיסק האתחול ולחזור לחלונית Operating system and storage, לוחצים על Select.
  4. בתפריט הניווט, לוחצים על Networking. בחלונית Networking שמופיעה:

    1. עוברים לקטע Firewall.
    2. כדי לאפשר תנועת HTTP או HTTPS למכונה הווירטואלית, בוחרים באפשרות Allow HTTP traffic או Allow HTTPS traffic.

      ‫Compute Engine מוסיף תג רשת למכונה הווירטואלית ויוצר את כלל חומת האש המתאים לתעבורת נתונים נכנסת, שמאפשר את כל תעבורת הנתונים הנכנסת ב-tcp:80 (HTTP) או ב-tcp:443 (HTTPS). תג הרשת משייך את הכלל של חומת האש למכונה הווירטואלית. מידע נוסף זמין במאמר סקירה כללית של כללי חומת האש במסמכי התיעוד של Cloud Next Generation Firewall.

  5. אופציונלי: אם בחרתם קובץ אימג' של מערכת הפעלה שתומך בתכונות של מכונה וירטואלית מוגנת, אתם יכולים לשנות את ההגדרות של המכונה הווירטואלית המוגנת.

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

  6. אופציונלי: מציינים אפשרויות הגדרה אחרות. למידע נוסף, ראו אפשרויות הגדרה במהלך יצירת מכונה.

  7. כדי ליצור את המכונה הווירטואלית ולהפעיל אותה, לוחצים על Create.

gcloud

  1. בוחרים תמונה שגלויה לכולם. רושמים את השם של קובץ האימג' או של משפחת קובצי האימג' ואת שם הפרויקט שמכיל את קובץ האימג'.
  2. משתמשים בפקודה gcloud compute instances create כדי ליצור מכונה וירטואלית ממשפחת קובצי אימג' או מגרסה ספציפית של קובץ אימג' של מערכת הפעלה.

    אם מציינים את הדגל האופציונלי --shielded-secure-boot,‏ Compute Engine יוצר מכונה וירטואלית שבה מופעלות כל שלוש התכונות של מכונה וירטואלית מוגנת:

    אחרי ש-Compute Engine מפעיל את ה-VM, צריך לעצור את ה-VM כדי לשנות את האפשרויות של המכונה הווירטואלית המוגנת.

    gcloud compute instances create VM_NAME \
        --zone=ZONE \
        --image-project=IMAGE_PROJECT \
        IMAGE_FLAG \
        --machine-type=MACHINE_TYPE

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

    • ‫VM_NAME: השם של המכונה הווירטואלית החדשה
    • ‫ZONE: האזור שבו יוצרים את המכונה
    • ‫IMAGE_PROJECT: הפרויקט שמכיל את קובץ האימג'
    • ‫IMAGE_FLAG: מציינים אחת מהאפשרויות הבאות:

      • משתמשים בדגל --image IMAGE_NAME כדי לציין גרסה ספציפית של תמונה ציבורית.

        לדוגמה, --image debian-12-bookworm-v20241112.

      • משתמשים בדגל --image-family IMAGE_FAMILY_NAME כדי לציין משפחת תמונות.

        כך נוצרת ה-VM מקובץ אימג' של מערכת ההפעלה העדכני ביותר במשפחת קובצי האימג', שלא הוצא משימוש. לדוגמה, אם מציינים את הערך --image-family debian-12, ‏Compute Engine משתמש בגרסה העדכנית של קובץ האימג' של מערכת ההפעלה במשפחת קובצי האימג' של Debian 12.

    • ‫MACHINE_TYPE: סוג המכונה של המכונה הווירטואלית החדשה, שיכול להיות סוג מכונה מוגדר מראש או סוג מכונה בהתאמה אישית.

      כדי לקבל רשימה של סוגי המכונות שזמינים באזור מסוים, משתמשים בפקודה gcloud compute machine-types list עם הדגל --zones.

  3. מוודאים ש-Compute Engine יצר את ה-VM:

    gcloud compute instances describe VM_NAME
    

    מחליפים את VM_NAME בשם של המכונה הווירטואלית.

Terraform

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


# Create a VM instance from a public image
# in the `default` VPC network and subnet

resource "google_compute_instance" "default" {
  name         = "my-vm"
  machine_type = "n1-standard-1"
  zone         = "us-central1-a"

  boot_disk {
    initialize_params {
      image = "ubuntu-minimal-2210-kinetic-amd64-v20230126"
    }
  }

  network_interface {
    network = "default"
    access_config {}
  }
}

כדי ללמוד איך להחיל הגדרות ב-Terraform או להסיר אותן, ראו פקודות בסיסיות ב-Terraform.

כדי ליצור את קוד Terraform, אפשר להשתמש ברכיב Equivalent code במסוף Google Cloud .
  1. נכנסים לדף VM instances במסוף Google Cloud .

    כניסה לדף VM Instances

  2. לוחצים על Create instance.
  3. מציינים את הפרמטרים הרצויים.
  4. בחלק העליון או התחתון של הדף, לוחצים על Equivalent code ואז על הכרטיסייה Terraform כדי לראות את הקוד של Terraform.

C#‎

C#

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של C# במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine C# API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


using Google.Cloud.Compute.V1;
using System.Threading.Tasks;

public class CreateInstanceAsyncSample
{
    public async Task CreateInstanceAsync(
        // TODO(developer): Set your own default values for these parameters or pass different values when calling this method.
        string projectId = "your-project-id",
        string zone = "us-central1-a",
        string machineName = "test-machine",
        string machineType = "n1-standard-1",
        string diskImage = "projects/debian-cloud/global/images/family/debian-12",
        long diskSizeGb = 10,
        string networkName = "default")
    {
        Instance instance = new Instance
        {
            Name = machineName,
            // See https://cloud.google.com/compute/docs/machine-types for more information on machine types.
            MachineType = $"zones/{zone}/machineTypes/{machineType}",
            // Instance creation requires at least one persistent disk.
            Disks =
            {
                new AttachedDisk
                {
                    AutoDelete = true,
                    Boot = true,
                    Type = ComputeEnumConstants.AttachedDisk.Type.Persistent,
                    InitializeParams = new AttachedDiskInitializeParams 
                    {
                        // See https://cloud.google.com/compute/docs/images for more information on available images.
                        SourceImage = diskImage,
                        DiskSizeGb = diskSizeGb
                    }
                }
            },
            NetworkInterfaces = { new NetworkInterface { Name = networkName } }
        };

        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        InstancesClient client = await InstancesClient.CreateAsync();

        // Insert the instance in the specified project and zone.
        var instanceCreation = await client.InsertAsync(projectId, zone, instance);

        // Wait for the operation to complete using client-side polling.
        // The server-side operation is not affected by polling,
        // and might finish successfully even if polling times out.
        await instanceCreation.PollUntilCompletedAsync();
    }
}

המשך

Go

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Go במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Go API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import (
	"context"
	"fmt"
	"io"

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

// createInstance sends an instance creation request to the Compute Engine API and waits for it to complete.
func createInstance(w io.Writer, projectID, zone, instanceName, machineType, sourceImage, networkName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// machineType := "n1-standard-1"
	// sourceImage := "projects/debian-cloud/global/images/family/debian-12"
	// networkName := "global/networks/default"

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

	req := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			Disks: []*computepb.AttachedDisk{
				{
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb:  proto.Int64(10),
						SourceImage: proto.String(sourceImage),
					},
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(true),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
				},
			},
			MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/%s", zone, machineType)),
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					Name: proto.String(networkName),
				},
			},
		},
	}

	op, err := instancesClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create instance: %w", err)
	}

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

	fmt.Fprintf(w, "Instance created\n")

	return nil
}

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Java במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Java API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDisk.Type;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
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 CreateInstance {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";
    createInstance(project, zone, instanceName);
  }


  // Create a new instance with the provided "instanceName" value in the specified project and zone.
  public static void createInstance(String project, String zone, String instanceName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // Below are sample values that can be replaced.
    // machineType: machine type of the VM being created.
    // *   This value uses the format zones/{zone}/machineTypes/{type_name}.
    // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
    // sourceImage: path to the operating system image to mount.
    // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
    // diskSizeGb: storage size of the boot disk to attach to the instance.
    // networkName: network interface to associate with the instance.
    String machineType = String.format("zones/%s/machineTypes/n1-standard-1", zone);
    String sourceImage = String
        .format("projects/debian-cloud/global/images/family/%s", "debian-13");
    long diskSizeGb = 10L;
    String networkName = "default";

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `instancesClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create()) {
      // Instance creation requires at least one persistent disk and one network interface.
      AttachedDisk disk =
          AttachedDisk.newBuilder()
              .setBoot(true)
              .setAutoDelete(true)
              .setType(Type.PERSISTENT.toString())
              .setDeviceName("disk-1")
              .setInitializeParams(
                  AttachedDiskInitializeParams.newBuilder()
                      .setSourceImage(sourceImage)
                      .setDiskSizeGb(diskSizeGb)
                      .build())
              .build();

      // Use the network interface provided in the networkName argument.
      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName(networkName)
          .build();

      // Bind `instanceName`, `machineType`, `disk`, and `networkInterface` to an instance.
      Instance instanceResource =
          Instance.newBuilder()
              .setName(instanceName)
              .setMachineType(machineType)
              .addDisks(disk)
              .addNetworkInterfaces(networkInterface)
              .build();

      System.out.printf("Creating instance: %s at %s %n", instanceName, zone);

      // Insert the instance in the specified project and zone.
      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(project)
          .setZone(zone)
          .setInstanceResource(instanceResource)
          .build();

      OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
          insertInstanceRequest);

      // Wait for the operation to complete.
      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        System.out.println("Instance creation failed ! ! " + response);
        return;
      }
      System.out.println("Operation Status: " + response.getStatus());
    }
  }
}

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Node.js במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Node.js API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b'
// const instanceName = 'YOUR_INSTANCE_NAME'
// const machineType = 'n1-standard-1';
// const sourceImage = 'projects/debian-cloud/global/images/family/debian-11';
// const networkName = 'global/networks/default';

const compute = require('@google-cloud/compute');

// Create a new instance with the values provided above in the specified project and zone.
async function createInstance() {
  const instancesClient = new compute.InstancesClient();

  console.log(`Creating the ${instanceName} instance in ${zone}...`);

  const [response] = await instancesClient.insert({
    instanceResource: {
      name: instanceName,
      disks: [
        {
          // Describe the size and source image of the boot disk to attach to the instance.
          initializeParams: {
            diskSizeGb: '10',
            sourceImage,
          },
          autoDelete: true,
          boot: true,
          type: 'PERSISTENT',
        },
      ],
      machineType: `zones/${zone}/machineTypes/${machineType}`,
      networkInterfaces: [
        {
          // Use the network interface provided in the networkName argument.
          name: networkName,
        },
      ],
    },
    project: projectId,
    zone,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the create operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Instance created.');
}

createInstance();

PHP

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של PHP במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine PHP API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

use Google\Cloud\Compute\V1\AttachedDisk;
use Google\Cloud\Compute\V1\AttachedDisk\Type;
use Google\Cloud\Compute\V1\AttachedDiskInitializeParams;
use Google\Cloud\Compute\V1\Client\InstancesClient;
use Google\Cloud\Compute\V1\InsertInstanceRequest;

/**
 * To correctly handle string enums in Cloud Compute library
 * use constants defined in the Enums subfolder.
 */
use Google\Cloud\Compute\V1\Instance;
use Google\Cloud\Compute\V1\NetworkInterface;

/**
 * Creates an instance in the specified project and zone.
 *
 * @param string $projectId Project ID of the Cloud project to create the instance in.
 * @param string $zone Zone to create the instance in (like "us-central1-a").
 * @param string $instanceName Unique name for this Compute Engine instance.
 * @param string $machineType Machine type of the instance being created.
 * @param string $sourceImage Boot disk image name or family.
 * @param string $networkName Network interface to associate with the instance.
 *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function create_instance(
    string $projectId,
    string $zone,
    string $instanceName,
    string $machineType = 'n1-standard-1',
    string $sourceImage = 'projects/debian-cloud/global/images/family/debian-11',
    string $networkName = 'global/networks/default'
) {
    // Set the machine type using the specified zone.
    $machineTypeFullName = sprintf('zones/%s/machineTypes/%s', $zone, $machineType);

    // Describe the source image of the boot disk to attach to the instance.
    $diskInitializeParams = (new AttachedDiskInitializeParams())
        ->setSourceImage($sourceImage);
    $disk = (new AttachedDisk())
        ->setBoot(true)
        ->setAutoDelete(true)
        ->setType(Type::name(Type::PERSISTENT))
        ->setInitializeParams($diskInitializeParams);

    // Use the network interface provided in the $networkName argument.
    $network = (new NetworkInterface())
        ->setName($networkName);

    // Create the Instance object.
    $instance = (new Instance())
        ->setName($instanceName)
        ->setDisks([$disk])
        ->setMachineType($machineTypeFullName)
        ->setNetworkInterfaces([$network]);

    // Insert the new Compute Engine instance using InstancesClient.
    $instancesClient = new InstancesClient();
    $request = (new InsertInstanceRequest())
        ->setInstanceResource($instance)
        ->setProject($projectId)
        ->setZone($zone);
    $operation = $instancesClient->insert($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Created instance %s' . PHP_EOL, $instanceName);
    } else {
        $error = $operation->getError();
        printf('Instance creation failed: %s' . PHP_EOL, $error?->getMessage());
    }
}

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Python API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

from __future__ import annotations

import re
import sys
from typing import Any
import warnings

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def get_image_from_family(project: str, family: str) -> compute_v1.Image:
    """
    Retrieve the newest image that is part of a given family in a project.

    Args:
        project: project ID or project number of the Cloud project you want to get image from.
        family: name of the image family you want to get image from.

    Returns:
        An Image object.
    """
    image_client = compute_v1.ImagesClient()
    # List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
    newest_image = image_client.get_from_family(project=project, family=family)
    return newest_image


def disk_from_image(
    disk_type: str,
    disk_size_gb: int,
    boot: bool,
    source_image: str,
    auto_delete: bool = True,
) -> compute_v1.AttachedDisk:
    """
    Create an AttachedDisk object to be used in VM instance creation. Uses an image as the
    source for the new disk.

    Args:
         disk_type: the type of disk you want to create. This value uses the following format:
            "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
            For example: "zones/us-west3-b/diskTypes/pd-ssd"
        disk_size_gb: size of the new disk in gigabytes
        boot: boolean flag indicating whether this disk should be used as a boot disk of an instance
        source_image: source image to use when creating this disk. You must have read access to this disk. This can be one
            of the publicly available images or an image from one of your projects.
            This value uses the following format: "projects/{project_name}/global/images/{image_name}"
        auto_delete: boolean flag indicating whether this disk should be deleted with the VM that uses it

    Returns:
        AttachedDisk object configured to be created using the specified image.
    """
    boot_disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_image = source_image
    initialize_params.disk_size_gb = disk_size_gb
    initialize_params.disk_type = disk_type
    boot_disk.initialize_params = initialize_params
    # Remember to set auto_delete to True if you want the disk to be deleted when you delete
    # your VM instance.
    boot_disk.auto_delete = auto_delete
    boot_disk.boot = boot
    return boot_disk


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

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

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

    Returns:
        Whatever the operation.result() returns.

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

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

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

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

    return result


def create_instance(
    project_id: str,
    zone: str,
    instance_name: str,
    disks: list[compute_v1.AttachedDisk],
    machine_type: str = "n1-standard-1",
    network_link: str = "global/networks/default",
    subnetwork_link: str = None,
    internal_ip: str = None,
    external_access: bool = False,
    external_ipv4: str = None,
    accelerators: list[compute_v1.AcceleratorConfig] = None,
    preemptible: bool = False,
    spot: bool = False,
    instance_termination_action: str = "STOP",
    custom_hostname: str = None,
    delete_protection: bool = False,
) -> compute_v1.Instance:
    """
    Send an instance creation request to the Compute Engine API and wait for it to complete.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        disks: a list of compute_v1.AttachedDisk objects describing the disks
            you want to attach to your new instance.
        machine_type: machine type of the VM being created. This value uses the
            following format: "zones/{zone}/machineTypes/{type_name}".
            For example: "zones/europe-west3-c/machineTypes/f1-micro"
        network_link: name of the network you want the new instance to use.
            For example: "global/networks/default" represents the network
            named "default", which is created automatically for each project.
        subnetwork_link: name of the subnetwork you want the new instance to use.
            This value uses the following format:
            "regions/{region}/subnetworks/{subnetwork_name}"
        internal_ip: internal IP address you want to assign to the new instance.
            By default, a free address from the pool of available internal IP addresses of
            used subnet will be used.
        external_access: boolean flag indicating if the instance should have an external IPv4
            address assigned.
        external_ipv4: external IPv4 address to be assigned to this instance. If you specify
            an external IP address, it must live in the same region as the zone of the instance.
            This setting requires `external_access` to be set to True to work.
        accelerators: a list of AcceleratorConfig objects describing the accelerators that will
            be attached to the new instance.
        preemptible: boolean value indicating if the new instance should be preemptible
            or not. Preemptible VMs have been deprecated and you should now use Spot VMs.
        spot: boolean value indicating if the new instance should be a Spot VM or not.
        instance_termination_action: What action should be taken once a Spot VM is terminated.
            Possible values: "STOP", "DELETE"
        custom_hostname: Custom hostname of the new VM instance.
            Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
        delete_protection: boolean value indicating if the new virtual machine should be
            protected against deletion or not.
    Returns:
        Instance object.
    """
    instance_client = compute_v1.InstancesClient()

    # Use the network interface provided in the network_link argument.
    network_interface = compute_v1.NetworkInterface()
    network_interface.network = network_link
    if subnetwork_link:
        network_interface.subnetwork = subnetwork_link

    if internal_ip:
        network_interface.network_i_p = internal_ip

    if external_access:
        access = compute_v1.AccessConfig()
        access.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.name
        access.name = "External NAT"
        access.network_tier = access.NetworkTier.PREMIUM.name
        if external_ipv4:
            access.nat_i_p = external_ipv4
        network_interface.access_configs = [access]

    # Collect information into the Instance object.
    instance = compute_v1.Instance()
    instance.network_interfaces = [network_interface]
    instance.name = instance_name
    instance.disks = disks
    if re.match(r"^zones/[a-z\d\-]+/machineTypes/[a-z\d\-]+$", machine_type):
        instance.machine_type = machine_type
    else:
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"

    instance.scheduling = compute_v1.Scheduling()
    if accelerators:
        instance.guest_accelerators = accelerators
        instance.scheduling.on_host_maintenance = (
            compute_v1.Scheduling.OnHostMaintenance.TERMINATE.name
        )

    if preemptible:
        # Set the preemptible setting
        warnings.warn(
            "Preemptible VMs are being replaced by Spot VMs.", DeprecationWarning
        )
        instance.scheduling = compute_v1.Scheduling()
        instance.scheduling.preemptible = True

    if spot:
        # Set the Spot VM setting
        instance.scheduling.provisioning_model = (
            compute_v1.Scheduling.ProvisioningModel.SPOT.name
        )
        instance.scheduling.instance_termination_action = instance_termination_action

    if custom_hostname is not None:
        # Set the custom hostname for the instance
        instance.hostname = custom_hostname

    if delete_protection:
        # Set the delete protection bit
        instance.deletion_protection = True

    # Prepare the request to insert an instance.
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    # Wait for the create operation to complete.
    print(f"Creating the {instance_name} instance in {zone}...")

    operation = instance_client.insert(request=request)

    wait_for_extended_operation(operation, "instance creation")

    print(f"Instance {instance_name} created.")
    return instance_client.get(project=project_id, zone=zone, instance=instance_name)

Ruby

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Ruby במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Ruby API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


require "google/cloud/compute/v1"

# Sends an instance creation request to the Compute Engine API and waits for it to complete.
#
# @param [String] project project ID or project number of the Cloud project you want to use.
# @param [String] zone name of the zone you want to use. For example: "us-west3-b"
# @param [String] instance_name name of the new virtual machine.
# @param [String] machine_type machine type of the VM being created. For example: "e2-standard-2"
#         See https://cloud.google.com/compute/docs/machine-types for more information
#         on machine types.
# @param [String] source_image path to the operating system image to mount on your boot
#         disk. This can be one of the public images
#         (like "projects/debian-cloud/global/images/family/debian-12")
#         or a private image you have access to.
#         See https://cloud.google.com/compute/docs/images for more information on available images.
# @param [String] network_name name of the network you want the new instance to use.
#         For example: "global/networks/default" represents the `default`
#         network interface, which is created automatically for each project.
def create_instance project:, zone:, instance_name:,
                    machine_type: "n2-standard-2",
                    source_image: "projects/debian-cloud/global/images/family/debian-12",
                    network_name: "global/networks/default"
  # Initialize client that will be used to send requests. This client only needs to be created
  # once, and can be reused for multiple requests.
  client = ::Google::Cloud::Compute::V1::Instances::Rest::Client.new

  # Construct the instance object.
  # It can be either a hash or ::Google::Cloud::Compute::V1::Instance instance.
  instance = {
    name: instance_name,
    machine_type: "zones/#{zone}/machineTypes/#{machine_type}",
    # Instance creation requires at least one persistent disk.
    disks: [{
      auto_delete: true,
      boot: true,
      type: :PERSISTENT,
      initialize_params: {
        source_image: source_image,
        disk_size_gb: 10
      }
    }],
    network_interfaces: [{ name: network_name }]
  }

  # Prepare a request to create the instance in the specified project and zone.
  request = { project: project, zone: zone, instance_resource: instance }

  puts "Creating the #{instance_name} instance in #{zone}..."
  begin
    # Send the insert request.
    operation = client.insert request
    # Wait for the create operation to complete.
    operation = wait_until_done operation: operation

    compute_operation = operation.operation
    if operation.error?
      warn "Error during creation:", compute_operation.error.errors.map { |e| "#{e.code}: #{e.message}" }
    else
      warn "Warning during creation:", compute_operation.warnings unless compute_operation.warnings.empty?
      puts "Instance #{instance_name} created."
    end
  rescue ::Google::Cloud::Error => e
    warn "Exception during creation:", e
  end
end

REST

  1. בוחרים תמונה שגלויה לכולם. רושמים את השם של קובץ האימג' או של משפחת קובצי האימג' ואת שם הפרויקט שמכיל את קובץ האימג'.
  2. כדי ליצור מכונה וירטואלית ממשפחת קובצי אימג' או מגרסה ספציפית של קובץ אימג' של מערכת הפעלה, משתמשים בשיטה instances.insert:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
    
    {
       "machineType":"zones/MACHINE_TYPE_ZONE/machineTypes/MACHINE_TYPE",
       "name":"VM_NAME",
       
       "disks":[
          {
             "initializeParams":{
                "sourceImage":"projects/IMAGE_PROJECT/global/images/IMAGE"
             },
             "boot":true
          }
       ],
       
       
       "networkInterfaces":[
          {
             "network":"global/networks/NETWORK_NAME"
          }
       ],
       
      
       "shieldedInstanceConfig":{
          "enableSecureBoot":"ENABLE_SECURE_BOOT"
       }
    }
    

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

    • ‫PROJECT_ID: מזהה הפרויקט שבו יוצרים את המכונה הווירטואלית
    • ‫ZONE: האזור שבו יוצרים את המכונה הווירטואלית
    • ‫MACHINE_TYPE_ZONE: האזור שבו נמצא סוג המכונה שרוצים להשתמש בו בשביל המכונה הווירטואלית החדשה
    • ‫MACHINE_TYPE: סוג המכונה, מוגדר מראש או בהתאמה אישית, של המכונה הווירטואלית החדשה
    • ‫VM_NAME: השם של המכונה הווירטואלית החדשה
    • ‫IMAGE_PROJECT: הפרויקט שמכיל את קובץ האימג'
      . לדוגמה, אם מציינים את debian-12 בתור משפחת קובצי האימג', צריך לציין את debian-cloud בתור פרויקט קובץ האימג'.
    • ‫IMAGE: מציינים אחת מהאפשרויות הבאות:
      • ‫IMAGE: גרסה ספציפית של קובץ אימג' ציבורי

        לדוגמה, "sourceImage": "projects/debian-cloud/global/images/debian-12-bookworm-v20241112"

      • ‫IMAGE_FAMILY: משפחת קובצי אימג'

        כשמציינים משפחת קובצי אימג', המכונה הווירטואלית נוצרת מקובץ האימג' העדכני ביותר של מערכת ההפעלה, שלא הוצא משימוש. לדוגמה, אם מציינים את הערך "sourceImage": "projects/debian-cloud/global/images/family/debian-12", ‏Compute Engine יוצרת מכונה וירטואלית מהגרסה העדכנית של קובץ האימג' של מערכת ההפעלה במשפחת קובצי האימג' של Debian 12.

    • ‫NETWORK_NAME: רשת ה-VPC שבה רוצים להשתמש בשביל ה-VM. אפשר לציין את הערך default כדי להשתמש ברשת ברירת המחדל.
    • ‫ENABLE_SECURE_BOOT: אופציונלי: אם בחרתם תמונה שתומכת בתכונות של מכונה וירטואלית מוגנת, כברירת מחדל Compute Engine מפעיל את מודול הפלטפורמה המהימנה הווירטואלית (vTPM) ואת מעקב התקינות. כברירת מחדל, Compute Engine לא מפעיל את Secure Boot.

      אם מציינים את הערך true בשדה enableSecureBoot, המערכת של Compute Engine יוצרת מכונה וירטואלית שבה מופעלות כל שלוש התכונות של מכונה וירטואלית מוגנת. אחרי ש-Compute Engine מפעיל את ה-VM, כדי לשנות את האפשרויות של המכונה הווירטואלית המוגנת צריך לעצור את ה-VM.

יצירת מכונה פיזית מקובץ אימג' ציבורי

‫Google, קהילות קוד פתוח וספקים חיצוניים מספקים ומתחזקים קובצי אימג' ציבוריים של מערכות הפעלה. כברירת מחדל, בכל הפרויקטים ב- Google Cloud אפשר ליצור מכונות Bare Metal באמצעות קובצי אימג' ציבוריים נתמכים של מערכת ההפעלה. עם זאת, אם בפרויקט ב- Google Cloud יש רשימה מוגדרת של תמונות מהימנות, תוכלו להשתמש רק בתמונות שברשימה הזו כדי ליצור מכונה פיזית ללא מערכת הפעלה.

המסוף

  1. נכנסים לדף Create an instance במסוף Google Cloud .

    כניסה לדף Create an instance

    אם מוצגת בקשה, בוחרים את הפרויקט ולוחצים על Continue. הדף Create an instance מופיע ובו החלונית Machine configuration.

  2. בחלונית Machine configuration:

    1. בשדה Name, מציינים שם למכונה. מידע נוסף זמין במאמר מוסכמות למתן שמות למשאבים.
    2. אופציונלי: בשדה Zone, בוחרים אזור למכונה הזו. אם תבחרו אזור שאין בו שרתי Bare Metal זמינים, תתבקשו לבחור אזור אחר.

      ברירת המחדל היא כל. אם לא תשנו את בחירת ברירת המחדל הזו, Google תבחר בשבילכם אזור באופן אוטומטי על סמך סוג המכונה והזמינות.

    3. בוחרים את המשפחה והסדרה של המכונה ללא מערכת הפעלה באחת מהדרכים הבאות:

      • לסדרות C4,‏ C4A,‏ C4D או C3 ללא מערכת הפעלה, בוחרים באפשרות General purpose כמשפחת המכונות, ואז בעמודה Series בוחרים באפשרות C4,‏ C4A,‏ C4D או C3.
      • בסדרת X4 bare metal, בוחרים באפשרות Memory optimized בתור משפחת המכונות, ואז בעמודה Series בוחרים באפשרות X4.
      • בסדרות Z3,‏ Z4D או Z4M של מכונות Bare Metal, בוחרים באפשרות Storage optimized כמשפחת המכונות, ואז בעמודה Series בוחרים באפשרות Z3,‏ Z4D או Z4M.
    4. בקטע Machine type, לוחצים על הרשימה. בתפריט הסינון, מקלידים metal ובוחרים אחד מסוגי המכונות הזמינים.

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

    1. לוחצים על Change. מופיע החלונית דיסק אתחול ומוצגת הכרטיסייה Public images.
    2. ברשימה Operating system בוחרים את סוג מערכת ההפעלה.
    3. ברשימה Version בוחרים את גרסת מערכת ההפעלה.
    4. ברשימה Boot disk type, בוחרים את סוג דיסק האתחול.
    5. בשדה Size (GB) מציינים את גודל דיסק האתחול.
    6. אופציונלי: בדיסקי אתחול מסוג Hyperdisk Balanced, מציינים ערכים בשדות Provisioned IOPS ו-Provisioned throughput.
    7. אופציונלי: כדי לראות אפשרויות הגדרה מתקדמות, מרחיבים את הקטע Show advanced configurations.
    8. כדי לאשר את האפשרויות של דיסק האתחול ולחזור לחלונית Operating system and storage, לוחצים על Select.

  4. בתפריט הניווט, לוחצים על Networking. בחלונית Networking שמופיעה:

    1. עוברים לקטע Firewall.
    2. כדי לאפשר תעבורת נתונים מסוג HTTP או HTTPS למכונה, בוחרים באפשרות Allow HTTP traffic או Allow HTTPS traffic.

      ‫Compute Engine מוסיף תג רשת למכונה ויוצר את הכלל התואם של חומת האש לתעבורת נתונים נכנסת, שמאפשר את כל תעבורת הנתונים הנכנסת ב-tcp:80 (HTTP) או ב-tcp:443 (HTTPS). תג הרשת משייך את כלל חומת האש למכונה. מידע נוסף זמין במאמר סקירה כללית של כללי חומת האש במסמכי התיעוד של Cloud Next Generation Firewall.

    3. בקטע Network performance configuration, מוודאים שהשדה כרטיס רשת מוגדר ל-IDPF.

  5. בתפריט הניווט, לוחצים על מתקדם. בחלונית Advanced שמופיעה:

    1. מרחיבים את הקטע VM provisioning model advanced settings. מוודאים שהשדה On host maintenance מוגדר לערך Terminate instance.
  6. זה שינוי אופציונלי. מציינים את שאר הפרמטרים של ההגדרות שרוצים. מידע נוסף על אפשרויות הגדרה בהתאמה אישית זמין במאמר יצירה והפעלה של מכונה.

  7. כדי ליצור את המכונה ללא מערכת הפעלה ולהפעיל אותה, לוחצים על Create.

gcloud

  1. בוחרים תמונה ציבורית שתומכת במכונות ללא מערכת הפעלה. רושמים את השם של קובץ האימג' או של משפחת קובצי האימג' ואת שם הפרויקט שמכיל את קובץ האימג'.
  2. משתמשים בפקודה gcloud compute instances create כדי ליצור מכונה ללא מערכת הפעלה ממשפחת קובצי אימג' או מגרסה ספציפית של קובץ אימג' של מערכת הפעלה.

    gcloud compute instances create INSTANCE_NAME \
        --zone=ZONE \
        --machine-type=MACHINE_TYPE \
        --network-interface=nic-type=IDPF \
        --maintenance-policy=TERMINATE \
        --create-disk=boot=yes,type=hyperdisk-balanced,image=projects/IMAGE_PROJECT/global/images/IMAGE,provisioned-iops=IOPS,provisioned-throughput=THROUGHPUT,size=SIZE \
        --no-shielded-secure-boot
    

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

    • ‫INSTANCE_NAME: שם למכונה החדשה בשרת פיזי
    • ‫ZONE: האזור שבו יוצרים את המכונה ללא מערכת הפעלה
    • ‫MACHINE_TYPE: סוג מכונת ה-Bare Metal שרוצים להשתמש בה למכונה. השם של סוג המכונה חייב להסתיים ב--metal.

      כדי לקבל רשימה של סוגי המכונות שזמינים באזור מסוים, משתמשים בפקודה gcloud compute machine-types list עם הדגל --zones.

    • ‫IMAGE_PROJECT: פרויקט התמונה שמכיל את התמונה

    • ‫IMAGE: מציינים אחת מהאפשרויות הבאות:

      • גרסה ספציפית של קובץ האימג' של מערכת ההפעלה, לדוגמה sles-15-sp4-sap-v20240208-x86-6.
      • משפחת תמונות, בפורמט family/IMAGE_FAMILY. כך המכונה נוצרת מקובץ אימג' של מערכת ההפעלה העדכני ביותר, שלא הוצא משימוש. לדוגמה, אם מציינים את הערך family/sles-15-sp4-sap, המערכת של Compute Engine יוצרת מכונה פיזית מהגרסה העדכנית של קובץ האימג' של מערכת ההפעלה במשפחת קובצי האימג' של SUSE Linux Enterprise Server 15 SP4. למידע נוסף על השימוש במשפחות של קובצי אימג', ראו שיטות מומלצות למשפחות של קובצי אימג'.
    • ‫IOPS: אופציונלי: המספר הגבוה ביותר של פעולות קלט/פלט לשנייה (IOPS) שהדיסק יכול לטפל בהן.

    • ‫THROUGHPUT: אופציונלי: מספר שלם שמייצג את התפוקה המקסימלית, ב-MiB לשנייה, שהדיסק יכול לטפל בה.

    • ‫SIZE: אופציונלי: הגודל של הדיסק החדש. הערך חייב להיות מספר שלם. יחידת המידה שמוגדרת כברירת מחדל היא GiB.

  3. מוודאים ש-Compute Engine יצר את המכונה:

    gcloud compute instances describe INSTANCE_NAME
    

    מחליפים את INSTANCE_NAME בשם של המכונה החדשה.

REST

  1. בוחרים תמונה ציבורית שתומכת במכונות ללא מערכת הפעלה. רושמים את השם של קובץ האימג' או של משפחת קובצי האימג' ואת שם הפרויקט שמכיל את קובץ האימג'.
  2. כדי ליצור מכונה פיזית ממשפחת קובצי אימג' או מגרסה ספציפית של קובץ אימג' של מערכת הפעלה, משתמשים בשיטה instances.insert:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
    {
     "machineType": "projects/PROJECT_ID/zones/MACHINE_TYPE_ZONE/machineTypes/MACHINE_TYPE",
     "name": "INSTANCE_NAME",
     "disks": [
       {
         "boot": true,
         "initializeParams": {
           "diskSizeGb": "DISK_SIZE",
           "diskType": "hyperdisk-balanced",
           "provisionedIops": "IOPS_LIMIT",
           "provisionedThroughput": "THROUGHPUT_LIMIT",
           "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
         }
       }
     ],
     "networkInterfaces": [
       {
         "nicType": "IDPF"
       }
     ],
     "scheduling": {
       "onHostMaintenance": "TERMINATE"
     }
    }
    

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

    • ‫PROJECT_ID: מזהה הפרויקט שבו רוצים ליצור את המכונה Bare Metal
    • ‫ZONE: האזור שבו יוצרים את המכונה ללא מערכת הפעלה
    • ‫MACHINE_TYPE_ZONE: האזור שבו נמצא סוג המכונה שרוצים להשתמש בו למכונה החדשה ללא מערכת הפעלה
    • ‫MACHINE_TYPE: סוג המכונה שבה משתמשים. השם של סוג המכונה חייב להסתיים ב--metal.
    • ‫INSTANCE_NAME: השם של המכונה החדשה
    • ‫DISK_SIZE: גודל הדיסק ב-GiB
    • ‫IOPS_LIMIT: מספר פעולות הקלט/פלט לשנייה שרוצים להקצות לדיסק.
    • ‫THROUGHPUT_LIMIT: מספר שלם שמייצג את קצב העברת הנתונים שרוצים להקצות לדיסק, ב-MB לשנייה.
    • ‫IMAGE_PROJECT: פרויקט התמונה שמכיל את התמונה
    • ‫IMAGE: מציינים אחת מהאפשרויות הבאות:
      • גרסה ספציפית של קובץ האימג' של מערכת ההפעלה, לדוגמה sles-15-sp4-sap-v20240208-x86-6.
      • משפחת תמונות, בפורמט family/IMAGE_FAMILY. כך המכונה נוצרת מקובץ אימג' של מערכת ההפעלה העדכני ביותר, שלא הוצא משימוש. לדוגמה, אם מציינים את הערך family/sles-15-sp4-sap, המערכת של Compute Engine יוצרת מכונה פיזית מהגרסה העדכנית של קובץ האימג' של מערכת ההפעלה במשפחת קובצי האימג' של SUSE Linux Enterprise Server 15 SP4. למידע נוסף על השימוש במשפחות של קובצי אימג', ראו שיטות מומלצות למשפחות של קובצי אימג'.

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