Create custom notes and occurrences Stay organized with collections Save and categorize content based on your preferences.
You can choose to provide your own metadata to Artifact Analysisto satisfy a specific business need. For example, an organization that providessecurity management for their customers' Docker containers can useArtifact Analysis to store and retrieve security-relatedmetadata for those images.
Note: You are not required to provide your own metadata to useArtifact Analysis.The following steps show how to provide attestation metadata for yourimages using the Artifact Analysis API. You can use the sameinstructions to store and retrieve anykind of metadata thatArtifact Analysis supports.
Before you begin
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Enable the Container Analysis API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
gcloudinit
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Enable the Container Analysis API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
gcloudinit
- Learnhow to set up access control for metadata in your project. Skip this step if you only consume metadata from occurrences created by Artifact Analysis container scanning.
Create notes and occurrences for projects
This section explains how you can create notes and occurrences. For this example, you will be using theATTESTATION kind.
As a provider, you will create a note in your project for each attestation, and you will create an occurrence in your customer's project for anoccurrence of that attestation.
Create notes
Use the following steps to create a note and give it a note ID.
Note: Your note ID can't exceed 100 characters.API
Create a file named
note.jsonwith attestation description and details.The following code shows an examplenote.jsonfile:{ "shortDescription": "A brief Description of the note", "longDescription": "A longer description of the note", "kind": "ATTESTATION", "attestation": { "hint": { "humanReadableName": "my-attestation-authority" } }}See thenotes API documentation for more information aboutthe notes JSON representation.
Run the following curl command to create a note:
curl-v-H"Content-Type: application/json"-H\"Authorization: Bearer$(gcloudauthprint-access-token)"\https://containeranalysis.googleapis.com/v1/projects/PROVIDER_PROJECT_ID/notes?note_id=NOTE_ID-d@note.jsonWhere:
- PROVIDER_PROJECT_ID is your project ID.
- NOTE_ID specifies an identifier for your note. Use a string witha maximum length of 100 characters.
Java
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Java API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
importcom.google.cloud.devtools.containeranalysis.v1.ContainerAnalysisClient;importio.grafeas.v1.GrafeasClient;importio.grafeas.v1.Note;importio.grafeas.v1.ProjectName;importio.grafeas.v1.Version;importio.grafeas.v1.AttestationNote;importjava.io.IOException;importjava.lang.InterruptedException;publicclassCreateNote{// Creates and returns a new NotepublicstaticNotecreateNote(StringnoteId,StringprojectId)throwsIOException,InterruptedException{// String noteId = "my-note";// String projectId = "my-project-id";finalStringprojectName=ProjectName.format(projectId);NotenewNote=Note.newBuilder()// Associate the Note with the metadata type// https://cloud.google.com/container-registry/docs/container-analysis#supported_metadata_types// Here, we use the type "attestation".setAttestation(AttestationNote.newBuilder().setHint(AttestationNote.Hint.newBuilder().setHumanReadableName("my-attestation-authority"))).build();// 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.GrafeasClientclient=ContainerAnalysisClient.create().getGrafeasClient();Noteresult=client.createNote(projectName,noteId,newNote);returnresult;}}Go
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Go API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
import("context""fmt"containeranalysis"cloud.google.com/go/containeranalysis/apiv1"grafeaspb"google.golang.org/genproto/googleapis/grafeas/v1")// createNote creates and returns a new attestation Note.funccreateNote(noteID,projectIDstring)(*grafeaspb.Note,error){ctx:=context.Background()client,err:=containeranalysis.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("NewClient: %w",err)}deferclient.Close()projectName:=fmt.Sprintf("projects/%s",projectID)req:=&grafeaspb.CreateNoteRequest{Parent:projectName,NoteId:noteID,Note:&grafeaspb.Note{Type:&grafeaspb.Note_Attestation{Attestation:&grafeaspb.AttestationNote{Hint:&grafeaspb.AttestationNote_Hint{HumanReadableName:"my-attestation-authority",},},},},}returnclient.GetGrafeasClient().CreateNote(ctx,req)}Node.js
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Node.js API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
/*** TODO(developer): Uncomment these variables before running the sample*/// const projectId = 'your-project-id', // Your Google Cloud Project ID// const noteId = 'my-note-id' // Id of the note// Import the library and create a clientconst{ContainerAnalysisClient}=require('@google-cloud/containeranalysis');constclient=newContainerAnalysisClient();// 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 "attestation"constformattedParent=client.getGrafeasClient().projectPath(projectId);// Creates and returns a new Noteconst[note]=awaitclient.getGrafeasClient().createNote({parent:formattedParent,noteId:noteId,note:{attestation:{hint:{humanReadableName:'my-attestation-authority',},},},});console.log(`Note${note.name} created.`);Ruby
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Ruby API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
# note_id = "A user-specified identifier for the note"# project_id = "Your Google Cloud project ID"require"google/cloud/container_analysis"# Initialize the clientclient=Google::Cloud::ContainerAnalysis.container_analysis.grafeas_clientparent=client.project_pathproject:project_idnote={attestation:{hint:{human_readable_name:"attestation-authority"}}}response=client.create_noteparent:parent,note_id:note_id,note:noteputsresponse.namePython
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Python API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
fromgoogle.cloud.devtoolsimportcontaineranalysis_v1fromgrafeas.grafeas_v1importtypes,Versiondefcreate_note(note_id:str,project_id:str)->types.grafeas.Note:"""Creates and returns a new attestation note."""# note_id = 'my-note'# project_id = 'my-gcp-project'client=containeranalysis_v1.ContainerAnalysisClient()grafeas_client=client.get_grafeas_client()project_name=f"projects/{project_id}"note={"attestation":{"hint":{"human_readable_name":"attestation-authority",}}}response=grafeas_client.create_note(parent=project_name,note_id=note_id,note=note)returnresponseCreate occurrences for the notes
To create occurrences for a note:
API
Create a file named
occurrence.jsonwith attestation description and details.The following code shows an exampleoccurrence.jsonfile:{ "resourceUri": "your-resource-uri-here", "noteName": "projects/your-note-project/notes/your-note-id", "kind": "ATTESTATION", "attestation": { "serializedPayload": "eW91ci1wYXlsb2FkLWhlcmU=", "signatures": [ { "publicKeyId": "your-key-id-here", "signature": "eW91ci1zaWduYXR1cmUtaGVyZQ==" } ] }}See thenotes API documentation for more information aboutthe notes JSON representation.
Run the following curl command to create an occurrence:
curl-v-H"Content-Type: application/json"-H\"Authorization: Bearer$(gcloudauthprint-access-token)"\https://containeranalysis.googleapis.com/v1/projects/PROVIDER_PROJECT_ID/occurrences/-d@occurrence.jsonWhere:
- PROVIDER_PROJECT_ID is your project ID.
- NOTE_ID specifies an identifier for your note. Use a string witha maximum length of 100 characters.
Java
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Java API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
importcom.google.cloud.devtools.containeranalysis.v1.ContainerAnalysisClient;importcom.google.protobuf.ByteString;importio.grafeas.v1.AttestationOccurrence;importio.grafeas.v1.GrafeasClient;importio.grafeas.v1.NoteName;importio.grafeas.v1.Occurrence;importio.grafeas.v1.ProjectName;importio.grafeas.v1.Signature;importjava.io.IOException;publicclassCreateOccurrence{// Creates and returns a new attestation Occurrence associated with an existing NotepublicstaticOccurrencecreateOccurrence(StringresourceUrl,StringnoteId,StringoccProjectId,StringnoteProjectId)throwsIOException{// String resourceUrl = "https://gcr.io/project/image@sha256:123";// String noteId = "my-note";// String occProjectId = "my-project-id";// String noteProjectId = "my-project-id";finalNoteNamenoteName=NoteName.of(noteProjectId,noteId);finalStringoccProjectName=ProjectName.format(occProjectId);OccurrencenewOcc=Occurrence.newBuilder().setNoteName(noteName.toString()).setResourceUri(resourceUrl).setAttestation(AttestationOccurrence.newBuilder().setSerializedPayload(ByteString.copyFrom("your-payload-here","UTF-8")).addSignatures(Signature.newBuilder().setPublicKeyId("your-key-id-here").setSignature(ByteString.copyFrom("your-signature-here","UTF-8")))).build();// 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.GrafeasClientclient=ContainerAnalysisClient.create().getGrafeasClient();Occurrenceresult=client.createOccurrence(occProjectName,newOcc);returnresult;}}Go
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Go API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
import("context""fmt"containeranalysis"cloud.google.com/go/containeranalysis/apiv1"grafeaspb"google.golang.org/genproto/googleapis/grafeas/v1")// createsOccurrence creates and returns a new Occurrence of a previously created attestation note.// Use this style of URL when you use Google Artifact Registry.// resourceURL := "https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image"// noteID := "my-note"ctx:=context.Background()client,err:=containeranalysis.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("NewClient: %w",err)}deferclient.Close()req:=&grafeaspb.CreateOccurrenceRequest{Parent:fmt.Sprintf("projects/%s",occProjectID),Occurrence:&grafeaspb.Occurrence{NoteName:fmt.Sprintf("projects/%s/notes/%s",noteProjectID,noteID),// Attach the occurrence to the associated resource uri.ResourceUri:resourceURL,// Details about the attestation can be added here.Details:&grafeaspb.Occurrence_Attestation{Attestation:&grafeaspb.AttestationOccurrence{SerializedPayload:[]byte("..."),Signatures:[]*grafeaspb.Signature{{PublicKeyId:"...",Signature:[]byte("..."),},},},},},}returnclient.GetGrafeasClient().CreateOccurrence(ctx,req)}Node.js
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Node.js API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
/** * TODO(developer): Uncomment these variables before running the sample */// const noteProjectId = 'your-project-id', // Your Google Cloud Project ID// const noteId = 'my-note-id', // Id of the note// const occurrenceProjectId = 'your-project-id', // The Google Cloud Project ID of the occurrence// If you are using Google Artifact Registry// const imageUrl = 'https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image:123' // Image to attach metadata to// Import the library and create a clientconst{ContainerAnalysisClient}=require('@google-cloud/containeranalysis');constclient=newContainerAnalysisClient();// Construct requestconstformattedParent=client.getGrafeasClient().projectPath(occurrenceProjectId);constformattedNote=client.getGrafeasClient().notePath(noteProjectId,noteId);// Creates and returns a new Occurrence associated with an existing Noteconst[occurrence]=awaitclient.getGrafeasClient().createOccurrence({parent:formattedParent,occurrence:{noteName:formattedNote,resourceUri:imageUrl,attestation:{serializedPayload:Buffer.from('your-payload-here').toString('base64'),signatures:[{publicKeyId:'your-key-id-here',signature:Buffer.from('your-signature-here').toString('base64'),},],},},});console.log(`Occurrence created${occurrence.name}.`);returnoccurrence;Ruby
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Ruby API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
# note_id = "A user-specified identifier for the note"# project_id = "Your Google Cloud project ID"# note_project = "The project that contains the note"# occurrence_project = "The project that contains the occurrence"require"google/cloud/container_analysis"require"base64"# Initialize the clientclient=Google::Cloud::ContainerAnalysis.container_analysis.grafeas_clientnote_path=client.note_pathproject:note_project,note:note_idproject_path=client.project_pathproject:occurrence_projectoccurrence={note_name:note_path,resource_uri:resource_url,attestation:{serialized_payload:Base64.encode64("your-payload-here"),signatures:[{public_key_id:"your-key-id-here",signature:Base64.encode64("your-signature-here")}]}}response=client.create_occurrenceparent:project_path,occurrence:occurrenceputsresponse.namePython
To learn how to install and use the client library for Artifact Analysis,seeArtifact Analysis client libraries.For more information, see theArtifact Analysis Python API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
importbase64fromgoogle.cloud.devtoolsimportcontaineranalysis_v1fromgrafeas.grafeas_v1importtypesdefcreate_occurrence(resource_url:str,note_id:str,occurrence_project:str,note_project:str)->types.grafeas.Occurrence:"""Creates and returns a new occurrence of a previously created attestation note."""# note_id = 'my-note'# project_id = 'my-gcp-project'client=containeranalysis_v1.ContainerAnalysisClient()grafeas_client=client.get_grafeas_client()formatted_note=f"projects/{note_project}/notes/{note_id}"formatted_project=f"projects/{occurrence_project}"occurrence={"note_name":formatted_note,"resource_uri":resource_url,"attestation":{"serialized_payload":base64.b64encode(b"your-payload-here").decode("utf-8"),"signatures":[{"public_key_id":"your-key-id-here","signature":base64.b64encode(b"your-signature-here").decode("utf-8"),}],},}returngrafeas_client.create_occurrence(parent=formatted_project,occurrence=occurrence)Get all occurrences for a specific note
You can view all occurrences of a specific attestation across your customer'sprojects usingnotes.occurrences.list().
API
To list all the occurrences for a note, send a GET request as follows:
GET https://containeranalysis.googleapis.com/v1/projects/PROJECT_ID/notes/NOTE_ID/occurrences
Refer to theprojects.notes.occurrences.list API endpointfor complete details.
Java
To learn how to install and use the client library for Artifact Analysis, seeArtifact Analysis client libraries. For more information, see theArtifact AnalysisJava API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
import staticjava.lang.Thread.sleep;importcom.google.cloud.devtools.containeranalysis.v1.ContainerAnalysisClient;importio.grafeas.v1.GrafeasClient;importio.grafeas.v1.ListNoteOccurrencesRequest;importio.grafeas.v1.NoteName;importio.grafeas.v1.Occurrence;importjava.io.IOException;importjava.lang.InterruptedException;publicclassOccurrencesForNote{// Retrieves all the Occurrences associated with a specified Note// Here, all Occurrences are printed and countedpublicstaticintgetOccurrencesForNote(StringnoteId,StringprojectId)throwsIOException,InterruptedException{// String noteId = "my-note";// String projectId = "my-project-id";finalNoteNamenoteName=NoteName.of(projectId,noteId);ListNoteOccurrencesRequestrequest=ListNoteOccurrencesRequest.newBuilder().setName(noteName.toString()).build();// 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.GrafeasClientclient=ContainerAnalysisClient.create().getGrafeasClient();inti=0;for(Occurrenceo:client.listNoteOccurrences(request).iterateAll()){// Write custom code to process each Occurrence hereSystem.out.println(o.getName());i=i+1;}returni;}}Go
To learn how to install and use the client library for Artifact Analysis, seeArtifact Analysis client libraries. For more information, see theArtifact AnalysisGo API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
import("context""fmt""io"containeranalysis"cloud.google.com/go/containeranalysis/apiv1""google.golang.org/api/iterator"grafeaspb"google.golang.org/genproto/googleapis/grafeas/v1")// getOccurrencesForNote retrieves all the Occurrences associated with a specified Note.// Here, all Occurrences are printed and counted.funcgetOccurrencesForNote(wio.Writer,noteID,projectIDstring)(int,error){// noteID := fmt.Sprintf("my-note")ctx:=context.Background()client,err:=containeranalysis.NewClient(ctx)iferr!=nil{return-1,fmt.Errorf("NewClient: %w",err)}deferclient.Close()req:=&grafeaspb.ListNoteOccurrencesRequest{Name:fmt.Sprintf("projects/%s/notes/%s",projectID,noteID),}it:=client.GetGrafeasClient().ListNoteOccurrences(ctx,req)count:=0for{occ,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{return-1,fmt.Errorf("occurrence iteration error: %w",err)}// Write custom code to process each Occurrence here.fmt.Fprintln(w,occ)count=count+1}returncount,nil}Node.js
To learn how to install and use the client library for Artifact Analysis, seeArtifact Analysis client libraries. For more information, see theArtifact AnalysisNode.js API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
/** * 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 clientconst{ContainerAnalysisClient}=require('@google-cloud/containeranalysis');constclient=newContainerAnalysisClient();// Get path to NoteconstformattedNote=client.notePath(projectId,noteId);// Retrieves all the Occurrences associated with a specified Noteconst[occurrences]=awaitclient.getGrafeasClient().listNoteOccurrences({name:formattedNote,});if(occurrences.length){console.log('Occurrences:');occurrences.forEach(occurrence=>{console.log(`${occurrence.name}:`);});}else{console.log('No occurrences found.');}Ruby
To learn how to install and use the client library for Artifact Analysis, seeArtifact Analysis client libraries. For more information, see theArtifact AnalysisRuby API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
# note_id = "The identifier for the note to query"# project_id = "The Google Cloud project ID of the occurrences to retrieve"require"google/cloud/container_analysis"# Initialize the clientclient=Google::Cloud::ContainerAnalysis.container_analysis.grafeas_clientname=client.note_pathproject:project_id,note:note_idcount=0client.list_note_occurrences(name:name).eachdo|occurrence|# Process occurrence hereputsoccurrencecount+=1endputs"Found#{count} occurrences"countenddefget_discovery_inforesource_url:,project_id:# resource_url = "The URL of the resource associated with the occurrence."# # e.g. https://gcr.io/project/image@sha256:123# project_id = "The Google Cloud project ID of the occurrences to retrieve"require"google/cloud/container_analysis"# Initialize the clientclient=Google::Cloud::ContainerAnalysis.container_analysis.grafeas_clientparent=client.project_pathproject:project_idfilter="kind =\"DISCOVERY\" AND resourceUrl =\"#{resource_url}\""client.list_occurrences(parent:parent,filter:filter).eachdo|occurrence|# Process discovery occurrence hereputsoccurrenceendenddefoccurrence_pubsubsubscription_id:,timeout_seconds:,project_id:# subscription_id = "A user-specified identifier for the new subscription"# timeout_seconds = "The number of seconds to listen for new Pub/Sub messages"# project_id = "Your Google Cloud project ID"require"google/cloud/pubsub"pubsub=Google::Cloud::PubSub.newproject_id:project_idsubscription_admin=pubsub.subscription_adminsubscription=subscription_admin.create_subscription\name:pubsub.subscription_path(subscription_id),topic:pubsub.topic_path("container-analysis-occurrences-v1")subscriber=pubsub.subscribersubscription.namecount=0listener=subscriber.listendo|received_message|count+=1# Process incoming occurrence hereputs"Message#{count}:#{received_message.data}"received_message.acknowledge!endlistener.start# Wait for incoming occurrencessleeptimeout_secondslistener.stop.wait!subscription_admin.delete_subscriptionsubscription:subscription.name# Print and return the total number of Pub/Sub messages receivedputs"Total Messages Received:#{count}"countend# rubocop:disable Metrics/MethodLengthdefpoll_discovery_finishedresource_url:,timeout_seconds:,project_id:# resource_url = "The URL of the resource associated with the occurrence."# # e.g. https://gcr.io/project/image@sha256:123# timeout_seconds = "The number of seconds to wait for the discovery occurrence"# project_id = "Your Google Cloud project ID"require"google/cloud/container_analysis"deadline=Time.now+timeout_seconds# Initialize the clientclient=Google::Cloud::ContainerAnalysis.container_analysis.grafeas_clientparent=client.project_pathproject:project_id# Find the discovery occurrence using a filter stringdiscovery_occurrence=nilwhilediscovery_occurrence.nil?beginfilter="resourceUrl=\"#{resource_url}\" "\'AND noteProjectId="goog-analysis" '\'AND noteId="PACKAGE_VULNERABILITY"'# The above filter isn't testable, since it looks for occurrences in a# locked down project. Fall back to a more permissive filter for testingfilter="kind =\"DISCOVERY\" AND resourceUrl =\"#{resource_url}\""# Only the discovery occurrence should be returned for the given filterdiscovery_occurrence=client.list_occurrences(parent:parent,filter:filter).firstrescueStandardError# If there is an error, keep trying until the deadlineputs"discovery occurrence not yet found"ensure# check for timeoutsleep1raise"Timeout while retrieving discovery occurrence."ifTime.now >deadlineendend# Wait for the discovery occurrence to enter a terminal statestatus=Grafeas::V1::DiscoveryOccurrence::AnalysisStatus::PENDINGuntil[:FINISHED_SUCCESS,:FINISHED_FAILED,:FINISHED_UNSUPPORTED].include?status# Update occurrencebeginupdated=client.get_occurrencename:discovery_occurrence.namestatus=updated.discovery.analysis_statusrescueStandardError# If there is an error, keep trying until the deadlineputs"discovery occurrence not yet in terminal state"ensure# check for timeoutsleep1raise"Timeout while retrieving discovery occurrence."ifTime.now >deadlineendendputs"Found discovery occurrence#{updated.name}."puts"Status:#{updated.discovery.analysis_status}"updatedend# rubocop:enable Metrics/MethodLengthdeffind_vulnerabilities_for_imageresource_url:,project_id:# resource_url = "The URL of the resource associated with the occurrence# e.g. https://gcr.io/project/image@sha256:123"# project_id = "The Google Cloud project ID of the vulnerabilities to find"require"google/cloud/container_analysis"# Initialize the clientclient=Google::Cloud::ContainerAnalysis.container_analysis.grafeas_clientparent=client.project_pathproject:project_idfilter="resourceUrl =\"#{resource_url}\" AND kind =\"VULNERABILITY\""client.list_occurrencesparent:parent,filter:filterenddeffind_high_severity_vulnerabilities_for_imageresource_url:,project_id:# resource_url = "The URL of the resource associated with the occurrence."# # If you are using Google Container Registry# # e.g. https://gcr.io/project/repo/image@sha256:123# # If you are using Google Artifact Registry# # e.g. https://LOCATION-docker.pkg.dev/project/repo/image@sha256:123# project_id = "The Google Cloud project ID of the vulnerabilities to find"require"google/cloud/container_analysis"# Initialize the clientclient=Google::Cloud::ContainerAnalysis.container_analysis.grafeas_clientparent=client.project_pathproject:project_idfilter="resourceUrl =\"#{resource_url}\" AND kind =\"VULNERABILITY\""vulnerability_list=client.list_occurrencesparent:parent,filter:filter# Filter the list to include only "high" and "critical" vulnerabilitiesvulnerability_list.selectdo|item|[:HIGH,:CRITICAL].include?item.vulnerability.effective_severityendendPython
To learn how to install and use the client library for Artifact Analysis, seeArtifact Analysis client libraries. For more information, see theArtifact AnalysisPython API reference documentation.
To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
fromgoogle.cloud.devtoolsimportcontaineranalysis_v1defget_occurrences_for_note(note_id:str,project_id:str)->int:"""Retrieves all the occurrences associated with a specified Note. Here, all occurrences are printed and counted."""# note_id = 'my-note'# project_id = 'my-gcp-project'client=containeranalysis_v1.ContainerAnalysisClient()grafeas_client=client.get_grafeas_client()note_name=f"projects/{project_id}/notes/{note_id}"response=grafeas_client.list_note_occurrences(name=note_name)count=0foroinresponse:# do something with the retrieved occurrence# in this sample, we will simply count each onecount+=1returncountWhat's next
For instructions on how to view and filter notes and occurrences forcontainer images, seeViewing vulnerability occurrences.
For instructions on how to set up notifications, seePub/Sub notifications.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-19 UTC.