Configure remote repository authentication to the Python Package Index (PyPI)

This document describes how to configure authentication to Python Package Index (PyPI) upstream repositories for Artifact Registry remote repositories.

This document assumes you have already created an Artifact Registry Python remote repository, and a PyPI account.

For more information on remote repositories, see the Remote repositories overview.

Required roles

To get the permissions that you need to configure authentication to PyPI for remote repositories, ask your administrator to grant you the following IAM roles on the project:

For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

Create a PyPI API token

  1. Sign in to PyPI.
  2. Create an API token.

Save your API token in a secret version

  1. Create a secret in Secret Manager.
  2. Save your PyPI API token as a secret version.

Grant the Artifact Registry service account access to your secret

The Artifact Registry service agent acts on behalf of Artifact Registry when interacting with Google Cloud services. To allow the service agent to use secrets stored in Secret Manager, you must grant the service agent permission to view your secret version.

The service agent identifier is:

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

PROJECT-NUMBER is the project number of the Google Cloud project where Artifact Registry is running.

To grant the Artifact Registry service agent the Secret Manager Secret Accessor role:

Console

  1. Go to the Secret Manager page in the Google Cloud console.

    Go to the Secret Manager page

  2. On the Secret Manager page, click the checkbox next to the name of the secret.

  3. If it is not already open, click Show Info Panel to open the panel.

  4. In the info panel, click Add Principal.

  5. In the New principals text area, enter the email address(es) of the members to add.

  6. In the Select a role dropdown, choose Secret Manager and then Secret Manager Secret Accessor.

gcloud

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

Where member is an IAM member, such as a user, group, or service account.

C#

To authenticate to Artifact Registry, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

usingGoogle.Cloud.SecretManager.V1;usingGoogle.Cloud.Iam.V1;publicclassIamGrantAccessSample{publicPolicyIamGrantAccess(stringprojectId="my-project",stringsecretId="my-secret",stringmember="user:foo@example.com"){// Create the client.SecretManagerServiceClientclient=SecretManagerServiceClient.Create();// Build the resource name.SecretNamesecretName=newSecretName(projectId,secretId);// Get current policy.Policypolicy=client.GetIamPolicy(newGetIamPolicyRequest{ResourceAsResourceName=secretName,});// Add the user to the list of bindings.policy.AddRoleMember("roles/secretmanager.secretAccessor",member);// Save the updated policy.policy=client.SetIamPolicy(newSetIamPolicyRequest{ResourceAsResourceName=secretName,Policy=policy,});returnpolicy;}}

Go

To authenticate to Artifact Registry, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import("context""fmt""io"secretmanager"cloud.google.com/go/secretmanager/apiv1")// iamGrantAccess grants the given member access to the secret.funciamGrantAccess(wio.Writer,name,memberstring)error{// name := "projects/my-project/secrets/my-secret"// member := "user:foo@example.com"// Create the client.ctx:=context.Background()client,err:=secretmanager.NewClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create secretmanager client: %w",err)}deferclient.Close()// Get the current IAM policy.handle:=client.IAM(name)policy,err:=handle.Policy(ctx)iferr!=nil{returnfmt.Errorf("failed to get policy: %w",err)}// Grant the member access permissions.policy.Add(member,"roles/secretmanager.secretAccessor")iferr=handle.SetPolicy(ctx,policy);err!=nil{returnfmt.Errorf("failed to save policy: %w",err)}fmt.Fprintf(w,"Updated IAM policy for %s\n",name)returnnil}

Java

To authenticate to Artifact Registry, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

importcom.google.cloud.secretmanager.v1.SecretManagerServiceClient;importcom.google.cloud.secretmanager.v1.SecretName;importcom.google.iam.v1.Binding;importcom.google.iam.v1.GetIamPolicyRequest;importcom.google.iam.v1.Policy;importcom.google.iam.v1.SetIamPolicyRequest;importjava.io.IOException;publicclassIamGrantAccess{publicstaticvoidiamGrantAccess()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringsecretId="your-secret-id";Stringmember="user:foo@example.com";iamGrantAccess(projectId,secretId,member);}// Grant a member access to a particular secret.publicstaticvoidiamGrantAccess(StringprojectId,StringsecretId,Stringmember)throwsIOException{// 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(SecretManagerServiceClientclient=SecretManagerServiceClient.create()){// Build the name from the version.SecretNamesecretName=SecretName.of(projectId,secretId);// Request the current IAM policy.PolicycurrentPolicy=client.getIamPolicy(GetIamPolicyRequest.newBuilder().setResource(secretName.toString()).build());// Build the new binding.Bindingbinding=Binding.newBuilder().setRole("roles/secretmanager.secretAccessor").addMembers(member).build();// Create a new IAM policy from the current policy, adding the binding.PolicynewPolicy=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

To authenticate to Artifact Registry, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/** * 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 libraryconst{SecretManagerServiceClient}=require('@google-cloud/secret-manager');// Instantiates a clientconstclient=newSecretManagerServiceClient();asyncfunctiongrantAccess(){// Get the current IAM policy.const[policy]=awaitclient.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.awaitclient.setIamPolicy({resource:name,policy:policy,});console.log(`Updated IAM policy for ${name}`);}grantAccess();

PHP

To authenticate to Artifact Registry, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To authenticate to Artifact Registry, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

defiam_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.fromgoogle.cloudimportsecretmanager# 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

To authenticate to Artifact Registry, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# 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_pathproject:project_id,secret:secret_id# Get the current IAM policy.policy=client.get_iam_policyresource:name# Add new member to current bindingspolicy.bindings << Google::Iam::V1::Binding.new(members:[member],role:"roles/secretmanager.secretAccessor")# Update IAM policynew_policy=client.set_iam_policyresource:name,policy:policy# Print a success message.puts"Updated IAM policy for #{secret_id}"

API

Note: Unlike the other examples, this replaces the entire IAM policy.

$ 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\"}]}}" 

For more information on granting or revoking access to secrets, see Manage access to secrets.

Add PyPI credentials to your remote repository

To update your remote repository with your PyPI credentials:

Console

  1. Open the Repositories page in the Google Cloud console.

    Open the Repositories page

  2. In the repository list, select the repository and click Edit Repository.

  3. In the Remote repository authentication mode section, update or add your PYPI username __token__, and the secret version containing your PyPI API token.

gcloud CLI

To update your remote repository with your PyPI credentials, run the following command:

gcloudartifactsrepositoriesupdateREPOSITORY \ --project=PROJECT_ID \ --location=LOCATION \ --remote-username=__token__ \ --remote-password-secret-version=projects/SECRET_PROJECT_ID/secrets/SECRET_ID/versions/SECRET_VERSION

Replace the following:

  • REPOSITORY with the name of your Artifact Registry remote repository.
  • PROJECT_ID with your Google Cloud project ID.
  • LOCATION with the regional or multi-regional location for the repository. You can omit this flag if you set a default. To view a list of supported locations, run the command gcloud artifacts locations list.
  • USERNAME with your PyPI username.
  • SECRET_PROJECT_ID with the project ID of the project in which you created your secret.
  • SECRET_ID with the name you gave your secret.
  • SECRET_VERSION with the secret version you saved your PyPI API token in.

Your credentials are used the next time the remote repository sends a request for an artifact from the upstream source.