Aggiornare un feed

Aggiorna un feed di asset.

Esempio di codice

Go

Per scoprire come installare e utilizzare la libreria client per Cloud Asset Inventory, consulta Librerie client di Cloud Asset Inventory.

Per eseguire l'autenticazione su Cloud Asset Inventory, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.


// Sample update-feed update feed.
package main

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

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
	cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1"
	field_mask "google.golang.org/genproto/protobuf/field_mask"
)

// 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")
	cloudresourcemanagerClient, err := cloudresourcemanager.NewService(ctx)
	if err != nil {
		log.Fatalf("cloudresourcemanager.NewService: %v", err)
	}

	project, err := cloudresourcemanagerClient.Projects.Get(projectID).Do()
	if err != nil {
		log.Fatalf("cloudresourcemanagerClient.Projects.Get.Do: %v", err)
	}
	projectNumber := strconv.FormatInt(project.ProjectNumber, 10)
	feedName := fmt.Sprintf("projects/%s/feeds/%s", projectNumber, *feedID)
	topic := fmt.Sprintf("projects/%s/topics/%s", projectID, "TOPIC_TO_UPDATE")

	req := &assetpb.UpdateFeedRequest{
		Feed: &assetpb.Feed{
			Name: feedName,
			FeedOutputConfig: &assetpb.FeedOutputConfig{
				Destination: &assetpb.FeedOutputConfig_PubsubDestination{
					PubsubDestination: &assetpb.PubsubDestination{
						Topic: topic,
					},
				},
			},
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"feed_output_config.pubsub_destination.topic"},
		},
	}
	response, err := client.UpdateFeed(ctx, req)
	if err != nil {
		log.Fatalf("client.UpdateFeed: %v", err)
	}
	fmt.Print(response)
}

Java

Per scoprire come installare e utilizzare la libreria client per Cloud Asset Inventory, consulta Librerie client di Cloud Asset Inventory.

Per autenticarti a Cloud Asset Inventory, configura le credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.Feed;
import com.google.cloud.asset.v1.FeedOutputConfig;
import com.google.cloud.asset.v1.PubsubDestination;
import com.google.cloud.asset.v1.UpdateFeedRequest;
import com.google.protobuf.FieldMask;

public class UpdateFeedExample {

  // Update a feed
  public static void updateFeed(String feedName, String topic) throws Exception {
    // String feedName = "MY_FEED_NAME"
    // String topic = "projects/[PROJECT_ID]/topics/[TOPIC_NAME]"
    Feed feed =
        Feed.newBuilder()
            .setName(feedName)
            .setFeedOutputConfig(
                FeedOutputConfig.newBuilder()
                    .setPubsubDestination(PubsubDestination.newBuilder().setTopic(topic).build())
                    .build())
            .build();
    UpdateFeedRequest request =
        UpdateFeedRequest.newBuilder()
            .setFeed(feed)
            .setUpdateMask(
                FieldMask.newBuilder()
                    .addPaths("feed_output_config.pubsub_destination.topic")
                    .build())
            .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.updateFeed(request);
      System.out.println("Feed updated successfully: " + response.getName());
    } catch (Exception e) {
      System.out.println("Error during UpdateFeed: \n" + e.toString());
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per Cloud Asset Inventory, consulta Librerie client di Cloud Asset Inventory.

Per eseguire l'autenticazione su Cloud Asset Inventory, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

const client = new AssetServiceClient();
// example inputs:
// const fullQueryName = 'folders/<FOLDER_NUMBER>/savedQueries/<QUERY_ID>';
// const description = 'a new description';
async function updateSavedQuery() {
  const request = {
    savedQuery: {
      name: fullQueryName,
      description: description,
    },
    updateMask: {
      paths: ['description'],
    },
  };

  // Handle the operation using the promise pattern.
  const [query] = await client.updateSavedQuery(request);
  // Do things with with the response.
  console.log('Query name:', query.name);
  console.log('Query description:', query.description);
  console.log('Created time:', query.createTime);
  console.log('Updated time:', query.lastUpdateTime);
  console.log('Query type:', query.content.queryContent);
  console.log('Query content:', JSON.stringify(query.content, null, 4));

Python

Per scoprire come installare e utilizzare la libreria client per Cloud Asset Inventory, consulta Librerie client di Cloud Asset Inventory.

Per eseguire l'autenticazione su Cloud Asset Inventory, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

from google.cloud import asset_v1
from google.protobuf import field_mask_pb2

# TODO feed_name = 'Feed Name you want to update'
# TODO topic = "Topic name you want to update with"

client = asset_v1.AssetServiceClient()
feed = asset_v1.Feed()
feed.name = feed_name
feed.feed_output_config.pubsub_destination.topic = topic
update_mask = field_mask_pb2.FieldMask()
# In this example, we update topic of the feed
update_mask.paths.append("feed_output_config.pubsub_destination.topic")
response = client.update_feed(request={"feed": feed, "update_mask": update_mask})
print(f"updated_feed: {response}")

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta Browser di esempio Google Cloud.