Concedi ruoli utilizzando le librerie client

Scopri come iniziare a utilizzare i metodi IAM dell'API Resource Manager nel tuo linguaggio di programmazione preferito.


Per seguire le indicazioni dettagliate per questa attività direttamente nella console Google Cloud, fai clic su Aiuto:

Guidami


Prima di iniziare

Creare un progetto Google Cloud

Per questa guida rapida è necessario un nuovo progetto Google Cloud.

  1. Accedi al tuo account Google Cloud. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti gratuiti per l'esecuzione, il test e il deployment dei carichi di lavoro.
  2. Installa Google Cloud CLI.
  3. Per initialize gcloud CLI, esegui questo comando:

    gcloud init
  4. Crea o seleziona un progetto Google Cloud.

    • Crea un progetto Google Cloud:

      gcloud projects create PROJECT_ID

      Sostituisci PROJECT_ID con un nome per il progetto Google Cloud che stai creando.

    • Seleziona il progetto Google Cloud che hai creato:

      gcloud config set project PROJECT_ID

      Sostituisci PROJECT_ID con il nome del tuo progetto Google Cloud.

  5. Attiva l'API Resource Manager.

    gcloud services enable cloudresourcemanager.googleapis.com
  6. Crea credenziali di autenticazione locali per il tuo Account Google:

    gcloud auth application-default login
  7. Concedi i ruoli al tuo Account Google. Esegui questo comando una volta per ciascuno dei seguenti ruoli IAM: roles/resourcemanager.projectIamAdmin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • Sostituisci PROJECT_ID con l'ID progetto.
    • Sostituisci EMAIL_ADDRESS con il tuo indirizzo email.
    • Sostituisci ROLE con ogni singolo ruolo.
  8. Installa Google Cloud CLI.
  9. Per initialize gcloud CLI, esegui questo comando:

    gcloud init
  10. Crea o seleziona un progetto Google Cloud.

    • Crea un progetto Google Cloud:

      gcloud projects create PROJECT_ID

      Sostituisci PROJECT_ID con un nome per il progetto Google Cloud che stai creando.

    • Seleziona il progetto Google Cloud che hai creato:

      gcloud config set project PROJECT_ID

      Sostituisci PROJECT_ID con il nome del tuo progetto Google Cloud.

  11. Attiva l'API Resource Manager.

    gcloud services enable cloudresourcemanager.googleapis.com
  12. Crea credenziali di autenticazione locali per il tuo Account Google:

    gcloud auth application-default login
  13. Concedi i ruoli al tuo Account Google. Esegui questo comando una volta per ciascuno dei seguenti ruoli IAM: roles/resourcemanager.projectIamAdmin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • Sostituisci PROJECT_ID con l'ID progetto.
    • Sostituisci EMAIL_ADDRESS con il tuo indirizzo email.
    • Sostituisci ROLE con ogni singolo ruolo.

installa la libreria client

C#

Per saperne di più sulla configurazione dell'ambiente di sviluppo C#, consulta la Guida alla configurazione dell'ambiente di sviluppo C#.

install-package Google.Apis.Iam.v1
install-package Google.Apis.CloudResourceManager.v1

Go

go get golang.org/x/oauth2/google
go get google.golang.org/api/cloudresourcemanager/v1

Java

Per ulteriori informazioni sulla configurazione dell'ambiente di sviluppo Java, consulta la Guida alla configurazione dell'ambiente di sviluppo Java.

Se utilizzi Maven, aggiungilo al tuo file pom.xml.
<dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-cloudresourcemanager</artifactId>
  <version>v3-rev20240128-2.0.0</version>
</dependency>
<dependency>
  <groupId>com.google.auth</groupId>
  <artifactId>google-auth-library-oauth2-http</artifactId>
</dependency>
<dependency>
  <groupId>com.google.http-client</groupId>
  <artifactId>google-http-client-jackson2</artifactId>
</dependency>
<dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-iam</artifactId>
  <version>v1-rev20240118-2.0.0</version>
</dependency>

Python

Per saperne di più sulla configurazione dell'ambiente di sviluppo Python, consulta la Guida alla configurazione dell'ambiente di sviluppo Python.

pip install --upgrade google-api-python-client google-auth google-auth-httplib2

Lettura, modifica e scrittura di un criterio di autorizzazione

Lo snippet di codice in questa guida rapida:

  • Inizializza il servizio Resource Manager, che gestisce i progetti Google Cloud.
  • Legge il criterio di autorizzazione per il tuo progetto.
  • Modifica il criterio di autorizzazione concedendo il ruolo Autore log (roles/logging.logWriter) al tuo Account Google.
  • Scrive il criterio di autorizzazione aggiornato.
  • Stampa tutte le entità con il ruolo di Writer log (roles/logging.logWriter) a livello di progetto.
  • Revoca il ruolo di Writer log.

Sostituisci i seguenti valori prima di eseguire lo snippet di codice:

  • your-project: l'ID del progetto.
  • your-member: l'indirizzo email del tuo Account Google, con il prefisso user:. Ad esempio, user:tanya@example.com.

C#

Per scoprire come installare e utilizzare la libreria client per Resource Manager, consulta librerie client di Resource Manager. Per saperne di più, consulta la documentazione di riferimento dell'API C# di Resource Manager.

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


using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;
using Google.Apis.Iam.v1;
using System;
using System.Collections.Generic;
using System.Linq;

public class QuickStart
{
    public static void Main(string[] args)
    {
        // TODO: Replace with your project ID
        var projectId = "your-project";
        // TODO: Replace with the ID of your member in the form "user:member@example.com"
        var member = "your-member";
        // Role to be granted
        var role = "roles/logging.logWriter";

        // Initialize service
        CloudResourceManagerService crmService = InitializeService();

        // Grant your member the "Log Writer" role for your project
        AddBinding(crmService, projectId, member, role);

        // Get the project's policy and print all members with the the "Log Writer" role
        var policy = GetPolicy(crmService, projectId);
        var binding = policy.Bindings.FirstOrDefault(x => x.Role == role);
        Console.WriteLine("Role: " + binding.Role);
        Console.Write("Members: ");
        foreach (var m in binding.Members)
        {
            Console.Write("[" + m + "] ");
        }
        Console.WriteLine();

        // Remove member from the "Log Writer" role
        RemoveMember(crmService, projectId, member, role);
    }

    public static CloudResourceManagerService InitializeService()
    {
        // Get credentials
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);

        // Create the Cloud Resource Manager service object
        CloudResourceManagerService crmService = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        return crmService;
    }

    public static Policy GetPolicy(CloudResourceManagerService crmService, String projectId)
    {
        // Get the project's policy by calling the
        // Cloud Resource Manager Projects API
        var policy = crmService.Projects.GetIamPolicy(
            new GetIamPolicyRequest(),
            projectId).Execute();
        return policy;
    }

    public static void SetPolicy(CloudResourceManagerService crmService, String projectId, Policy policy)
    {
        // Set the project's policy by calling the
        // Cloud Resource Manager Projects API
        crmService.Projects.SetIamPolicy(
           new SetIamPolicyRequest
           {
               Policy = policy
           }, projectId).Execute();
    }

    public static void AddBinding(
        CloudResourceManagerService crmService,
        string projectId,
        string member,
        string role)
    {
        // Get the project's policy
        var policy = GetPolicy(crmService, projectId);

        // Find binding in policy
        var binding = policy.Bindings.FirstOrDefault(x => x.Role == role);

        // If binding already exists, add member to binding
        if (binding != null)
        {
            binding.Members.Add(member);
        }
        // If binding does not exist, add binding to policy
        else
        {
            binding = new Binding
            {
                Role = role,
                Members = new List<string> { member }
            };
            policy.Bindings.Add(binding);
        }

        // Set the updated policy
        SetPolicy(crmService, projectId, policy);
    }

    public static void RemoveMember(
        CloudResourceManagerService crmService,
        string projectId,
        string member,
        string role)
    {
        // Get the project's policy
        var policy = GetPolicy(crmService, projectId);

        // Remove the member from the role
        var binding = policy.Bindings.FirstOrDefault(x => x.Role == role);
        if (binding == null)
        {
            Console.WriteLine("Role does not exist in policy.");
        }
        else
        {
            if (binding.Members.Contains(member))
            {
                binding.Members.Remove(member);
            }
            else
            {
                Console.WriteLine("The member has not been granted this role.");
            }

            if (binding.Members.Count == 0)
            {
                policy.Bindings.Remove(binding);
            }
        }

        // Set the updated policy
        SetPolicy(crmService, projectId, policy);
    }
}

Go

Per scoprire come installare e utilizzare la libreria client per Resource Manager, consulta librerie client di Resource Manager. Per saperne di più, consulta la documentazione di riferimento dell'API Go di Resource Manager.

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


package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"strings"
	"time"

	"google.golang.org/api/cloudresourcemanager/v1"
)

func main() {
	// TODO: Add your project ID
	projectID := flag.String("project_id", "", "Cloud Project ID")
	// TODO: Add the ID of your member in the form "user:member@example.com"
	member := flag.String("member_id", "", "Your member ID")
	flag.Parse()

	// The role to be granted
	var role string = "roles/logging.logWriter"

	// Initializes the Cloud Resource Manager service
	ctx := context.Background()
	crmService, err := cloudresourcemanager.NewService(ctx)
	if err != nil {
		log.Fatalf("cloudresourcemanager.NewService: %v", err)
	}

	// Grants your member the "Log writer" role for your project
	addBinding(crmService, *projectID, *member, role)

	// Gets the project's policy and prints all members with the "Log Writer" role
	policy := getPolicy(crmService, *projectID)
	// Find the policy binding for role. Only one binding can have the role.
	var binding *cloudresourcemanager.Binding
	for _, b := range policy.Bindings {
		if b.Role == role {
			binding = b
			break
		}
	}
	fmt.Println("Role: ", binding.Role)
	fmt.Print("Members: ", strings.Join(binding.Members, ", "))

	// Removes member from the "Log writer" role
	removeMember(crmService, *projectID, *member, role)

}

// addBinding adds the member to the project's IAM policy
func addBinding(crmService *cloudresourcemanager.Service, projectID, member, role string) {

	policy := getPolicy(crmService, projectID)

	// Find the policy binding for role. Only one binding can have the role.
	var binding *cloudresourcemanager.Binding
	for _, b := range policy.Bindings {
		if b.Role == role {
			binding = b
			break
		}
	}

	if binding != nil {
		// If the binding exists, adds the member to the binding
		binding.Members = append(binding.Members, member)
	} else {
		// If the binding does not exist, adds a new binding to the policy
		binding = &cloudresourcemanager.Binding{
			Role:    role,
			Members: []string{member},
		}
		policy.Bindings = append(policy.Bindings, binding)
	}

	setPolicy(crmService, projectID, policy)

}

// removeMember removes the member from the project's IAM policy
func removeMember(crmService *cloudresourcemanager.Service, projectID, member, role string) {

	policy := getPolicy(crmService, projectID)

	// Find the policy binding for role. Only one binding can have the role.
	var binding *cloudresourcemanager.Binding
	var bindingIndex int
	for i, b := range policy.Bindings {
		if b.Role == role {
			binding = b
			bindingIndex = i
			break
		}
	}

	// Order doesn't matter for bindings or members, so to remove, move the last item
	// into the removed spot and shrink the slice.
	if len(binding.Members) == 1 {
		// If the member is the only member in the binding, removes the binding
		last := len(policy.Bindings) - 1
		policy.Bindings[bindingIndex] = policy.Bindings[last]
		policy.Bindings = policy.Bindings[:last]
	} else {
		// If there is more than one member in the binding, removes the member
		var memberIndex int
		for i, mm := range binding.Members {
			if mm == member {
				memberIndex = i
			}
		}
		last := len(policy.Bindings[bindingIndex].Members) - 1
		binding.Members[memberIndex] = binding.Members[last]
		binding.Members = binding.Members[:last]
	}

	setPolicy(crmService, projectID, policy)

}

// getPolicy gets the project's IAM policy
func getPolicy(crmService *cloudresourcemanager.Service, projectID string) *cloudresourcemanager.Policy {

	ctx := context.Background()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	request := new(cloudresourcemanager.GetIamPolicyRequest)
	policy, err := crmService.Projects.GetIamPolicy(projectID, request).Do()
	if err != nil {
		log.Fatalf("Projects.GetIamPolicy: %v", err)
	}

	return policy
}

// setPolicy sets the project's IAM policy
func setPolicy(crmService *cloudresourcemanager.Service, projectID string, policy *cloudresourcemanager.Policy) {

	ctx := context.Background()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	request := new(cloudresourcemanager.SetIamPolicyRequest)
	request.Policy = policy
	policy, err := crmService.Projects.SetIamPolicy(projectID, request).Do()
	if err != nil {
		log.Fatalf("Projects.SetIamPolicy: %v", err)
	}
}

Java

Per scoprire come installare e utilizzare la libreria client per Resource Manager, consulta librerie client di Resource Manager. Per saperne di più, consulta la documentazione di riferimento dell'API Java di Resource Manager.

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

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.cloudresourcemanager.v3.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.v3.model.Binding;
import com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import com.google.api.services.cloudresourcemanager.v3.model.SetIamPolicyRequest;
import com.google.api.services.iam.v1.IamScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class Quickstart {

  public static void main(String[] args) {
    // TODO: Replace with your project ID in the form "projects/your-project-id".
    String projectId = "your-project";
    // TODO: Replace with the ID of your member in the form "user:member@example.com"
    String member = "your-member";
    // The role to be granted.
    String role = "roles/logging.logWriter";

    // Initializes the Cloud Resource Manager service.
    CloudResourceManager crmService = null;
    try {
      crmService = initializeService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.getMessage() + e.getStackTrace());
    }

    // Grants your member the "Log writer" role for your project.
    addBinding(crmService, projectId, member, role);

    // Get the project's policy and print all members with the "Log Writer" role
    Policy policy = getPolicy(crmService, projectId);
    Binding binding = null;
    List<Binding> bindings = policy.getBindings();
    for (Binding b : bindings) {
      if (b.getRole().equals(role)) {
        binding = b;
        break;
      }
    }
    System.out.println("Role: " + binding.getRole());
    System.out.print("Members: ");
    for (String m : binding.getMembers()) {
      System.out.print("[" + m + "] ");
    }
    System.out.println();

    // Removes member from the "Log writer" role.
    removeMember(crmService, projectId, member, role);
  }

  public static CloudResourceManager initializeService()
      throws IOException, GeneralSecurityException {
    // Use the Application Default Credentials strategy for authentication. For more info, see:
    // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    // Creates the Cloud Resource Manager service object.
    CloudResourceManager service =
        new CloudResourceManager.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("iam-quickstart")
            .build();
    return service;
  }

  public static void addBinding(
      CloudResourceManager crmService, String projectId, String member, String role) {

    // Gets the project's policy.
    Policy policy = getPolicy(crmService, projectId);

    // If policy is not retrieved, return early.
    if (policy == null) {
      return;
    }

    // Finds binding in policy, if it exists.
    Binding binding = null;
    for (Binding b : policy.getBindings()) {
      if (b.getRole().equals(role)) {
        binding = b;
        break;
      }
    }

    if (binding != null) {
      // If binding already exists, adds member to binding.
      binding.getMembers().add(member);
    } else {
      // If binding does not exist, adds binding to policy.
      binding = new Binding();
      binding.setRole(role);
      binding.setMembers(Collections.singletonList(member));
      policy.getBindings().add(binding);
    }

    // Sets the updated policy.
    setPolicy(crmService, projectId, policy);
  }

  public static void removeMember(
      CloudResourceManager crmService, String projectId, String member, String role) {
    // Gets the project's policy.
    Policy policy = getPolicy(crmService, projectId);

    // Removes the member from the role.
    Binding binding = null;
    for (Binding b : policy.getBindings()) {
      if (b.getRole().equals(role)) {
        binding = b;
        break;
      }
    }
    if (binding != null && binding.getMembers().contains(member)) {
      binding.getMembers().remove(member);
      if (binding.getMembers().isEmpty()) {
        policy.getBindings().remove(binding);
      }
    }

    // Sets the updated policy.
    setPolicy(crmService, projectId, policy);
  }

  public static Policy getPolicy(CloudResourceManager crmService, String projectId) {
    // Gets the project's policy by calling the
    // Cloud Resource Manager Projects API.
    Policy policy = null;
    try {
      GetIamPolicyRequest request = new GetIamPolicyRequest();
      policy = crmService.projects().getIamPolicy(projectId, request).execute();
    } catch (IOException e) {
      System.out.println("Unable to get policy: \n" + e.getMessage() + e.getStackTrace());
    }
    return policy;
  }

  private static void setPolicy(CloudResourceManager crmService, String projectId, Policy policy) {
    // Sets the project's policy by calling the
    // Cloud Resource Manager Projects API.
    try {
      SetIamPolicyRequest request = new SetIamPolicyRequest();
      request.setPolicy(policy);
      crmService.projects().setIamPolicy(projectId, request).execute();
    } catch (IOException e) {
      System.out.println("Unable to set policy: \n" + e.getMessage() + e.getStackTrace());
    }
  }
}

Python

Per scoprire come installare e utilizzare la libreria client per Resource Manager, consulta librerie client di Resource Manager. Per saperne di più, consulta la documentazione di riferimento dell'API Python di Resource Manager.

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

import google.auth
import googleapiclient.discovery

def quickstart(project_id: str, member: str) -> None:
    """Gets a policy, adds a member, prints their permissions, and removes the member."""

    # Role to be granted.
    role = "roles/logging.logWriter"

    # Initializes service.
    crm_service = initialize_service()

    # Grants your member the 'Log Writer' role for the project.
    modify_policy_add_role(crm_service, project_id, role, member)

    # Gets the project's policy and prints all members with the 'Log Writer' role.
    policy = get_policy(crm_service, project_id)
    binding = next(b for b in policy["bindings"] if b["role"] == role)
    print(f'Role: {(binding["role"])}')
    print("Members: ")
    for m in binding["members"]:
        print(f"[{m}]")

    # Removes the member from the 'Log Writer' role.
    modify_policy_remove_member(crm_service, project_id, role, member)

def initialize_service() -> dict:
    """Initializes a Cloud Resource Manager service."""

    credentials, _ = google.auth.default(
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    crm_service = googleapiclient.discovery.build(
        "cloudresourcemanager", "v1", credentials=credentials
    )
    return crm_service

def modify_policy_add_role(
    crm_service: str, project_id: str, role: str, member: str
) -> None:
    """Adds a new role binding to a policy."""

    policy = get_policy(crm_service, project_id)

    binding = None
    for b in policy["bindings"]:
        if b["role"] == role:
            binding = b
            break
    if binding is not None:
        binding["members"].append(member)
    else:
        binding = {"role": role, "members": [member]}
        policy["bindings"].append(binding)

    set_policy(crm_service, project_id, policy)

def modify_policy_remove_member(
    crm_service: str, project_id: str, role: str, member: str
) -> None:
    """Removes a  member from a role binding."""

    policy = get_policy(crm_service, project_id)

    binding = next(b for b in policy["bindings"] if b["role"] == role)
    if "members" in binding and member in binding["members"]:
        binding["members"].remove(member)

    set_policy(crm_service, project_id, policy)

def get_policy(crm_service: str, project_id: str, version: int = 3) -> dict:
    """Gets IAM policy for a project."""

    policy = (
        crm_service.projects()
        .getIamPolicy(
            resource=project_id,
            body={"options": {"requestedPolicyVersion": version}},
        )
        .execute()
    )
    return policy

def set_policy(crm_service: str, project_id: str, policy: str) -> dict:
    """Sets IAM policy for a project."""

    policy = (
        crm_service.projects()
        .setIamPolicy(resource=project_id, body={"policy": policy})
        .execute()
    )
    return policy

if __name__ == "__main__":
    # TODO: replace with your project ID
    project_id = "your-project-id"
    # TODO: Replace with the ID of your member in the form 'user:member@example.com'.
    member = "your-member"
    quickstart(project_id, member)

Complimenti! Hai usato i metodi IAM nell'API Resource Manager per modificare l'accesso a un progetto.

Com'è andata?

Esegui la pulizia

  1. Facoltativo: revoca le credenziali di autenticazione che hai creato ed elimina il file delle credenziali locale.

    gcloud auth application-default revoke
  2. Facoltativo: revoca le credenziali dallgcloud CLI.

    gcloud auth revoke

Passaggi successivi