Container Analysis client libraries

This page shows how to get started with the Cloud Client Libraries for the Container Analysis API. Client libraries make it easier to access Google Cloud APIs from a supported language. Although you can use Google Cloud APIs directly by making raw requests to the server, client libraries provide simplifications that significantly reduce the amount of code you need to write.

Read more about the Cloud Client Libraries and the older Google API Client Libraries in Client libraries explained.

Install the client library

C++

See Setting up a C++ development environment for details about this client library's requirements and install dependencies.

Go

go get cloud.google.com/go/containeranalysis/apiv1

For more information, see Setting Up a Go Development Environment.

Java



If you are using Maven with a BOM, add the following to your pom.xml file:

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>26.70.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
 </dependencies>
</dependencyManagement>
<dependencies>
 <dependency>
 <groupId>com.google.cloud</groupId>
<artifactId>google-cloud-containeranalysis</artifactId>
</dependency>
</dependencies>

If you are using Maven without a BOM, add this to your dependencies:

<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-containeranalysis</artifactId>
<version>2.78.0</version>
</dependency>

If you are using Gradle, add the following to your dependencies:

implementation'com.google.cloud:google-cloud-containeranalysis:2.78.0'

If you are using sbt, add the following to your dependencies:

libraryDependencies+="com.google.cloud"%"google-cloud-containeranalysis"%"2.78.0"

If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

For more information, see Setting Up a Java Development Environment.

Node.js


npm install @google-cloud/containeranalysis

For more information, see Setting Up a Node.js Development Environment.

Python


It is recommended to install this library in a virtualenv using pip. Virtualenv allows you to install the Python libraries in an isolated environment, preventing conflicts with the system dependencies.

  • Mac and Linux

    pipinstallvirtualenv
    virtualenv<your-env>
    source<your-env>/bin/activate
    <your-env>/bin/pipinstallgoogle-cloud-containeranalysis
    
  • Windows

    pipinstallvirtualenv
    virtualenv<your-env>
    <your-env>\Scripts\activate
    <your-env>\Scripts\pip.exeinstallgoogle-cloud-containeranalysis
    

    For more information, see Setting Up a Python Development Environment.

Ruby

gem install google-cloud-container_analysis

For more information, see Setting Up a Ruby Development Environment.

Set up authentication

To authenticate calls to Google Cloud APIs, client libraries support Application Default Credentials (ADC); the libraries look for credentials in a set of defined locations and use those credentials to authenticate requests to the API. With ADC, you can make credentials available to your application in a variety of environments, such as local development or production, without needing to modify your application code.

For production environments, the way you set up ADC depends on the service and context. For more information, see Set up Application Default Credentials.

For a local development environment, you can set up ADC with the credentials that are associated with your Google Account:

  1. Install the Google Cloud CLI. After installation, initialize the Google Cloud CLI by running the following command:

    gcloudinit

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloudauthapplication-defaultlogin

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    A sign-in screen appears. After you sign in, your credentials are stored in the local credential file used by ADC.

Use the client library

The following example shows how to use the client library.

C++


#include"google/cloud/containeranalysis/v1/grafeas_client.h"
#include"google/cloud/project.h"
#include <iostream>
intmain(intargc,char*argv[])try{
if(argc!=2){
std::cerr << "Usage: " << argv[0] << " project-id\n";
return1;
}
namespacecontaineranalysis=::google::cloud::containeranalysis_v1;
autoclient=containeranalysis::GrafeasClient(
containeranalysis::MakeGrafeasConnection());
autoconstproject=google::cloud::Project(argv[1]);
for(auton:client.ListNotes(project.FullName(),/*filter=*/"")){
if(!n)throwstd::move(n).status();
std::cout << n->DebugString() << "\n";
}
return0;
}catch(google::cloud::Statusconst&status){
std::cerr << "google::cloud::Status thrown: " << status << "\n";
return1;
}

Go


import(
"context"
"fmt"
containeranalysis"cloud.google.com/go/containeranalysis/apiv1"
grafeaspb"google.golang.org/genproto/googleapis/grafeas/v1"
)
// getOccurrence retrieves and prints a specified Occurrence from the server.
funcgetOccurrence(occurrenceID,projectIDstring)(*grafeaspb.Occurrence ,error){
// occurrenceID := path.Base(occurrence.Name)
ctx:=context.Background()
client,err:=containeranalysis.NewClient (ctx)
iferr!=nil{
returnnil,fmt.Errorf("NewClient: %w",err)
}
deferclient.Close ()
req:=&grafeaspb.GetOccurrenceRequest {
Name:fmt.Sprintf("projects/%s/occurrences/%s",projectID,occurrenceID),
}
occ,err:=client.GetGrafeasClient ().GetOccurrence(ctx,req)
iferr!=nil{
returnnil,fmt.Errorf("client.GetOccurrence: %w",err)
}
returnocc,nil
}

Java

importcom.google.cloud.devtools.containeranalysis.v1.ContainerAnalysisClient ;
importio.grafeas.v1.GrafeasClient ;
importio.grafeas.v1.Occurrence ;
importio.grafeas.v1.OccurrenceName ;
importjava.io.IOException;
importjava.lang.InterruptedException;
publicclass GetOccurrence{
// Retrieves and prints a specified Occurrence from the server
publicstaticOccurrence getOccurrence(StringoccurrenceId,StringprojectId)
throwsIOException,InterruptedException{
// String occurrenceId = "123-456-789";
// String projectId = "my-project-id";
finalOccurrenceName occurrenceName=OccurrenceName .of(projectId,occurrenceId);
// Initialize client that will be used to send requests. After completing all of your requests, 
// call the "close" method on the client to safely clean up any remaining background resources.
GrafeasClient client=ContainerAnalysisClient .create().getGrafeasClient ();
Occurrence occ=client.getOccurrence (occurrenceName);
System.out.println(occ);
returnocc;
}
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample
 */
// const projectId = 'your-project-id', // Your GCP Project ID
// const noteId = 'my-note-id' // Id of the note
// Import the library and create a client
const{ContainerAnalysisClient}=require('@google-cloud/containeranalysis');
constclient=newContainerAnalysisClient ();
// Fetch an instance of a Grafeas client:
// see: https://googleapis.dev/nodejs/grafeas/latest
constgrafeasClient=client.getGrafeasClient ();
// Construct request
// Associate the Note with a metadata type
// https://cloud.google.com/container-registry/docs/container-analysis#supported_metadata_types
// Here, we use the type "vulnerabiltity"
constformattedParent=grafeasClient.projectPath (projectId);
// Creates and returns a new Note
const[note]=awaitgrafeasClient.createNote({
parent:formattedParent,
noteId:noteId,
note:{
vulnerability:{
details:[
{
affectedCpeUri:'foo.uri',
affectedPackage:'foo',
minAffectedVersion:{
kind:'MINIMUM',
},
fixedVersion:{
kind:'MAXIMUM',
},
},
],
},
},
});
console.log(`Note ${note.name} created.`);

Python

fromtypingimport List
fromgrafeas.grafeas_v1import types
deffind_high_severity_vulnerabilities_for_image(
 resource_url: str, project_id: str
) -> List[types.grafeas.Occurrence]:
"""Retrieves a list of only high vulnerability occurrences associated
 with a resource."""
 # resource_url = 'https://gcr.io/my-project/my-image@sha256:123'
 # project_id = 'my-gcp-project'
 fromgrafeas.grafeas_v1import Severity
 fromgoogle.cloud.devtoolsimport containeranalysis_v1
 client = containeranalysis_v1.ContainerAnalysisClient()
 grafeas_client = client.get_grafeas_client()
 project_name = f"projects/{project_id}"
 filter_str = 'kind="VULNERABILITY" AND resourceUrl="{}"'.format(resource_url)
 vulnerabilities = grafeas_client.list_occurrences(
 parent=project_name, filter=filter_str
 )
 filtered_list = []
 for v in vulnerabilities:
 if (
 v.vulnerability.effective_severity == Severity.HIGH
 or v.vulnerability.effective_severity == Severity.CRITICAL
 ):
 filtered_list.append(v)
 return filtered_list

Ruby

require"google/cloud/container_analysis/v1"
##
# Snippet for the get_vulnerability_occurrences_summary call in the ContainerAnalysis service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::ContainerAnalysis::V1::ContainerAnalysis::Client#get_vulnerability_occurrences_summary.
#
defget_vulnerability_occurrences_summary
# Create a client object. The client can be reused for multiple calls.
client=Google::Cloud::ContainerAnalysis::V1::ContainerAnalysis::Client.new
# Create a request. To set request fields, pass in keyword arguments.
request=Google::Cloud::ContainerAnalysis::V1::GetVulnerabilityOccurrencesSummaryRequest.new
# Call the get_vulnerability_occurrences_summary method.
result=client.get_vulnerability_occurrences_summaryrequest
# The returned object is of type Google::Cloud::ContainerAnalysis::V1::VulnerabilityOccurrencesSummary.
presult
end

Additional resources

C++

The following list contains links to more resources related to the client library for C++:

Go

The following list contains links to more resources related to the client library for Go:

Java

The following list contains links to more resources related to the client library for Java:

Node.js

The following list contains links to more resources related to the client library for Node.js:

Python

The following list contains links to more resources related to the client library for Python:

Ruby

The following list contains links to more resources related to the client library for Ruby:

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025年10月30日 UTC.