הצגת רשימת נכסים

אתם יכולים להציג את הנכסים בפרויקטים, בתיקיות או בארגונים ב- Google Cloud .

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

  1. מפעילים את Cloud Asset Inventory API בפרויקט שממנו מריצים את הפקודות של מאגר משאבי ענן.

    הפעלת Cloud Asset Inventory API

  2. מוודאים שלחשבון שלכם יש את התפקיד המתאים כדי להפעיל את Cloud Asset Inventory API. בקטע הרשאות מפורטות ההרשאות הספציפיות לכל סוג קריאה.

מגבלות

  • כשמציגים את נתוני הטבלה ב-BigQuery, לא כל השדות נתמכים.

  • שדות של נכסים שמשתנים לעיתים קרובות במטא-נתונים של BigQuery, כמו numBytes,‏ numLongTermBytes,‏ numPhysicalBytes ו-numRows, מקבלים ערכי null.

רשימת הנכסים

המסוף

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

כדי להציג רשימה של המטא-נתונים של המשאבים בפרויקט, בתיקייה או בארגון:

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

    מעבר למלאי הנכסים

  2. עוברים לפרויקט, לתיקייה או לארגון שבהם רוצים להציג את רשימת המשאבים.
  3. לוחצים על הכרטיסייה משאב.
  4. בחלונית Filter results, בוחרים את סוגי המשאבים, הפרויקטים או המיקומים שלפיהם רוצים לסנן את התוצאות.
  5. כדי לראות את המטא-נתונים של משאב, לוחצים על השם המוצג של המשאב בחלונית התוצאות.

gcloud

gcloud asset list \
    --SCOPE \
    --asset-types=ASSET_TYPE_1,ASSET_TYPE_2,... \
    --content-type=CONTENT_TYPE \
    --snapshot-time="SNAPSHOT_TIME"

מספקים את הערכים הבאים:

  • ‫SCOPE: משתמשים באחד מהערכים הבאים:

    • ‫project=PROJECT_ID, כאשר PROJECT_ID הוא מזהה הפרויקט שכולל את הנכס שרוצים לאחזר.
    • ‫folder=FOLDER_ID, כאשר FOLDER_ID הוא המזהה של התיקייה שמכילה את הנכס שרוצים לאחזר.

      איך מוצאים את המזהה של תיקיית Google Cloud

      מסוףGoogle Cloud

      כדי למצוא את המזהה של תיקיית Google Cloud :

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

        כניסה למסוף Google Cloud

      2. לוחצים על תיבת הרשימה switcher בסרגל התפריטים.
      3. בוחרים את הארגון שלכם בתיבת הרשימה.
      4. מחפשים את שם התיקייה. מזהה התיקייה מוצג לצד שם התיקייה.

      ‫CLI של gcloud

      כדי לאחזר את המזהה של תיקייה ברמת הארגון, מריצים את הפקודה הבאה: Google Cloud

      gcloud resource-manager folders list \
          --organization=$(gcloud organizations describe ORGANIZATION_NAME \
            --format="value(name.segment(1))") \
          --filter='"DISPLAY_NAME":"TOP_LEVEL_FOLDER_NAME"' \
          --format="value(ID)"

      כאשר TOP_LEVEL_FOLDER_NAME הוא התאמה חלקית או מלאה של מחרוזת לשם התיקייה. מסירים את הדגל --format כדי לראות מידע נוסף על התיקיות שנמצאו.

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

      gcloud resource-manager folders list --folder=FOLDER_ID
    • ‫organization=ORGANIZATION_ID, כאשר ORGANIZATION_ID הוא המזהה של הארגון שבו נמצא הנכס שרוצים לאחזר.

      איך מוצאים את המזהה של ארגון ב- Google Cloud

      מסוףGoogle Cloud

      כדי למצוא את המזהה של ארגון ב- Google Cloud :

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

        כניסה למסוף Google Cloud

      2. לוחצים על תיבת הרשימה switcher בסרגל התפריטים.
      3. בוחרים את הארגון שלכם בתיבת הרשימה.
      4. לוחצים על הכרטיסייה הכול. מזהה הארגון מופיע לצד שם הארגון.

      ‫CLI של gcloud

      כדי לאחזר את המזהה של ארגון ב- Google Cloud , משתמשים בפקודה הבאה:

      gcloud organizations describe ORGANIZATION_NAME --format="value(name.segment(1))"
  • ‫ASSET_TYPE_#: אופציונלי. רשימה מופרדת בפסיקים של סוגי נכסים שניתן לחפש. יש תמיכה בביטויים רגולריים שתואמים ל-RE2. אם הביטוי הרגולרי לא תואם לאף סוג נכס נתמך, תוחזר שגיאת INVALID_ARGUMENT. אם לא מציינים את --asset-types, מוחזרים כל סוגי הנכסים.
  • ‫CONTENT_TYPE: אופציונלי. סוג התוכן של המטא-נתונים שרוצים לאחזר. אם לא מציינים את --content-type, מוחזר רק מידע בסיסי, כמו שמות הנכסים, מתי הם עודכנו לאחרונה ולאילו פרויקטים, תיקיות וארגונים הם שייכים.
  • ‫SNAPSHOT_TIME: אופציונלי. השעה שבה רוצים ליצור תמונת מצב של הנכסים, בפורמט datetime של נושא gcloud. הערך צריך להיות עד 35 ימים בעבר. אם לא מציינים את --snapshot-time, המערכת יוצרת תמונת מצב של הזמן הנוכחי.

כל האפשרויות מפורטות במדריך העזר ל-CLI של gcloud.

דוגמה

הפקודה הבאה מקבלת תמונת מצב של מטא-נתונים בפורמט resource של מכונות Compute Engine נכון ל-30 בינואר 2024 (2024-01-30) בפרויקט my-project.

לפני שמריצים את הפקודה, צריך לוודא שזמן קובץ ה-snapshot הוא ב-35 הימים האחרונים, ולשנות את שם הפרויקט.

gcloud asset list \
    --project=my-project \
    --asset-types=compute.googleapis.com/Instance \
    --content-type=resource \
    --snapshot-time="2024-01-30"

דוגמה לתשובה

---
ancestors:
- projects/000000000000
- folders/000000000000
- organizations/000000000000
assetType: compute.googleapis.com/Instance
name: //compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/instance-name
resource:
  data:
    ASSET_METADATA
updateTime: '2024-01-30T00:00:00.000000Z'

REST

ה-method של ה-HTTP וכתובת ה-URL:

POST https://cloudasset.googleapis.com/v1/SCOPE_PATH/assets

תוכן בקשת JSON:

{
  "assetTypes": [
    "ASSET_TYPE_1",
    "ASSET_TYPE_2",
    "..."
  ],
  "contentType": "CONTENT_TYPE",
  "readTime": "SNAPSHOT_TIME",
  "pageSize": "PAGE_SIZE",
  "pageToken": "PAGE_TOKEN"
}

מספקים את הערכים הבאים:

  • ‫SCOPE_PATH: משתמשים באחד מהערכים הבאים:

    • ‫projects/PROJECT_ID, כאשר PROJECT_ID הוא מזהה הפרויקט שכולל את הנכס שרוצים לאחזר.
    • ‫projects/PROJECT_NUMBER, כאשר PROJECT_NUMBER הוא מספר הפרויקט שבו נמצא הנכס שרוצים לאחזר.

      איך מוצאים את Google Cloud מספר הפרויקט

      מסוףGoogle Cloud

      כדי למצוא את מספר הפרויקט ב- Google Cloud :

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

        לדף Welcome

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

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

      ‫CLI של gcloud

      כדי לאחזר את מספר הפרויקט, משתמשים בפקודה הבאה: Google Cloud

      gcloud projects describe PROJECT_ID --format="value(projectNumber)"
    • ‫folders/FOLDER_ID, כאשר FOLDER_ID הוא המזהה של התיקייה שמכילה את הנכס שרוצים לאחזר.

      איך מוצאים את המזהה של תיקיית Google Cloud

      מסוףGoogle Cloud

      כדי למצוא את המזהה של תיקיית Google Cloud :

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

        כניסה למסוף Google Cloud

      2. לוחצים על תיבת הרשימה switcher בסרגל התפריטים.
      3. בוחרים את הארגון שלכם בתיבת הרשימה.
      4. מחפשים את שם התיקייה. מזהה התיקייה מוצג לצד שם התיקייה.

      ‫CLI של gcloud

      כדי לאחזר את המזהה של תיקייה ברמת הארגון, מריצים את הפקודה הבאה: Google Cloud

      gcloud resource-manager folders list \
          --organization=$(gcloud organizations describe ORGANIZATION_NAME \
            --format="value(name.segment(1))") \
          --filter='"DISPLAY_NAME":"TOP_LEVEL_FOLDER_NAME"' \
          --format="value(ID)"

      כאשר TOP_LEVEL_FOLDER_NAME הוא התאמה חלקית או מלאה של מחרוזת לשם התיקייה. מסירים את הדגל --format כדי לראות מידע נוסף על התיקיות שנמצאו.

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

      gcloud resource-manager folders list --folder=FOLDER_ID
    • ‫organizations/ORGANIZATION_ID, כאשר ORGANIZATION_ID הוא המזהה של הארגון שבו נמצא הנכס שרוצים לאחזר.

      איך מוצאים את המזהה של ארגון ב- Google Cloud

      מסוףGoogle Cloud

      כדי למצוא את המזהה של ארגון ב- Google Cloud :

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

        כניסה למסוף Google Cloud

      2. לוחצים על תיבת הרשימה switcher בסרגל התפריטים.
      3. בוחרים את הארגון שלכם בתיבת הרשימה.
      4. לוחצים על הכרטיסייה הכול. מזהה הארגון מופיע לצד שם הארגון.

      ‫CLI של gcloud

      כדי לאחזר את המזהה של ארגון ב- Google Cloud , משתמשים בפקודה הבאה:

      gcloud organizations describe ORGANIZATION_NAME --format="value(name.segment(1))"
  • ‫ASSET_TYPE_#: אופציונלי. מערך של סוגי נכסים שניתן לחפש. יש תמיכה בביטויים רגולריים שתואמים ל-RE2. אם הביטוי הרגולרי לא תואם לאף סוג נכס נתמך, תוחזר שגיאת INVALID_ARGUMENT. אם לא מציינים את assetTypes, מוחזרים כל סוגי הנכסים.
  • ‫CONTENT_TYPE: אופציונלי. סוג התוכן של המטא-נתונים שרוצים לאחזר. אם לא מציינים את contentType, מוחזר רק מידע בסיסי, כמו שמות הנכסים, הפעם האחרונה שבה הנכסים עודכנו, והפרויקטים, התיקיות והארגונים שאליהם הם שייכים.
  • ‫SNAPSHOT_TIME: אופציונלי. השעה שבה רוצים ליצור תמונת מצב של הנכסים, בפורמט RFC 3339. הערך צריך להיות עד 35 ימים בעבר. אם לא מציינים את readTime, המערכת יוצרת תמונת מצב בזמן הנוכחי.
  • ‫PAGE_SIZE: אופציונלי. מספר התוצאות שיוצגו בכל דף. המספר המקסימלי הוא 500. אם הערך מוגדר כ-0 או כערך שלילי, נבחרת ברירת מחדל מתאימה. מוחזר nextPageToken כדי לאחזר את התוצאות הבאות.

  • ‫PAGE_TOKEN: אופציונלי. תשובות ארוכות לבקשות מחולקות לכמה דפים. אם לא מציינים את pageToken, מוצג הדף הראשון. כדי לקרוא לדפים הבאים, אפשר להשתמש ב-nextPageToken של התגובה הקודמת בתור הערך של pageToken.

כל האפשרויות מפורטות במאמר העזרה בנושא REST.

דוגמאות לפקודות

הפקודות הבאות מאחזרות תמונת מצב של המטא-נתונים של resource במכונות Compute Engine נכון ל-30 בינואר 2024 (2024-01-30T00:00:00Z) בפרויקט my-project.

לפני שמריצים את הפקודות האלה, חשוב לוודא שזמן קובץ ה-snapshot הוא ב-35 הימים האחרונים, ולשנות את שם הפרויקט.

‏Curl (Linux,‏ macOS או Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": ["compute.googleapis.com/Instance"],
            "contentType": "RESOURCE",
            "readTime": "2024-01-30T00:00:00Z"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project/assets

‎PowerShell (Windows)

$cred = gcloud auth print-access-token

$headers = @{ 
  "X-HTTP-Method-Override" = "GET";
  "Authorization" = "Bearer $cred"
}


$body = @"
{
  "assetTypes": ["compute.googleapis.com/Instance"],
  "contentType": "RESOURCE",
  "readTime": "2024-01-30T00:00:00Z"
}
"@

Invoke-WebRequest `
  -Method POST `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body $body `
  -Uri "https://cloudasset.googleapis.com/v1/projects/my-project/assets" | Select-Object -Expand Content

דוגמה לתשובה

{
  "readTime": "2024-01-30T00:00:00Z",
  "assets": [
    {
      "name": "//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/instance-name",
      "assetType": "compute.googleapis.com/Instance",
      "resource": {
        "version": "v1",
        "discoveryDocumentUri": "https://www.googleapis.com/discovery/v1/apis/compute/v1/rest?version=v1",
        "discoveryName": "Instance",
        "parent": "//cloudresourcemanager.googleapis.com/projects/000000000000",
        "data": {
          ASSET_METADATA
        },
        "location": "us-central1-a"
      },
      "ancestors": [
        "projects/000000000000",
        "folders/000000000000",
        "organizations/000000000000"
      ],
    "updateTime": "2024-01-30T00:00:00.000000Z"
    }
  ]
}

C#‎

מידע על התקנת ספריית הלקוח של מאגר משאבי ענן והשימוש בה מופיע במאמר ספריות הלקוח של מאגר משאבי ענן.

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


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Asset.V1;

public class ListAssetsSample
{
    public  PagedEnumerable<ListAssetsResponse, Asset> ListAssets(string projectId)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        ListAssetsRequest request = new ListAssetsRequest
        {
            ParentAsResourceName = ProjectName.FromProject(projectId),
            ContentType = ContentType.Resource,
        };

        // Call the API.
         PagedEnumerable<ListAssetsResponse, Asset> response = client.ListAssets(request);

        // Return the result.
        return response;
    }
}

המשך

מידע על התקנת ספריית הלקוח של מאגר משאבי ענן והשימוש בה מופיע במאמר ספריות הלקוח של מאגר משאבי ענן.

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


// Sample list-assets list assets.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"google.golang.org/api/iterator"

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
)

func main() {
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	assetType := "storage.googleapis.com/Bucket"
	req := &assetpb.ListAssetsRequest{
		Parent:      fmt.Sprintf("projects/%s", projectID),
		AssetTypes:  []string{assetType},
		ContentType: assetpb.ContentType_RESOURCE,
	}

	// Call ListAssets API to get an asset iterator.
	it := client.ListAssets(ctx, req)

	// Traverse and print the first 10 listed assets in response.
	for i := 0; i < 10; i++ {
		response, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(response)
	}
}

Java

מידע על התקנת ספריית הלקוח של מאגר משאבי ענן והשימוש בה מופיע במאמר ספריות הלקוח של מאגר משאבי ענן.

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

// Imports the Google Cloud client library

public class ListAssetsExample {

  public static void listAssets() throws IOException, IllegalArgumentException {
    // The project id of the asset parent to list.
    String projectId = "YOUR_PROJECT_ID";
    // The asset types to list. E.g.,
    // ["storage.googleapis.com/Bucket", "bigquery.googleapis.com/Table"].
    // See full list of supported asset types at
    // https://cloud.google.com/asset-inventory/docs/supported-asset-types.
    String[] assetTypes = {"YOUR_ASSET_TYPES_TO_LIST"};
    // The asset content type to list. E.g., ContentType.CONTENT_TYPE_UNSPECIFIED.
    // See full list of content types at
    // https://cloud.google.com/asset-inventory/docs/reference/rpc/google.cloud.asset.v1#contenttype
    ContentType contentType = ContentType.CONTENT_TYPE_UNSPECIFIED;
    listAssets(projectId, assetTypes, contentType);
  }

  public static void listAssets(String projectId, String[] assetTypes, ContentType contentType)
      throws IOException, IllegalArgumentException {
    try (AssetServiceClient client = AssetServiceClient.create()) {
      ProjectName parent = ProjectName.of(projectId);

      // Build initial ListAssetsRequest without setting page token.
      ListAssetsRequest request =
          ListAssetsRequest.newBuilder()
              .setParent(parent.toString())
              .addAllAssetTypes(Arrays.asList(assetTypes))
              .setContentType(contentType)
              .build();

      // Repeatedly call ListAssets until page token is empty.
      ListAssetsPagedResponse response = client.listAssets(request);
      System.out.println(response);
      while (!response.getNextPageToken().isEmpty()) {
        request = request.toBuilder().setPageToken(response.getNextPageToken()).build();
        response = client.listAssets(request);
        System.out.println(response);
      }
    }
  }
}

Node.js

מידע על התקנת ספריית הלקוח של מאגר משאבי ענן והשימוש בה מופיע במאמר ספריות הלקוח של מאגר משאבי ענן.

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const assetTypes = 'storage.googleapis.com/Bucket,bigquery.googleapis.com/Table';
// const contentType = 'RESOURCE';

const util = require('util');
const {v1} = require('@google-cloud/asset');
const client = new v1.AssetServiceClient();

const projectId = await client.getProjectId();
const projectResource = `projects/${projectId}`;
// TODO(developer): Choose types of assets to list, such as 'storage.googleapis.com/Bucket':
//   const assetTypes = 'storage.googleapis.com/Bucket,bigquery.googleapis.com/Table';
// Or simply use empty string to list all types of assets:
//   const assetTypes = '';
const assetTypesList = assetTypes ? assetTypes.split(',') : [];

async function listAssets() {
  const request = {
    parent: projectResource,
    assetTypes: assetTypesList,
    contentType: contentType,
    // (Optional) Add readTime parameter to list assets at the given time instead of current time:
    //   readTime: { seconds: 1593988758 },
  };

  // Call cloud.assets.v1.ListAssets API.
  const result = await client.listAssets(request);
  // Handle the response.
  console.log(util.inspect(result, {depth: null}));
}
listAssets();

PHP

מידע על התקנת ספריית הלקוח של מאגר משאבי ענן והשימוש בה מופיע במאמר ספריות הלקוח של מאגר משאבי ענן.

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

use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\ListAssetsRequest;

/**
 * @param string   $projectId  Tthe project Id for list assets.
 * @param string[] $assetTypes (Optional) Asset types to list for.
 * @param int      $pageSize   (Optional) Size of one result page.
 */
function list_assets(
    string $projectId,
    array $assetTypes = [],
    int $pageSize = null
): void {
    // Instantiate a client.
    $client = new AssetServiceClient();

    // Run request
    $request = (new ListAssetsRequest())
        ->setParent("projects/$projectId")
        ->setAssetTypes($assetTypes)
        ->setPageSize($pageSize);
    $response = $client->listAssets($request);

    // Print the asset names in the result
    foreach ($response->getPage() as $asset) {
        print($asset->getName() . PHP_EOL);
    }
}

Python

מידע על התקנת ספריית הלקוח של מאגר משאבי ענן והשימוש בה מופיע במאמר ספריות הלקוח של מאגר משאבי ענן.

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

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'
# TODO asset_types = 'Your asset type list, e.g.,
# ["storage.googleapis.com/Bucket","bigquery.googleapis.com/Table"]'
# TODO page_size = 'Num of assets in one page, which must be between 1 and
# 1000 (both inclusively)'
# TODO content_type ="Content type to list"

project_resource = f"projects/{project_id}"
client = asset_v1.AssetServiceClient()

# Call ListAssets v1 to list assets.
response = client.list_assets(
    request={
        "parent": project_resource,
        "read_time": None,
        "asset_types": asset_types,
        "content_type": content_type,
        "page_size": page_size,
    }
)

for asset in response:
    print(asset)

Ruby

מידע על התקנת ספריית הלקוח של מאגר משאבי ענן והשימוש בה מופיע במאמר ספריות הלקוח של מאגר משאבי ענן.

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

require "google/cloud/asset"

asset_service = Google::Cloud::Asset.asset_service
# project_id = 'YOUR_PROJECT_ID'
formatted_parent = asset_service.project_path project: project_id

content_type = :RESOURCE
response = asset_service.list_assets(
  parent:           formatted_parent,
  content_type:     content_type
)

# Do things with the result
response.page.each do |resource|
  puts resource
end