创建 Feed

创建资产 Feed。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Go

如需了解如何安装和使用 Cloud Asset Inventory 客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// Sample create-feed create feed.
package main

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

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

// Command-line flags.
var (
	feedID = flag.String("feed_id", "YOUR_FEED_ID", "Identifier of Feed.")
)

func main() {
	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	feedParent := fmt.Sprintf("projects/%s", projectID)
	assetNames := []string{"YOUR_ASSET_NAME"}
	topic := fmt.Sprintf("projects/%s/topics/%s", projectID, "YOUR_TOPIC_NAME")

	req := &assetpb.CreateFeedRequest{
		Parent: feedParent,
		FeedId: *feedID,
		Feed: &assetpb.Feed{
			AssetNames: assetNames,
			FeedOutputConfig: &assetpb.FeedOutputConfig{
				Destination: &assetpb.FeedOutputConfig_PubsubDestination{
					PubsubDestination: &assetpb.PubsubDestination{
						Topic: topic,
					},
				},
			},
		}}
	response, err := client.CreateFeed(ctx, req)
	if err != nil {
		log.Fatalf("client.CreateFeed: %v", err)
	}
	fmt.Print(response)
}

Java

如需了解如何安装和使用 Cloud Asset Inventory 客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.ContentType;
import com.google.cloud.asset.v1.CreateFeedRequest;
import com.google.cloud.asset.v1.Feed;
import com.google.cloud.asset.v1.FeedOutputConfig;
import com.google.cloud.asset.v1.ProjectName;
import com.google.cloud.asset.v1.PubsubDestination;
import java.io.IOException;
import java.util.Arrays;

public class CreateFeedExample {
  // Create a feed
  public static void createFeed(
      String[] assetNames, String feedId, String topic, String projectId, ContentType contentType)
      throws IOException, IllegalArgumentException {
    // String[] assetNames = {"MY_ASSET_NAME"}
    // ContentType contentType = contentType
    // String FeedId = "MY_FEED_ID"
    // String topic = "projects/[PROJECT_ID]/topics/[TOPIC_NAME]"
    // String projectID = "MY_PROJECT_ID"
    Feed feed =
        Feed.newBuilder()
            .addAllAssetNames(Arrays.asList(assetNames))
            .setContentType(contentType)
            .setFeedOutputConfig(
                FeedOutputConfig.newBuilder()
                    .setPubsubDestination(PubsubDestination.newBuilder().setTopic(topic).build())
                    .build())
            .build();
    CreateFeedRequest request =
        CreateFeedRequest.newBuilder()
            .setParent(String.format(ProjectName.of(projectId).toString()))
            .setFeedId(feedId)
            .setFeed(feed)
            .build();
    // 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 "close" method on the client to safely clean up any remaining background resources.
    try (AssetServiceClient client = AssetServiceClient.create()) {
      Feed response = client.createFeed(request);
      System.out.println("Feed created successfully: " + response.getName());
    } catch (IOException | IllegalArgumentException e) {
      System.out.println("Error during CreateFeed: \n" + e.toString());
    }
  }
}

Node.js

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const feedId = 'my feed';
// const assetNames = '//storage.googleapis.com/<BUCKET_NAME1>,//storage.googleapis.com/<BUCKET_NAME2>';
// const topicName = 'projects/<PROJECT_ID>/topics/<TOPIC_ID>'
// const contentType = 'RESOURCE';

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

const client = new AssetServiceClient();

async function createFeed() {
  const projectId = await client.getProjectId();
  // TODO(developer): Choose asset names, such as //storage.googleapis.com/[YOUR_BUCKET_NAME].
  // const assetNames = ['ASSET_NAME1', 'ASSET_NAME2', ...];

  const request = {
    parent: `projects/${projectId}`,
    feedId: feedId,
    feed: {
      assetNames: assetNames.split(','),
      contentType: contentType,
      feedOutputConfig: {
        pubsubDestination: {
          topic: topicName,
        },
      },
    },
  };

  // Handle the operation using the promise pattern.
  const result = await client.createFeed(request);
  // Do things with with the response.
  console.log(util.inspect(result, {depth: null}));

Python

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'
# TODO feed_id = 'Feed ID you want to create'
# TODO asset_names = 'List of asset names the feed listen to'
# TODO topic = "Topic name of the feed"
# TODO content_type ="Content type of the feed"

client = asset_v1.AssetServiceClient()
parent = f"projects/{project_id}"
feed = asset_v1.Feed()
feed.asset_names.extend(asset_names)
feed.feed_output_config.pubsub_destination.topic = topic
feed.content_type = content_type
response = client.create_feed(
    request={"parent": parent, "feed_id": feed_id, "feed": feed}
)
print(f"feed: {response}")

Ruby

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/asset"

# project_id = 'YOUR_PROJECT_ID'
# feed_id = 'NAME_OF_FEED'
# pubsub_topic = 'YOUR_PUBSUB_TOPIC'
# asset names, e.g.: //storage.googleapis.com/[YOUR_BUCKET_NAME]
# asset_names = [ASSET_NAMES, COMMMA_DELIMTTED]
asset_service = Google::Cloud::Asset.asset_service

formatted_parent = asset_service.project_path project: project_id

feed = {
  asset_names:        asset_names,
  feed_output_config: {
    pubsub_destination: {
      topic: pubsub_topic
    }
  }
}
response = asset_service.create_feed(
  parent:  formatted_parent,
  feed_id: feed_id,
  feed:    feed
)
puts "Created feed: #{response.name}"

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器