Docker Hub へのリモート リポジトリ認証を構成する

このドキュメントでは、Artifact Registry リモート リポジトリの Docker Hub アップストリーム リポジトリに対する認証を構成する方法について説明します。

未認証の Docker Hub の割り当てが使用されないようにするには、リモート リポジトリを使用するときに Docker Hub に対する認証をおすすめします。リモート リポジトリを使用すると、Docker Hub のユーザー名とシークレットとして保存された個人アクセス トークンを Docker Hub の認証に使用できます。

このドキュメントは、Artifact Registry Docker リモート リポジトリDocker Hub アカウントをすでに作成していることを前提としています。

リモート リポジトリの詳細については、リモート リポジトリの概要をご覧ください。

準備

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Artifact Registry, Secret Manager API を有効にします。

    API を有効にする

  4. Google Cloud CLI をインストールします。
  5. gcloud CLI を初期化するには:

    gcloud init
  6. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  7. Artifact Registry, Secret Manager API を有効にします。

    API を有効にする

  8. Google Cloud CLI をインストールします。
  9. gcloud CLI を初期化するには:

    gcloud init

必要なロール

リモート リポジトリの Docker Hub への認証の構成に必要な権限を取得するには、プロジェクトに対する次の IAM ロールの付与を管理者に依頼してください。

ロールの付与の詳細については、アクセスの管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

Docker Hub の個人アクセス トークンを作成する

  1. Docker Hub にログインします。
  2. 読み取り専用の権限を持つ個人用アクセス トークンを作成します。
  3. アクセス トークンをコピーします。

  4. アクセス トークンをローカルまたは Cloud Shell のテキスト ファイルに保存します。

個人用のアクセス トークンをシークレット バージョンに保存する

  1. Secret Manager で Secret を作成する
  2. Docker Hub の個人アクセス トークンをシークレット バージョンとして保存します。

Artifact Registry サービス アカウントにシークレットへのアクセス権を付与する

Artifact Registry サービス エージェントは、Google Cloud サービスを操作するときに Artifact Registry の代理として動作する Google マネージド サービス アカウントです。サービス エージェントが Secret Manager に保存されているシークレットを使用できるようにするには、シークレット バージョンを表示する権限を付与する必要があります。

サービス エージェント ID は次のとおりです。

service-PROJECT-NUMBER@gcp-sa-artifactregistry.iam.gserviceaccount.com

PROJECT-NUMBER は、Artifact Registry が実行されている Google Cloud プロジェクトのプロジェクト番号です。

Artifact Registry サービス エージェントに Secret Manager のシークレット アクセサー ロールを付与するには:

コンソール

  1. Google Cloud コンソールの [Secret Manager] ページに移動します。

    [Secret Manager] ページに移動

  2. [Secret Manager] ページで、シークレットの名前の横にあるチェックボックスをオンにします。

  3. まだ開いていない場合は、[情報パネルを表示] をクリックしてパネルを開きます。

  4. 情報パネルで [プリンシパルを追加] をクリックします。

  5. [新しいプリンシパル] テキストエリアに、追加するメンバーのメールアドレスを入力します。

  6. [ロールを選択] プルダウンで、[シークレット マネージャー]、[Secret Manager のシークレット アクセサー] の順に選択します。

gcloud

$ gcloud secrets add-iam-policy-binding secret-id \
    --member="member" \
    --role="roles/secretmanager.secretAccessor"

ここで、member はユーザー、グループ、サービス アカウントなどの IAM メンバーです。

C#

Artifact Registry を認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。


using Google.Cloud.SecretManager.V1;
using Google.Cloud.Iam.V1;

public class IamGrantAccessSample
{
    public Policy IamGrantAccess(
      string projectId = "my-project", string secretId = "my-secret",
      string member = "user:foo@example.com")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Get current policy.
        Policy policy = client.GetIamPolicy(new GetIamPolicyRequest
        {
            ResourceAsResourceName = secretName,
        });

        // Add the user to the list of bindings.
        policy.AddRoleMember("roles/secretmanager.secretAccessor", member);

        // Save the updated policy.
        policy = client.SetIamPolicy(new SetIamPolicyRequest
        {
            ResourceAsResourceName = secretName,
            Policy = policy,
        });
        return policy;
    }
}

Go

Artifact Registry を認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
)

// iamGrantAccess grants the given member access to the secret.
func iamGrantAccess(w io.Writer, name, member string) error {
	// name := "projects/my-project/secrets/my-secret"
	// member := "user:foo@example.com"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

	// Get the current IAM policy.
	handle := client.IAM(name)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.Errorf("failed to get policy: %w", err)
	}

	// Grant the member access permissions.
	policy.Add(member, "roles/secretmanager.secretAccessor")
	if err = handle.SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("failed to save policy: %w", err)
	}

	fmt.Fprintf(w, "Updated IAM policy for %s\n", name)
	return nil
}

Java

Artifact Registry を認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import java.io.IOException;

public class IamGrantAccess {

  public static void iamGrantAccess() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String secretId = "your-secret-id";
    String member = "user:foo@example.com";
    iamGrantAccess(projectId, secretId, member);
  }

  // Grant a member access to a particular secret.
  public static void iamGrantAccess(String projectId, String secretId, String member)
      throws IOException {
    // 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 (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      // Build the name from the version.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Request the current IAM policy.
      Policy currentPolicy =
          client.getIamPolicy(
              GetIamPolicyRequest.newBuilder().setResource(secretName.toString()).build());

      // Build the new binding.
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/secretmanager.secretAccessor")
              .addMembers(member)
              .build();

      // Create a new IAM policy from the current policy, adding the binding.
      Policy newPolicy = Policy.newBuilder().mergeFrom(currentPolicy).addBindings(binding).build();

      // Save the updated IAM policy.
      client.setIamPolicy(
          SetIamPolicyRequest.newBuilder()
              .setResource(secretName.toString())
              .setPolicy(newPolicy)
              .build());

      System.out.printf("Updated IAM policy for %s\n", secretId);
    }
  }
}

Node.js

Artifact Registry を認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret';
// const member = 'user:you@example.com';
//
// NOTE: Each member must be prefixed with its type. See the IAM documentation
// for more information: https://cloud.google.com/iam/docs/overview.

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function grantAccess() {
  // Get the current IAM policy.
  const [policy] = await client.getIamPolicy({
    resource: name,
  });

  // Add the user with accessor permissions to the bindings list.
  policy.bindings.push({
    role: 'roles/secretmanager.secretAccessor',
    members: [member],
  });

  // Save the updated IAM policy.
  await client.setIamPolicy({
    resource: name,
    policy: policy,
  });

  console.log(`Updated IAM policy for ${name}`);
}

grantAccess();

PHP

Artifact Registry を認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;

// Import the Secret Manager IAM library.
use Google\Cloud\Iam\V1\Binding;
use Google\Cloud\Iam\V1\GetIamPolicyRequest;
use Google\Cloud\Iam\V1\SetIamPolicyRequest;

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 * @param string $member Your member (e.g. 'user:foo@example.com')
 */
function iam_grant_access(string $projectId, string $secretId, string $member): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the secret.
    $name = $client->secretName($projectId, $secretId);

    // Get the current IAM policy.
    $policy = $client->getIamPolicy((new GetIamPolicyRequest)->setResource($name));

    // Update the bindings to include the new member.
    $bindings = $policy->getBindings();
    $bindings[] = new Binding([
        'members' => [$member],
        'role' => 'roles/secretmanager.secretAccessor',
    ]);
    $policy->setBindings($bindings);

    // Build the request.
    $request = (new SetIamPolicyRequest)
        ->setResource($name)
        ->setPolicy($policy);

    // Save the updated policy to the server.
    $client->setIamPolicy($request);

    // Print out a success message.
    printf('Updated IAM policy for %s', $secretId);
}

Python

Artifact Registry を認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

def iam_grant_access(
    project_id: str, secret_id: str, member: str
) -> iam_policy_pb2.SetIamPolicyRequest:
    """
    Grant the given member access to a secret.
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret.
    name = client.secret_path(project_id, secret_id)

    # Get the current IAM policy.
    policy = client.get_iam_policy(request={"resource": name})

    # Add the given member with access permissions.
    policy.bindings.add(role="roles/secretmanager.secretAccessor", members=[member])

    # Update the IAM Policy.
    new_policy = client.set_iam_policy(request={"resource": name, "policy": policy})

    # Print data about the secret.
    print(f"Updated IAM policy on {secret_id}")

Ruby

Artifact Registry を認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")
# member     = "USER-OR-ACCOUNT"            # (e.g. "user:foo@example.com")

# Require the Secret Manager client library.
require "google/cloud/secret_manager"

# Create a Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service

# Build the resource name of the secret.
name = client.secret_path project: project_id, secret: secret_id

# Get the current IAM policy.
policy = client.get_iam_policy resource: name

# Add new member to current bindings
policy.bindings << Google::Iam::V1::Binding.new(
  members: [member],
  role:    "roles/secretmanager.secretAccessor"
)

# Update IAM policy
new_policy = client.set_iam_policy resource: name, policy: policy

# Print a success message.
puts "Updated IAM policy for #{secret_id}"

API

注: 他の例と異なり、IAM ポリシー全体が置き換えられます。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id:setIamPolicy" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --data "{\"policy\": {\"bindings\": [{\"members\": [\"member\"], \"role\": \"roles/secretmanager.secretAccessor\"}]}}"

シークレットへのアクセス権の付与または取り消しの詳細については、シークレットへのアクセス権の管理をご覧ください。

リモート リポジトリに Docker Hub 認証情報を追加する

Docker Hub の認証情報でリモート リポジトリを更新するには:

コンソール

  1. Google Cloud コンソールで [リポジトリ] ページを開きます。

    [リポジトリ] ページを開く

  2. リポジトリ リストでリポジトリを選択し、[リポジトリを編集] をクリックします。

  3. [リモート リポジトリ認証モード] セクションで、Docker Hub アクセス トークンを含む Docker Hub のユーザー名とシークレットを更新または追加します。

gcloud CLI

リモート リポジトリを Docker Hub 認証情報で更新するには、次のコマンドを実行します。

gcloud artifacts repositories update REPOSITORY \
    --project=PROJECT_ID \
    --location=LOCATION \
    --remote-username=USERNAME \
    --remote-password-secret-version=projects/PROJECT_ID/secrets/SECRET_ID/versions/SECRET_VERSION

次のように置き換えます。

  • REPOSITORY は、Artifact Registry のリモート リポジトリの名前に置き換えます。
  • PROJECT_ID は、Google Cloud プロジェクト ID に置き換えます。
  • LOCATION は、リポジトリのリージョンまたはマルチリージョンのロケーションです。デフォルトを設定すると、このフラグを省略できます。サポートされているリポジトリのロケーションの一覧を表示するには、コマンド gcloud artifacts locations listを実行します。
  • USERNAME を Docker Hub のユーザー名に置き換えます。
  • SECRET_ID を、Secret に付けた名前に置き換えます。
  • SECRET_VERSION は、Docker Hub のアクセス トークンを保存したシークレット バージョンに置き換えます。

次のステップ