Crear un feed

Crea un feed de recursos.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

Go

Para autenticarte en Cloud Asset Inventory, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


// 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

Para autenticarte en Cloud Asset Inventory, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Cloud Asset Inventory, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * 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

Para autenticarte en Cloud Asset Inventory, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Cloud Asset Inventory, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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}"

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.