Configura l'autenticazione del repository remoto su Docker Hub

Questo documento descrive come configurare l'autenticazione nei repository a monte di Docker Hub per i repository remoti di Artifact Registry.

Per impedire l'utilizzo della quota Docker Hub non autenticata, ti consigliamo di eseguire l'autenticazione su Docker Hub quando utilizzi repository remoti. I repository remoti consentono di aggiungere il nome utente Docker Hub e un token di accesso personale salvato come secret per l'autenticazione in Docker Hub.

Questo documento presuppone che tu abbia già creato un repository remoto Docker di Artifact Registry e un account Docker Hub.

Per ulteriori informazioni sui repository remoti, consulta la Panoramica dei repository remoti.

Prima di iniziare

  1. Accedi al tuo Account Google.

    Se non ne hai già uno, crea un nuovo account.

  2. Nella pagina del selettore di progetti della console Google Cloud, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  3. Abilita le API Artifact Registry, Secret Manager.

    Abilita le API

  4. Installa Google Cloud CLI.
  5. Per initialize gcloud CLI, esegui questo comando:

    gcloud init
  6. Nella pagina del selettore di progetti della console Google Cloud, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  7. Abilita le API Artifact Registry, Secret Manager.

    Abilita le API

  8. Installa Google Cloud CLI.
  9. Per initialize gcloud CLI, esegui questo comando:

    gcloud init

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per configurare l'autenticazione su Docker Hub per i repository remoti, chiedi all'amministratore di concederti i seguenti ruoli IAM per il progetto:

Per saperne di più sulla concessione dei ruoli, consulta Gestire l'accesso.

Potresti anche essere in grado di ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.

crea un token di accesso personale per Docker Hub

  1. Accedi a Docker Hub.
  2. Crea un token di accesso personale con autorizzazioni di sola lettura.
  3. Copia il token di accesso.

  4. Salva il token di accesso in un file di testo nel tuo locale o in Cloud Shell.

Salva il token di accesso personale in una versione del secret

  1. Crea un secret in Secret Manager.
  2. Salva il token di accesso personale Docker Hub come versione del secret.

Concedi all'account di servizio Artifact Registry l'accesso al tuo secret

L'agente di servizio Artifact Registry è un account di servizio gestito da Google che agisce per conto di Artifact Registry durante l'interazione con i servizi Google Cloud. Per consentire all'agente di servizio di utilizzare i secret archiviati in Secret Manager, devi concedergli l'autorizzazione per visualizzare la versione del secret.

L'identificatore dell'agente di servizio è:

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

PROJECT-NUMBER è il numero di progetto del progetto Google Cloud in cui è in esecuzione Artifact Registry.

Per concedere all'agente di servizio Artifact Registry il ruolo Funzione di accesso ai secret di Secret Manager:

Console

  1. Vai alla pagina Secret Manager nella console Google Cloud.

    Vai alla pagina di Secret Manager

  2. Nella pagina Secret Manager, fai clic sulla casella di controllo accanto al nome del secret.

  3. Se non è già aperto, fai clic su Mostra riquadro informazioni per aprirlo.

  4. Nel riquadro delle informazioni, fai clic su Aggiungi entità.

  5. Nell'area di testo Nuove entità, inserisci gli indirizzi email dei membri da aggiungere.

  6. Nel menu a discesa Seleziona un ruolo, scegli Secret Manager e poi Secret Manager (Accessore di accesso ai secret di Secret Manager).

gcloud

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

Dove member è un membro IAM, ad esempio un account utente, gruppo o servizio.

C#

Per eseguire l'autenticazione in Artifact Registry, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Artifact Registry, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Artifact Registry, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Artifact Registry, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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

Per eseguire l'autenticazione in Artifact Registry, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// 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

Per eseguire l'autenticazione in Artifact Registry, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Artifact Registry, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

# 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

Nota: a differenza degli altri esempi, questo sostituisce l'intero criterio 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\"}]}}"

Per maggiori informazioni sulla concessione o la revoca dell'accesso ai secret, consulta Gestire l'accesso ai secret.

Aggiungi le credenziali Docker Hub al repository remoto

Per aggiornare il repository remoto con le credenziali Docker Hub:

Console

  1. Apri la pagina Repositories nella console Google Cloud.

    Apri la pagina Repository

  2. Nell'elenco dei repository, seleziona il repository e fai clic su Modifica repository.

  3. Nella sezione Modalità di autenticazione repository remota, aggiorna o aggiungi il nome utente e il secret di Docker Hub contenenti il token di accesso a Docker Hub.

Interfaccia a riga di comando gcloud

Per aggiornare il repository remoto con le credenziali Docker Hub, esegui questo comando:

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

Sostituisci quanto segue:

  • REPOSITORY con il nome del tuo repository remoto Artifact Registry.
  • PROJECT_ID con il tuo ID progetto Google Cloud.
  • LOCATION con la località a livello di una o più regioni per il repository. Puoi omettere questo flag se imposti un valore predefinito. Per visualizzare un elenco delle località supportate, esegui il comando gcloud artifacts locations list.
  • USERNAME con il tuo nome utente Docker Hub.
  • SECRET_ID con il nome che hai fornito al tuo secret.
  • SECRET_VERSION con la versione del secret in cui hai salvato il token di accesso di Docker Hub.

Passaggi successivi