클라이언트 라이브러리를 사용하여 역할 부여

Resource Manager API에서 좋아하는 프로그래밍 언어로 IAM 메서드를 시작하는 방법을 알아봅니다.


Google Cloud 콘솔에서 이 태스크에 대한 단계별 안내를 직접 수행하려면 둘러보기를 클릭합니다.

둘러보기


시작하기 전에

Google Cloud 프로젝트 만들기

이 빠른 시작을 진행하려면 새 Google Cloud 프로젝트가 필요합니다.

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.
  3. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  5. Enable the Resource Manager API:

    gcloud services enable cloudresourcemanager.googleapis.com
  6. Create local authentication credentials for your user account:

    gcloud auth application-default login
  7. Google 계정에 역할을 부여합니다. 다음 각 IAM 역할에 대해 다음 명령어를 한 번씩 실행합니다. roles/resourcemanager.projectIamAdmin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID를 프로젝트 ID로 바꿉니다.
    • EMAIL_ADDRESS를 이메일 주소로 바꿉니다.
    • ROLE을 각 개별 역할로 바꿉니다.
  8. Install the Google Cloud CLI.
  9. To initialize the gcloud CLI, run the following command:

    gcloud init
  10. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  11. Enable the Resource Manager API:

    gcloud services enable cloudresourcemanager.googleapis.com
  12. Create local authentication credentials for your user account:

    gcloud auth application-default login
  13. Google 계정에 역할을 부여합니다. 다음 각 IAM 역할에 대해 다음 명령어를 한 번씩 실행합니다. roles/resourcemanager.projectIamAdmin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID를 프로젝트 ID로 바꿉니다.
    • EMAIL_ADDRESS를 이메일 주소로 바꿉니다.
    • ROLE을 각 개별 역할로 바꿉니다.

클라이언트 라이브러리 설치

C#

C# 개발 환경 설정에 관한 자세한 내용은 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

자바 개발 환경 설정에 관한 자세한 내용은 자바 개발 환경 설정 가이드를 참조하세요.

Maven을 사용하는 경우 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

Python 개발 환경 설정에 관한 자세한 내용은 Python 개발 환경 설정 가이드를 참조하세요.

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

허용 정책 읽기, 수정, 쓰기

이 빠른 시작의 코드 스니펫은 다음 작업을 수행합니다.

  • Google Cloud 프로젝트를 관리하는 Resource Manager 서비스를 초기화합니다.
  • 프로젝트의 허용 정책을 읽습니다.
  • Google 계정에 로그 작성자 역할(roles/logging.logWriter)을 부여하여 허용 정책을 수정합니다.
  • 업데이트된 허용 정책을 작성합니다.
  • 프로젝트 수준에서 로그 작성자 역할(roles/logging.logWriter)이 있는 모든 주 구성원을 출력합니다.
  • 로그 작성자 역할을 취소합니다.

코드 스니펫을 실행하기 전에 다음 값을 바꿉니다.

  • your-project: 프로젝트의 ID입니다.
  • your-member: Google 계정의 이메일 주소(프리픽스 user:)입니다. 예를 들면 user:tanya@example.com입니다.

C#

Resource Manager에 대해 클라이언트 라이브러리를 설치하고 사용하는 방법은 Resource Manager 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Resource Manager C# API 참조 문서를 확인하세요.

Resource Manager에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

Resource Manager에 대해 클라이언트 라이브러리를 설치하고 사용하는 방법은 Resource Manager 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Resource Manager Go API 참조 문서를 확인하세요.

Resource Manager에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

Resource Manager에 대해 클라이언트 라이브러리를 설치하고 사용하는 방법은 Resource Manager 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Resource Manager Java API 참조 문서를 확인하세요.

Resource Manager에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.ServiceAccountName;
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 com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Quickstart {

  public static void main(String[] args) throws IOException {
    // TODO: Replace with your project ID.
    String projectId = "your-project";
    // TODO: Replace with your service account name.
    String serviceAccount = "your-service-account";
    // 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";

    quickstart(projectId, serviceAccount, member, role);
  }

  // Creates new policy and adds binding.
  // Checks if changes are present and removes policy.
  public static void quickstart(String projectId, String serviceAccount,
                                String member, String role) throws IOException {

    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to delete the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#deleting

    serviceAccount = serviceAccount + "@" + projectId + ".iam.gserviceaccount.com";

    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    try (IAMClient iamClient = IAMClient.create()) {

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

      // Get the project's policy and print all members with the "Log Writer" role
      Policy policy = getPolicy(iamClient, projectId, serviceAccount);

      Binding binding = null;
      List<Binding> bindings = policy.getBindingsList();

      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.getMembersList()) {
        System.out.print("[" + m + "] ");
      }
      System.out.println();

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

  public static void addBinding(IAMClient iamClient, String projectId, String serviceAccount,
                                String member, String role) {
    // Gets the project's policy.
    Policy policy = getPolicy(iamClient, projectId, serviceAccount);

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

    Policy.Builder updatedPolicy = policy.toBuilder();

    // Get the binding if present in the policy.
    Binding binding = null;
    for (Binding b : updatedPolicy.getBindingsList()) {
      if (b.getRole().equals(role)) {
        binding = b;
        break;
      }
    }

    if (binding != null) {
      // If binding already exists, adds member to binding.
      binding.getMembersList().add(member);
    } else {
      // If binding does not exist, adds binding to policy.
      binding = Binding.newBuilder()
              .setRole(role)
              .addMembers(member)
              .build();
      updatedPolicy.addBindings(binding);
    }

    // Sets the updated policy.
    setPolicy(iamClient, projectId, serviceAccount, updatedPolicy.build());
  }

  public static void removeMember(IAMClient iamClient, String projectId, String serviceAccount,
                                  String member, String role) {
    // Gets the project's policy.
    Policy.Builder policy = getPolicy(iamClient, projectId, serviceAccount).toBuilder();

    // Removes the member from the role.
    Binding binding = null;
    for (Binding b : policy.getBindingsList()) {
      if (b.getRole().equals(role)) {
        binding = b;
        break;
      }
    }

    if (binding != null && binding.getMembersList().contains(member)) {
      List<String> newMemberList = new ArrayList<>(binding.getMembersList());
      newMemberList.remove(member);

      Binding newBinding = binding.toBuilder().clearMembers()
              .addAllMembers(newMemberList)
              .build();
      List<Binding> newBindingList = new ArrayList<>(policy.getBindingsList());
      newBindingList.remove(binding);

      if (!newBinding.getMembersList().isEmpty()) {
        newBindingList.add(newBinding);
      }

      policy.clearBindings()
              .addAllBindings(newBindingList);
    }

    // Sets the updated policy.
    setPolicy(iamClient, projectId, serviceAccount, policy.build());
  }

  public static Policy getPolicy(IAMClient iamClient, String projectId, String serviceAccount) {
    // Gets the project's policy by calling the
    // IAMClient API.
    GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder()
            .setResource(ServiceAccountName.of(projectId, serviceAccount).toString())
            .build();
    return iamClient.getIamPolicy(request);
  }

  private static void setPolicy(IAMClient iamClient, String projectId,
                                String serviceAccount, Policy policy) {
    List<String> paths = Arrays.asList("bindings", "etag");
    // Sets a project's policy.
    SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder()
            .setResource(ServiceAccountName.of(projectId, serviceAccount).toString())
            .setPolicy(policy)
            // A FieldMask specifying which fields of the policy to modify. Only
            // the fields in the mask will be modified. If no mask is provided, the
            // following default mask is used:
            // `paths: "bindings, etag"`
            .setUpdateMask(FieldMask.newBuilder().addAllPaths(paths).build())
            .build();
    iamClient.setIamPolicy(request);
  }
}

Python

Resource Manager에 대해 클라이언트 라이브러리를 설치하고 사용하는 방법은 Resource Manager 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Resource Manager Python API 참조 문서를 확인하세요.

Resource Manager에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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)

수고하셨습니다 Resource Manager API의 IAM 메서드를 사용하여 프로젝트의 액세스 권한을 수정했습니다.

어땠나요?

삭제

  1. Optional: Revoke the authentication credentials that you created, and delete the local credential file.

    gcloud auth application-default revoke
  2. Optional: Revoke credentials from the gcloud CLI.

    gcloud auth revoke

다음 단계