Container Analysis Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Container Analysis API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Installing the client library

Go

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

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

Java

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



Node.js

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


npm install @google-cloud/containeranalysis

Python

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


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

    pip install virtualenv
    virtualenv <your-env>
    source <your-env>/bin/activate
    <your-env>/bin/pip install google-cloud-containeranalysis</your-env></your-env></your-env>
    
  • Windows

    pip install virtualenv
    virtualenv <your-env>
    <your-env>\Scripts\activate
    <your-env>\Scripts\pip.exe install google-cloud-containeranalysis</your-env></your-env></your-env>
    

Ruby

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

gem install google-cloud-container_analysis

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

Cloud Console

  1. 在 Cloud Console 中,转到创建服务帐号密钥页面。

    转到“创建服务帐号密钥”页面
  2. 服务帐号列表中,选择新的服务帐号
  3. 服务帐号名称字段中,输入一个名称。
  4. 角色列表中,选择项目 > 所有者

    注意角色字段授权您的服务帐号资源访问权限。您稍后可以使用 Cloud Console 查看和更改此字段。如果您开发的是正式版应用,请指定比项目 > Owner 更为精细的权限。如需了解详情,请参阅为服务帐号授予角色
  5. 点击创建。包含密钥的 JSON 文件就会下载到计算机。

命令行

您可以使用本地机器上的 Cloud SDK 或在 Cloud Shell 中运行以下命令。

  1. 创建服务帐号。将 [NAME] 替换为服务帐号的名称。

    gcloud iam service-accounts create [NAME]
  2. 向服务帐号授予权限。将 [PROJECT_ID] 替换为您的项目 ID。

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    注意角色字段授权您的服务帐号资源访问权限。您稍后可以使用 Cloud Console 查看和更改此字段。如果您开发的是正式版应用,请指定比项目 > Owner 更为精细的权限。如需了解详情,请参阅向服务帐号授予角色
  3. 生成密钥文件。将 [FILE_NAME] 替换为密钥文件的名称。

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

通过设定环境变量 GOOGLE_APPLICATION_CREDENTIALS,向您的应用代码提供身份验证凭据。将 [PATH] 替换为包含您服务帐号密钥的 JSON 文件的路径,并将 [FILE_NAME] 替换为文件名。此变量仅适用于当前的 shell 会话,因此,如果您打开新的会话,请重新设置该变量。

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

使用 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

使用命令提示符:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

Go

To use this sample, prepare your machine for Go development, and complete the Container Analysis quickstart. For more information, see the Container Analysis Go API reference documentation.


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.
func getOccurrence(occurrenceID, projectID string) (*grafeaspb.Occurrence, error) {
	// occurrenceID := path.Base(occurrence.Name)
	ctx := context.Background()
	client, err := containeranalysis.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %v", err)
	}
	defer client.Close()

	req := &grafeaspb.GetOccurrenceRequest{
		Name: fmt.Sprintf("projects/%s/occurrences/%s", projectID, occurrenceID),
	}
	occ, err := client.GetGrafeasClient().GetOccurrence(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("client.GetOccurrence: %v", err)
	}
	return occ, nil
}

Java

Before trying this sample, follow the Java setup instructions in Setting Up a Java Development Environment. For more information, see the Container Analysis Java API reference documentation.

import com.google.cloud.devtools.containeranalysis.v1.ContainerAnalysisClient;
import io.grafeas.v1.GrafeasClient;
import io.grafeas.v1.Occurrence;
import io.grafeas.v1.OccurrenceName;
import java.io.IOException;
import java.lang.InterruptedException;

public class GetOccurrence {
  // Retrieves and prints a specified Occurrence from the server
  public static Occurrence getOccurrence(String occurrenceId, String projectId) 
      throws IOException, InterruptedException {
    // String occurrenceId = "123-456-789";
    // String projectId = "my-project-id";
    final OccurrenceName 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);
    return occ;
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in Setting Up a Node.js Development Environment. For more information, see the Container Analysis Node.js API reference documentation.

/**
 * 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');
const client = new ContainerAnalysisClient();
// Fetch an instance of a Grafeas client:
// see: https://googleapis.dev/nodejs/grafeas/latest
const grafeasClient = 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"
const formattedParent = grafeasClient.projectPath(projectId);

// Creates and returns a new Note
const [note] = await grafeasClient.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

Before trying this sample, follow the Python setup instructions in Setting Up a Python Development Environment. For more information, see the Container Analysis Python API reference documentation.

def find_high_severity_vulnerabilities_for_image(resource_url, project_id):
    """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'

    from grafeas.grafeas_v1.gapic.enums import Severity
    from google.cloud.devtools import containeranalysis_v1

    client = containeranalysis_v1.ContainerAnalysisClient()
    grafeas_client = client.get_grafeas_client()
    project_name = grafeas_client.project_path(project_id)

    filter_str = 'kind="VULNERABILITY" AND resourceUrl="{}"'\
        .format(resource_url)
    vulnerabilities = grafeas_client.list_occurrences(project_name, filter_str)
    filtered_list = []
    for v in vulnerabilities:
        if v.effective_severity == Severity.HIGH or v.effective_severity == Severity.CRITICAL:
            filtered_list.append(v)
    return filtered_list

Ruby

Before trying this sample, follow the Ruby setup instructions in Setting Up a Ruby Development Environment. For more information, see the Container Analysis Ruby API reference documentation.


require "logger"

module MyLogger
  LOGGER = Logger.new $stderr, level: Logger::WARN
  def logger
    LOGGER
  end
end

# Define a gRPC module-level logger method before grpc/logconfig.rb loads.
module GRPC
  extend MyLogger
end

Additional resources