IAM 권한 사용

개요

이 페이지는 Identity and Access Management(IAM) 권한을 통해 버킷, 관리 폴더, 객체에 대한 액세스를 제어하는 방법을 설명합니다. IAM을 사용하면 버킷, 관리 폴더, 객체에 액세스할 수 있는 사용자를 제어할 수 있습니다.

버킷, 관리 폴더, 객체에 대한 액세스를 제어하는 다른 방법은 액세스 제어 개요를 참조하세요. 버킷의 개별 객체에 대한 액세스를 제어하는 방법은 액세스 제어 목록을 참조하세요.

버킷에 IAM 사용

다음 섹션은 버킷에서 기본 IAM 작업을 완료하는 방법을 설명합니다.

필요한 역할

버킷의 IAM 정책을 설정하고 관리하는 데 필요한 권한을 얻으려면 관리자에게 버킷의 스토리지 관리자(roles/storage.admin) IAM 역할을 부여해 달라고 요청하세요.

이 역할에는 버킷의 IAM 정책을 설정하고 관리하는 데 필요한 다음 권한이 포함됩니다.

  • storage.buckets.get

  • storage.buckets.getIamPolicy

  • storage.buckets.setIamPolicy

  • storage.buckets.update

  • storage.buckets.list

    • 이 권한은 Google Cloud 콘솔을 사용하여 이 페이지의 태스크를 수행하려는 경우에만 필요합니다.

커스텀 역할로도 이러한 권한을 얻을 수 있습니다.

버킷 수준 정책에 주 구성원 추가

Cloud Storage와 관련된 역할 목록은 IAM 역할을 참조하세요. IAM 역할을 부여하는 항목에 대한 자세한 내용은 주 구성원 식별자를 참조하세요.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 주 구성원에게 역할을 부여할 버킷의 이름을 클릭합니다.

  3. 페이지 상단의 권한 탭을 선택합니다.

  4. 액세스 권한 부여 버튼을 클릭합니다.

    주 구성원 추가 대화상자가 나타납니다.

  5. 새 주 구성원 필드에 버킷에 액세스해야 하는 ID를 한 개 이상 입력합니다.

  6. 역할 선택 드롭다운 메뉴에서 역할을 한 개 이상 선택합니다. 선택한 역할 및 부여되는 권한에 대한 간단한 설명이 창에 표시됩니다.

  7. 저장을 클릭합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

buckets add-iam-policy-binding 명령어를 사용합니다.

gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME --member=PRINCIPAL_IDENTIFIER --role=IAM_ROLE

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 주 구성원에게 액세스 권한을 부여할 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • PRINCIPAL_IDENTIFIER는 버킷 액세스 권한을 부여할 개발자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

  • IAM_ROLE은 주 구성원에게 부여할 IAM 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& member) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));

  if (!policy) throw std::move(policy).status();

  policy->set_version(3);
  for (auto& binding : policy->bindings()) {
    if (binding.role() != role || binding.has_condition()) {
      continue;
    }
    auto& members = binding.members();
    if (std::find(members.begin(), members.end(), member) == members.end()) {
      members.emplace_back(member);
    }
  }

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::move(updated).status();

  std::cout << "Updated IAM policy bucket " << bucket_name
            << ". The new policy is " << *updated << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class AddBucketIamMemberSample
{
    public Policy AddBucketIamMember(
        string bucketName = "your-unique-bucket-name",
        string role = "roles/storage.objectViewer",
        string member = "serviceAccount:dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });
        // Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
        policy.Version = 3;

        Policy.BindingsData bindingToAdd = new Policy.BindingsData
        {
            Role = role,
            Members = new List<string> { member }
        };

        policy.Bindings.Add(bindingToAdd);
        var bucketIamPolicy = storage.SetBucketIamPolicy(bucketName, policy);
        Console.WriteLine($"Added {member} with role {role} " + $"to {bucketName}");
        return bucketIamPolicy;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/storage"
)

// addBucketIAMMember adds the bucket IAM member to permission role.
func addBucketIAMMember(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	policy, err := bucket.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).IAM().Policy: %w", bucketName, err)
	}
	// Other valid prefixes are "serviceAccount:", "user:"
	// See the documentation for more values.
	// https://cloud.google.com/storage/docs/access-control/iam
	identity := "group:cloud-logs@google.com"
	var role iam.RoleName = "roles/storage.objectViewer"

	policy.Add(identity, role)
	if err := bucket.IAM().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("Bucket(%q).IAM().SetPolicy: %w", bucketName, err)
	}
	// NOTE: It may be necessary to retry this operation if IAM policies are
	// being modified concurrently. SetPolicy will return an error if the policy
	// was modified since it was retrieved.
	fmt.Fprintf(w, "Added %v with role %v to %v\n", identity, role, bucketName)
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

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


import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AddBucketIamMember {
  /** Example of adding a member to the Bucket-level IAM */
  public static void addBucketIamMember(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";
    String member = "group:example@google.com";

    // getBindingsList() returns an ImmutableList and copying over to an ArrayList so it's mutable.
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Create a new binding using role and member
    Binding.Builder newMemberBindingBuilder = Binding.newBuilder();
    newMemberBindingBuilder.setRole(role).setMembers(Arrays.asList(member));
    bindings.add(newMemberBindingBuilder.build());

    // Update policy to add member
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);
    Policy updatedPolicy = storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.printf("Added %s with role %s to %s\n", member, role, bucketName);
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The role to grant
// const roleName = 'roles/storage.objectViewer';

// The members to grant the new role to
// const members = [
//   'user:jdoe@example.com',
//   'group:admins@example.com',
// ];

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function addBucketIamMember() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // For more information please read:
  // https://cloud.google.com/storage/docs/access-control/iam
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Adds the new roles to the bucket's IAM policy
  policy.bindings.push({
    role: roleName,
    members: members,
  });

  // Updates the bucket's IAM policy
  await bucket.iam.setPolicy(policy);

  console.log(
    `Added the following member(s) with role ${roleName} to ${bucketName}:`
  );

  members.forEach(member => {
    console.log(`  ${member}`);
  });
}

addBucketIamMember().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

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

use Google\Cloud\Storage\StorageClient;

/**
 * Adds a new member / role IAM pair to a given Cloud Storage bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $role The role to which the given member should be added.
 *        (e.g. 'roles/storage.objectViewer')
 * @param string[] $members The member(s) to be added to the role.
 *        (e.g. ['group:example@google.com'])
 */
function add_bucket_iam_member(string $bucketName, string $role, array $members): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);
    $policy['version'] = 3;

    $policy['bindings'][] = [
        'role' => $role,
        'members' => $members
    ];

    $bucket->iam()->setPolicy($policy);

    printf('Added the following member(s) to role %s for bucket %s' . PHP_EOL, $role, $bucketName);
    foreach ($members as $member) {
        printf('    %s' . PHP_EOL, $member);
    }
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

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

from google.cloud import storage


def add_bucket_iam_member(bucket_name, role, member):
    """Add a new member to an IAM Policy"""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g., roles/storage.objectViewer"
    # member = "IAM identity, e.g., user: name@example.com"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    policy.bindings.append({"role": role, "members": {member}})

    bucket.set_iam_policy(policy)

    print(f"Added {member} with role {role} to {bucket_name}.")

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

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

def add_bucket_iam_member bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  role   = "roles/storage.objectViewer"
  member = "group:example@google.com"

  bucket.policy requested_policy_version: 3 do |policy|
    policy.bindings.insert role: role, members: [member]
  end

  puts "Added #{member} with role #{role} to #{bucket_name}"
end

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 다음 정보를 포함하는 JSON 파일을 만듭니다.

    {
    "bindings":[
      {
        "role": "IAM_ROLE",
        "members":[
          "PRINCIPAL_IDENTIFIER"
        ]
      }
    ]
    }

    각 항목의 의미는 다음과 같습니다.

    • IAM_ROLE은 부여할 IAM 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

    • PRINCIPAL_IDENTIFIER는 버킷 액세스 권한을 부여할 개발자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

  3. cURL을 사용하여 PUT setIamPolicy 요청으로 JSON API를 호출합니다.

    curl -X PUT --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • JSON_FILE_NAME은 2단계에서 만든 파일의 경로입니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 주 구성원에게 액세스 권한을 부여할 버킷의 이름입니다. 예를 들면 my-bucket입니다.

버킷에 대한 IAM 정책 보기

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 확인하려는 정책의 버킷 이름을 클릭합니다.

  3. 버킷 세부정보 페이지에서 권한 탭을 클릭합니다.

    버킷에 적용되는 IAM 정책이 권한 섹션에 표시됩니다.

  4. 선택사항: 필터 막대를 사용해서 결과를 필터링합니다.

    주 구성원별로 검색하면 주 구성원이 부여된 각 역할이 결과에 표시됩니다.

명령줄

buckets get-iam-policy 명령어를 사용합니다.

gcloud storage buckets get-iam-policy gs://BUCKET_NAME

여기서 BUCKET_NAME은 확인하려는 IAM 정책의 버킷 이름입니다. 예를 들면 my-bucket입니다.

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));

  if (!policy) throw std::move(policy).status();
  std::cout << "The IAM policy for bucket " << bucket_name << " is "
            << *policy << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class ViewBucketIamMembersSample
{
    public Policy ViewBucketIamMembers(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });

        foreach (var binding in policy.Bindings)
        {
            Console.WriteLine($"Role: {binding.Role}");
            Console.WriteLine("Members:");
            foreach (var member in binding.Members)
            {
                Console.WriteLine($"{member}");
            }
        }
        return policy;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/storage"
)

// getBucketPolicy gets the bucket IAM policy.
func getBucketPolicy(w io.Writer, bucketName string) (*iam.Policy3, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	policy, err := client.Bucket(bucketName).IAM().V3().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Bucket(%q).IAM().V3().Policy: %w", bucketName, err)
	}
	for _, binding := range policy.Bindings {
		fmt.Fprintf(w, "%q: %q (condition: %v)\n", binding.Role, binding.Members, binding.Condition)
	}
	return policy, nil
}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

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

import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListBucketIamMembers {
  public static void listBucketIamMembers(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy policy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    // Print binding information
    for (Binding binding : policy.getBindingsList()) {
      System.out.printf("Role: %s Members: %s\n", binding.getRole(), binding.getMembers());

      // Print condition if one is set
      boolean bindingIsConditional = binding.getCondition() != null;
      if (bindingIsConditional) {
        System.out.printf("Condition Title: %s\n", binding.getCondition().getTitle());
        System.out.printf("Condition Description: %s\n", binding.getCondition().getDescription());
        System.out.printf("Condition Expression: %s\n", binding.getCondition().getExpression());
      }
    }
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function viewBucketIamMembers() {
  // For more information please read:
  // https://cloud.google.com/storage/docs/access-control/iam
  const results = await storage
    .bucket(bucketName)
    .iam.getPolicy({requestedPolicyVersion: 3});

  const bindings = results[0].bindings;

  console.log(`Bindings for bucket ${bucketName}:`);
  for (const binding of bindings) {
    console.log(`  Role: ${binding.role}`);
    console.log('  Members:');

    const members = binding.members;
    for (const member of members) {
      console.log(`    ${member}`);
    }

    const condition = binding.condition;
    if (condition) {
      console.log('  Condition:');
      console.log(`    Title: ${condition.title}`);
      console.log(`    Description: ${condition.description}`);
      console.log(`    Expression: ${condition.expression}`);
    }
  }
}

viewBucketIamMembers().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

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

use Google\Cloud\Storage\StorageClient;

/**
 * View Bucket IAM members for a given Cloud Storage bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function view_bucket_iam_members(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);

    printf('Printing Bucket IAM members for Bucket: %s' . PHP_EOL, $bucketName);
    printf(PHP_EOL);

    foreach ($policy['bindings'] as $binding) {
        printf('Role: %s' . PHP_EOL, $binding['role']);
        printf('Members:' . PHP_EOL);
        foreach ($binding['members'] as $member) {
            printf('  %s' . PHP_EOL, $member);
        }

        if (isset($binding['condition'])) {
            $condition = $binding['condition'];
            printf('  with condition:' . PHP_EOL);
            printf('    Title: %s' . PHP_EOL, $condition['title']);
            printf('    Description: %s' . PHP_EOL, $condition['description']);
            printf('    Expression: %s' . PHP_EOL, $condition['expression']);
        }
        printf(PHP_EOL);
    }
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

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

from google.cloud import storage


def view_bucket_iam_members(bucket_name):
    """View IAM Policy for a bucket"""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    for binding in policy.bindings:
        print(f"Role: {binding['role']}, Members: {binding['members']}")

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

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

def view_bucket_iam_members bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  policy = bucket.policy requested_policy_version: 3
  policy.bindings.each do |binding|
    puts "Role: #{binding.role}"
    puts "Members: #{binding.members}"

    # if a conditional binding exists print the condition.
    if binding.condition
      puts "Condition Title: #{binding.condition.title}"
      puts "Condition Description: #{binding.condition.description}"
      puts "Condition Expression: #{binding.condition.expression}"
    end
  end
end

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET getIamPolicy 요청으로 JSON API를 호출합니다.

    curl -X GET \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 확인하려는 IAM 정책의 버킷 이름입니다. 예를 들면 my-bucket입니다.

버킷 수준 정책에서 주 구성원 삭제

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 주 구성원의 역할을 삭제하려는 버킷의 이름을 클릭합니다.

  3. 버킷 세부정보 페이지에서 권한 탭을 클릭합니다.

    버킷에 적용되는 IAM 정책이 권한 섹션에 표시됩니다.

  4. 주 구성원별 보기 탭에서 삭제하려는 주 구성원에 해당하는 체크박스를 선택합니다.

  5. - 액세스 삭제 버튼을 클릭합니다.

  6. 나타나는 오버레이 창에서 확인을 클릭합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

buckets remove-iam-policy-binding 명령어를 사용합니다.

gcloud storage buckets remove-iam-policy-binding  gs://BUCKET_NAME --member=PRINCIPAL_IDENTIFIER --role=IAM_ROLE

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 액세스 권한을 취소하려는 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • PRINCIPAL_IDENTIFIER는 액세스 권한을 취소할 사용자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

  • IAM_ROLE은 취소할 IAM 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& member) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!policy) throw std::move(policy).status();

  policy->set_version(3);
  std::vector<google::cloud::storage::NativeIamBinding> updated_bindings;
  for (auto& binding : policy->bindings()) {
    auto& members = binding.members();
    if (binding.role() == role && !binding.has_condition()) {
      members.erase(std::remove(members.begin(), members.end(), member),
                    members.end());
    }
    if (!members.empty()) {
      updated_bindings.emplace_back(std::move(binding));
    }
  }
  policy->bindings() = std::move(updated_bindings);

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::move(updated).status();

  std::cout << "Updated IAM policy bucket " << bucket_name
            << ". The new policy is " << *updated << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

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


using Google.Cloud.Storage.V1;
using System;
using System.Linq;

public class RemoveBucketIamMemberSample
{
    public void RemoveBucketIamMember(
        string bucketName = "your-unique-bucket-name",
        string role = "roles/storage.objectViewer",
        string member = "serviceAccount:dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });
        // Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
        policy.Version = 3;

        foreach (var binding in policy.Bindings.Where(c => c.Role == role).ToList())
        {
            // Remove the role/member combo from the IAM policy.
            binding.Members = binding.Members.Where(m => m != member).ToList();
            // Remove role if it contains no members.
            if (binding.Members.Count == 0)
            {
                policy.Bindings.Remove(binding);
            }
        }
        // Set the modified IAM policy to be the current IAM policy.
        storage.SetBucketIamPolicy(bucketName, policy);
        Console.WriteLine($"Removed {member} with role {role} from {bucketName}");
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/storage"
)

// removeBucketIAMMember removes the bucket IAM member.
func removeBucketIAMMember(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	policy, err := bucket.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).IAM().Policy: %w", bucketName, err)
	}
	// Other valid prefixes are "serviceAccount:", "user:"
	// See the documentation for more values.
	// https://cloud.google.com/storage/docs/access-control/iam
	// member string, role iam.RoleName
	identity := "group:cloud-logs@google.com"
	var role iam.RoleName = "roles/storage.objectViewer"

	policy.Remove(identity, role)
	if err := bucket.IAM().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("Bucket(%q).IAM().SetPolicy: %w", bucketName, err)
	}
	// NOTE: It may be necessary to retry this operation if IAM policies are
	// being modified concurrently. SetPolicy will return an error if the policy
	// was modified since it was retrieved.
	fmt.Fprintf(w, "Removed %v with role %v from %v\n", identity, role, bucketName)
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

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


import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.List;

public class RemoveBucketIamMember {
  public static void removeBucketIamMember(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";
    String member = "group:example@google.com";

    // getBindingsList() returns an ImmutableList and copying over to an ArrayList so it's mutable.
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Remove role-member binding without a condition.
    for (int index = 0; index < bindings.size(); index++) {
      Binding binding = bindings.get(index);
      boolean foundRole = binding.getRole().equals(role);
      boolean foundMember = binding.getMembers().contains(member);
      boolean bindingIsNotConditional = binding.getCondition() == null;

      if (foundRole && foundMember && bindingIsNotConditional) {
        bindings.set(index, binding.toBuilder().removeMembers(member).build());
        break;
      }
    }

    // Update policy to remove member
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);
    Policy updatedPolicy = storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.printf("Removed %s with role %s from %s\n", member, role, bucketName);
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The role to revoke
// const roleName = 'roles/storage.objectViewer';

// The members to revoke the roles from
// const members = [
//   'user:jdoe@example.com',
//   'group:admins@example.com',
// ];

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function removeBucketIamMember() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // For more information please read:
  // https://cloud.google.com/storage/docs/access-control/iam
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Finds and updates the appropriate role-member group, without a condition.
  const index = policy.bindings.findIndex(
    binding => binding.role === roleName && !binding.condition
  );

  const role = policy.bindings[index];
  if (role) {
    role.members = role.members.filter(
      member => members.indexOf(member) === -1
    );

    // Updates the policy object with the new (or empty) role-member group
    if (role.members.length === 0) {
      policy.bindings.splice(index, 1);
    } else {
      policy.bindings.index = role;
    }

    // Updates the bucket's IAM policy
    await bucket.iam.setPolicy(policy);
  } else {
    // No matching role-member group(s) were found
    throw new Error('No matching role-member group(s) found.');
  }

  console.log(
    `Removed the following member(s) with role ${roleName} from ${bucketName}:`
  );
  members.forEach(member => {
    console.log(`  ${member}`);
  });
}

removeBucketIamMember().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

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

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a member / role IAM pair from a given Cloud Storage bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $role The role from which the specified member should be removed.
 *        (e.g. 'roles/storage.objectViewer')
 * @param string $member The member to be removed from the specified role.
 *        (e.g. 'group:example@google.com')
 */
function remove_bucket_iam_member(string $bucketName, string $role, string $member): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $iam = $bucket->iam();
    $policy = $iam->policy(['requestedPolicyVersion' => 3]);
    $policy['version'] = 3;

    foreach ($policy['bindings'] as $i => $binding) {
        // This example only removes member from bindings without a condition.
        if ($binding['role'] == $role && !isset($binding['condition'])) {
            $key = array_search($member, $binding['members']);
            if ($key !== false) {
                unset($binding['members'][$key]);

                // If the last member is removed from the binding, clean up the
                // binding.
                if (count($binding['members']) == 0) {
                    unset($policy['bindings'][$i]);
                    // Ensure array keys are sequential, otherwise JSON encodes
                    // the array as an object, which fails when calling the API.
                    $policy['bindings'] = array_values($policy['bindings']);
                } else {
                    // Ensure array keys are sequential, otherwise JSON encodes
                    // the array as an object, which fails when calling the API.
                    $binding['members'] = array_values($binding['members']);
                    $policy['bindings'][$i] = $binding;
                }

                $iam->setPolicy($policy);
                printf('User %s removed from role %s for bucket %s' . PHP_EOL, $member, $role, $bucketName);
                return;
            }
        }
    }

    throw new \RuntimeException('No matching role-member group(s) found.');
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

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

from google.cloud import storage


def remove_bucket_iam_member(bucket_name, role, member):
    """Remove member from bucket IAM Policy"""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # member = "IAM identity, e.g. user: name@example.com"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    for binding in policy.bindings:
        print(binding)
        if binding["role"] == role and binding.get("condition") is None:
            binding["members"].discard(member)

    bucket.set_iam_policy(policy)

    print(f"Removed {member} with role {role} from {bucket_name}.")

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

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

def remove_bucket_iam_member bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # For more information please read: https://cloud.google.com/storage/docs/access-control/iam

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  role   = "roles/storage.objectViewer"
  member = "group:example@google.com"

  bucket.policy requested_policy_version: 3 do |policy|
    policy.bindings.each do |binding|
      if binding.role == role && binding.condition.nil?
        binding.members.delete member
      end
    end
  end

  puts "Removed #{member} with role #{role} from #{bucket_name}"
end

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 버킷에 적용된 기존 정책을 가져옵니다. 이렇게 하려면 cURL을 사용하여 GET getIamPolicy 요청으로 JSON API를 호출합니다.

    curl -X GET \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • BUCKET_NAME은 확인하려는 IAM 정책의 버킷 이름입니다. 예를 들면 my-bucket입니다.
  3. 이전 단계에서 검색한 정책을 포함하는 JSON 파일을 만듭니다.

  4. JSON 파일을 편집하여 정책에서 주 구성원을 삭제합니다.

  5. cURL을 사용하여 PUT setIamPolicy 요청으로 JSON API를 호출합니다.

    curl -X PUT --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • JSON_FILE_NAME은 3단계에서 만든 파일의 경로입니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 액세스 권한을 삭제할 버킷의 이름입니다. 예를 들면 my-bucket입니다.

버킷에 IAM 조건 사용

다음 섹션에서는 버킷에서 IAM 조건을 추가하고 삭제하는 방법을 설명합니다. 버킷의 IAM 조건을 보려면 버킷에 대한 IAM 정책 보기를 참조하세요. Cloud Storage에 IAM 조건 사용에 대한 자세한 내용은 조건을 참조하세요.

조건을 추가하기 전에 버킷에 균일한 버킷 수준 액세스를 사용 설정해야 합니다.

버킷에 새 조건 설정

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 새 조건을 추가하려는 버킷의 이름을 클릭합니다.

  3. 버킷 세부정보 페이지에서 권한 탭을 클릭합니다.

    버킷에 적용되는 IAM 정책이 권한 섹션에 표시됩니다.

  4. + 액세스 권한 부여를 클릭합니다.

  5. 새 주 구성원에서 버킷에 대한 액세스 권한을 부여할 주 구성원을 입력합니다.

  6. 조건을 적용할 각 역할에 대해 다음을 수행합니다.

    1. 역할을 선택하여 주 구성원에게 부여합니다.

    2. 조건 추가를 클릭하여 조건 추가 양식을 엽니다.

    3. 조건의 제목을 작성합니다. 설명 필드는 선택사항입니다.

    4. 조건 빌더를 사용하여 조건을 시각적으로 빌드하거나 조건 편집기 탭을 사용하여 CEL 표현식을 입력합니다.

    5. 저장을 클릭하여 주 구성원 추가 양식으로 돌아갑니다. 여러 역할을 추가하려면 다른 역할 추가를 클릭합니다.

  7. 저장을 클릭합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

  1. 조건 title, 조건에 대한 속성 기반 논리 expression 및 선택적으로 조건에 대한 description을 포함하여 조건을 정의하는 JSON 또는 YAML 파일을 생성합니다.

    Cloud Storage는 날짜/시간,리소스 유형expression리소스 이름 속성만을 지원합니다.

  2. --condition-from-file 플래그와 함께 buckets add-iam-policy-binding 명령어를 사용합니다.

gcloud storage buckets add-iam-policy-binding  gs://BUCKET_NAME --member=PRINCIPAL_IDENTIFIER --role=IAM_ROLE --condition-from-file=CONDITION_FILE

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 주 구성원에게 액세스 권한을 부여할 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • PRINCIPAL_IDENTIFIER는 조건이 적용되는 사용자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

  • IAM_ROLE은 주 구성원에게 부여할 IAM 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

  • CONDITION_FILE은 이전 단계에서 만든 파일입니다.

또는 --condition-from-file 플래그 대신 --condition 플래그를 사용하여 명령어에 조건을 직접 포함할 수 있습니다.

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& member,
   std::string const& condition_title,
   std::string const& condition_description,
   std::string const& condition_expression) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!policy) throw std::move(policy).status();

  policy->set_version(3);
  policy->bindings().emplace_back(gcs::NativeIamBinding(
      role, {member},
      gcs::NativeExpression(condition_expression, condition_title,
                            condition_description)));

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::move(updated).status();

  std::cout << "Updated IAM policy bucket " << bucket_name
            << ". The new policy is " << *updated << "\n";

  std::cout << "Added member " << member << " with role " << role << " to "
            << bucket_name << ":\n";
  std::cout << "with condition:\n"
            << "\t Title: " << condition_title << "\n"
            << "\t Description: " << condition_description << "\n"
            << "\t Expression: " << condition_expression << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class AddBucketConditionalIamBindingSample
{
    /// <summary>
    /// Adds a conditional Iam policy to a bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="role">The role that members may assume.</param>
    /// <param name="member">The identifier of the member who may assume the provided role.</param>
    /// <param name="title">Title for the expression.</param>
    /// <param name="description">Description of the expression.</param>
    /// <param name="expression">Describes the conditions that need to be met for the policy to be applied.
    /// It's represented as a string using Common Expression Language syntax.</param>
    public Policy AddBucketConditionalIamBinding(
        string bucketName = "your-unique-bucket-name",
        string role = "roles/storage.objectViewer",
        string member = "serviceAccount:dev@iam.gserviceaccount.com",
        string title = "title",
        string description = "description",
        string expression = "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")")
    {
        var storage = StorageClient.Create();
        var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });
        // Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
        policy.Version = 3;
        Policy.BindingsData bindingToAdd = new Policy.BindingsData
        {
            Role = role,
            Members = new List<string> { member },
            Condition = new Expr
            {
                Title = title,
                Description = description,
                Expression = expression
            }
        };

        policy.Bindings.Add(bindingToAdd);

        var bucketIamPolicy = storage.SetBucketIamPolicy(bucketName, policy);
        Console.WriteLine($"Added {member} with role {role} " + $"to {bucketName}");
        return bucketIamPolicy;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

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

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
bucket := c.Bucket(bucketName)
policy, err := bucket.IAM().V3().Policy(ctx)
if err != nil {
	return err
}

policy.Bindings = append(policy.Bindings, &iampb.Binding{
	Role:    role,
	Members: []string{member},
	Condition: &expr.Expr{
		Title:       title,
		Description: description,
		Expression:  expression,
	},
})

if err := bucket.IAM().V3().SetPolicy(ctx, policy); err != nil {
	return err
}
// NOTE: It may be necessary to retry this operation if IAM policies are
// being modified concurrently. SetPolicy will return an error if the policy
// was modified since it was retrieved.

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

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


import com.google.cloud.Binding;
import com.google.cloud.Condition;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AddBucketIamConditionalBinding {
  /** Example of adding a conditional binding to the Bucket-level IAM */
  public static void addBucketIamConditionalBinding(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";
    String member = "group:example@google.com";

    // Create a condition
    String conditionTitle = "Title";
    String conditionDescription = "Description";
    String conditionExpression =
        "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")";
    Condition.Builder conditionBuilder = Condition.newBuilder();
    conditionBuilder.setTitle(conditionTitle);
    conditionBuilder.setDescription(conditionDescription);
    conditionBuilder.setExpression(conditionExpression);

    // getBindingsList() returns an ImmutableList, we copy over to an ArrayList so it's mutable
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Add condition to a binding
    Binding.Builder newBindingBuilder =
        Binding.newBuilder()
            .setRole(role)
            .setMembers(Arrays.asList(member))
            .setCondition(conditionBuilder.build());
    bindings.add(newBindingBuilder.build());

    // Update policy with new conditional binding
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);

    storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.printf(
        "Added %s with role %s to %s with condition %s %s %s\n",
        member, role, bucketName, conditionTitle, conditionDescription, conditionExpression);
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The role to grant
// const roleName = 'roles/storage.objectViewer';

// The members to grant the new role to
// const members = [
//   'user:jdoe@example.com',
//   'group:admins@example.com',
// ];

// Create a condition
// const title = 'Title';
// const description = 'Description';
// const expression = 'resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function addBucketConditionalBinding() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // Gets and updates the bucket's IAM policy
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Set the policy's version to 3 to use condition in bindings.
  policy.version = 3;

  // Adds the new roles to the bucket's IAM policy
  policy.bindings.push({
    role: roleName,
    members: members,
    condition: {
      title: title,
      description: description,
      expression: expression,
    },
  });

  // Updates the bucket's IAM policy
  await bucket.iam.setPolicy(policy);

  console.log(
    `Added the following member(s) with role ${roleName} to ${bucketName}:`
  );

  members.forEach(member => {
    console.log(`  ${member}`);
  });

  console.log('with condition:');
  console.log(`  Title: ${title}`);
  console.log(`  Description: ${description}`);
  console.log(`  Expression: ${expression}`);
}

addBucketConditionalBinding().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

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

use Google\Cloud\Storage\StorageClient;

/**
 * Adds a conditional IAM binding to a bucket's IAM policy.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $role The role that will be given to members in this binding.
 *        (e.g. 'roles/storage.objectViewer')
 * @param string[] $members The member(s) associated with this binding.
 *        (e.g. ['group:example@google.com'])
 * @param string $title The title of the condition. (e.g. 'Title')
 * @param string $description The description of the condition.
 *        (e.g. 'Condition Description')
 * @param string $expression The condition specified in CEL expression language.
 *        (e.g. 'resource.name.startsWith("projects/_/buckets/bucket-name/objects/prefix-a-")')
 *
 * To see how to express a condition in CEL, visit:
 * @see https://cloud.google.com/storage/docs/access-control/iam#conditions.
 */
function add_bucket_conditional_iam_binding(string $bucketName, string $role, array $members, string $title, string $description, string $expression): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);

    $policy['version'] = 3;

    $policy['bindings'][] = [
        'role' => $role,
        'members' => $members,
        'condition' => [
            'title' => $title,
            'description' => $description,
            'expression' => $expression,
        ],
    ];

    $bucket->iam()->setPolicy($policy);

    printf('Added the following member(s) with role %s to %s:' . PHP_EOL, $role, $bucketName);
    foreach ($members as $member) {
        printf('    %s' . PHP_EOL, $member);
    }
    printf('with condition:' . PHP_EOL);
    printf('    Title: %s' . PHP_EOL, $title);
    printf('    Description: %s' . PHP_EOL, $description);
    printf('    Expression: %s' . PHP_EOL, $expression);
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

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

from google.cloud import storage


def add_bucket_conditional_iam_binding(
    bucket_name, role, title, description, expression, members
):
    """Add a conditional IAM binding to a bucket's IAM policy."""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # members = {"IAM identity, e.g. user: name@example.com}"
    # title = "Condition title."
    # description = "Condition description."
    # expression = "Condition expression."

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    # Set the policy's version to 3 to use condition in bindings.
    policy.version = 3

    policy.bindings.append(
        {
            "role": role,
            "members": members,
            "condition": {
                "title": title,
                "description": description,
                "expression": expression,
            },
        }
    )

    bucket.set_iam_policy(policy)

    print(f"Added the following member(s) with role {role} to {bucket_name}:")

    for member in members:
        print(f"    {member}")

    print("with condition:")
    print(f"    Title: {title}")
    print(f"    Description: {description}")
    print(f"    Expression: {expression}")

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

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

def add_bucket_conditional_iam_binding bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  role        = "roles/storage.objectViewer"
  member      = "group:example@google.com"
  title       = "Title"
  description = "Description"
  expression  = "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")"

  bucket.policy requested_policy_version: 3 do |policy|
    policy.version = 3
    policy.bindings.insert(
      role:      role,
      members:   member,
      condition: {
        title:       title,
        description: description,
        expression:  expression
      }
    )
  end

  puts "Added #{member} with role #{role} to #{bucket_name} with condition #{title} #{description} #{expression}"
end

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. GET getIamPolicy 요청을 사용하여 버킷의 IAM 정책을 임시 JSON 파일에 저장합니다.

    curl \
    'https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam' \
    --header 'Authorization: Bearer OAUTH2_TOKEN' > tmp-policy.json

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
  3. 텍스트 편집기에서 tmp-policy.json 파일을 수정하여 IAM 정책의 바인딩에 새 조건을 추가합니다.

    {
        "version": VERSION,
        "bindings": [
          {
            "role": "IAM_ROLE",
            "members": [
              "PRINCIPAL_IDENTIFIER"
            ],
            "condition": {
              "title": "TITLE",
              "description": "DESCRIPTION",
              "expression": "EXPRESSION"
            }
          }
        ],
        "etag": "ETAG"
    }

    각 항목의 의미는 다음과 같습니다.

    • VERSIONIAM 정책 버전으로, IAM 조건이 있는 버킷의 경우 3이어야 합니다.

    • IAM_ROLE은 조건이 적용되는 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

    • PRINCIPAL_IDENTIFIER는 조건이 적용되는 사용자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

    • TITLE은 조건의 제목입니다. 예를 들면 expires in 2019입니다.

    • DESCRIPTION은 선택사항으로, 조건의 설명입니다. 예를 들면 Permission revoked on New Year's입니다.

    • EXPRESSION속성 기반 논리 표현식입니다. 예를 들면 request.time < timestamp(\"2019-01-01T00:00:00Z\")입니다. 표현식의 더 많은 예시는 조건 속성 참조를 확인하세요. Cloud Storage는 날짜/시간, 리소스 유형, 리소스 이름 속성만을 지원합니다.

    ETAG는 수정하지 마세요.

  4. PUT setIamPolicy 요청을 사용하여 버킷에서 수정된 IAM 정책을 설정합니다.

    curl -X PUT --data-binary @tmp-policy.json \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

버킷에서 조건 삭제

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 조건을 삭제하려는 버킷의 이름을 클릭합니다.

  3. 버킷 세부정보 페이지에서 권한 탭을 클릭합니다.

    버킷에 적용되는 IAM 정책이 권한 섹션에 표시됩니다.

  4. 조건과 연결된 주 구성원의 수정 아이콘 을 클릭합니다.

  5. 나타나는 액세스 수정 오버레이에서 삭제할 조건의 이름을 클릭합니다.

  6. 나타나는 조건 수정 오버레이에서 삭제, 확인을 차례로 클릭합니다.

  7. 저장을 클릭합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

  1. buckets get-iam-policy 명령어를 사용하여 버킷의 IAM 정책을 임시 JSON 파일에 저장합니다.

    gcloud storage buckets get-iam-policy gs://BUCKET_NAME > tmp-policy.json
  2. 텍스트 편집기에서 tmp-policy.json 파일을 수정하여 IAM 정책에서 조건을 삭제합니다.

  3. buckets set-iam-policy을 사용하여 버킷에서 수정된 IAM 정책을 설정합니다.

    gcloud storage buckets set-iam-policy gs://BUCKET_NAME tmp-policy.json

코드 샘플

C++

자세한 내용은 Cloud Storage C++ API 참조 문서를 확인하세요.

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& condition_title,
   std::string const& condition_description,
   std::string const& condition_expression) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!policy) throw std::move(policy).status();

  policy->set_version(3);
  auto& bindings = policy->bindings();
  auto e = std::remove_if(
      bindings.begin(), bindings.end(),
      [role, condition_title, condition_description,
       condition_expression](gcs::NativeIamBinding b) {
        return (b.role() == role && b.has_condition() &&
                b.condition().title() == condition_title &&
                b.condition().description() == condition_description &&
                b.condition().expression() == condition_expression);
      });
  if (e == bindings.end()) {
    std::cout << "No matching binding group found.\n";
    return;
  }
  bindings.erase(e);
  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::move(updated).status();

  std::cout << "Conditional binding was removed.\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Linq;

public class RemoveBucketConditionalIamBindingSample
{
    public Policy RemoveBucketConditionalIamBinding(
        string bucketName = "your-unique-bucket-name",
        string role = "roles/storage.objectViewer",
        string title = "title",
        string description = "description",
        string expression = "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")")
    {
        var storage = StorageClient.Create();
        var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });
        // Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
        policy.Version = 3;

        var bindingsToRemove = policy.Bindings.Where(binding => binding.Role == role
              && binding.Condition != null
              && binding.Condition.Title == title
              && binding.Condition.Description == description
              && binding.Condition.Expression == expression).ToList();
        if (bindingsToRemove.Count() > 0)
        {
            foreach (var binding in bindingsToRemove)
            {
                policy.Bindings.Remove(binding);
            }
            // Set the modified IAM policy to be the current IAM policy.
            policy = storage.SetBucketIamPolicy(bucketName, policy);
            Console.WriteLine("Conditional Binding was removed.");
        }
        else
        {
            Console.WriteLine("No matching conditional binding found.");
        }
        return policy;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

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

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
bucket := c.Bucket(bucketName)
policy, err := bucket.IAM().V3().Policy(ctx)
if err != nil {
	return err
}

// Find the index of the binding matching inputs
i := -1
for j, binding := range policy.Bindings {
	if binding.Role == role && binding.Condition != nil {
		condition := binding.Condition
		if condition.Title == title &&
			condition.Description == description &&
			condition.Expression == expression {
			i = j
		}
	}
}

if i == -1 {
	return errors.New("No matching binding group found.")
}

// Get a slice of the bindings, removing the binding at index i
policy.Bindings = append(policy.Bindings[:i], policy.Bindings[i+1:]...)

if err := bucket.IAM().V3().SetPolicy(ctx, policy); err != nil {
	return err
}
// NOTE: It may be necessary to retry this operation if IAM policies are
// being modified concurrently. SetPolicy will return an error if the policy
// was modified since it was retrieved.

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

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


import com.google.cloud.Binding;
import com.google.cloud.Condition;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RemoveBucketIamConditionalBinding {
  /** Example of removing a conditional binding to the Bucket-level IAM */
  public static void removeBucketIamConditionalBinding(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";

    // getBindingsList() returns an ImmutableList and copying over to an ArrayList so it's mutable.
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Create a condition to compare against
    Condition.Builder conditionBuilder = Condition.newBuilder();
    conditionBuilder.setTitle("Title");
    conditionBuilder.setDescription("Description");
    conditionBuilder.setExpression(
        "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")");

    Iterator iterator = bindings.iterator();
    while (iterator.hasNext()) {
      Binding binding = (Binding) iterator.next();
      boolean foundRole = binding.getRole().equals(role);
      boolean conditionsEqual = conditionBuilder.build().equals(binding.getCondition());

      // Remove condition when the role and condition are equal
      if (foundRole && conditionsEqual) {
        iterator.remove();
        break;
      }
    }

    // Update policy to remove conditional binding
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);
    Policy updatedPolicy = storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.println("Conditional Binding was removed.");
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The role to grant
// const roleName = 'roles/storage.objectViewer';

// The members to grant the new role to
// const members = [
//   'user:jdoe@example.com',
//   'group:admins@example.com',
// ];

// Create a condition
// const title = 'Title';
// const description = 'Description';
// const expression = 'resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function removeBucketConditionalBinding() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // Gets and updates the bucket's IAM policy
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Set the policy's version to 3 to use condition in bindings.
  policy.version = 3;

  // Finds and removes the appropriate role-member group with specific condition.
  const index = policy.bindings.findIndex(
    binding =>
      binding.role === roleName &&
      binding.condition &&
      binding.condition.title === title &&
      binding.condition.description === description &&
      binding.condition.expression === expression
  );

  const binding = policy.bindings[index];
  if (binding) {
    policy.bindings.splice(index, 1);

    // Updates the bucket's IAM policy
    await bucket.iam.setPolicy(policy);

    console.log('Conditional Binding was removed.');
  } else {
    // No matching role-member group with specific condition were found
    throw new Error('No matching binding group found.');
  }
}

removeBucketConditionalBinding().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

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

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a conditional IAM binding from a bucket's IAM policy.
 *
 * To see how to express a condition in CEL, visit:
 * @see https://cloud.google.com/storage/docs/access-control/iam#conditions.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $role the role that will be given to members in this binding.
 *        (e.g. 'roles/storage.objectViewer')
 * @param string $title The title of the condition. (e.g. 'Title')
 * @param string $description The description of the condition.
 *        (e.g. 'Condition Description')
 * @param string $expression Te condition specified in CEL expression language.
 *        (e.g. 'resource.name.startsWith("projects/_/buckets/bucket-name/objects/prefix-a-")')
 */
function remove_bucket_conditional_iam_binding(string $bucketName, string $role, string $title, string $description, string $expression): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);

    $policy['version'] = 3;

    $key_of_conditional_binding = null;
    foreach ($policy['bindings'] as $key => $binding) {
        if ($binding['role'] == $role && isset($binding['condition'])) {
            $condition = $binding['condition'];
            if ($condition['title'] == $title
                 && $condition['description'] == $description
                 && $condition['expression'] == $expression) {
                $key_of_conditional_binding = $key;
                break;
            }
        }
    }

    if ($key_of_conditional_binding != null) {
        unset($policy['bindings'][$key_of_conditional_binding]);
        // Ensure array keys are sequential, otherwise JSON encodes
        // the array as an object, which fails when calling the API.
        $policy['bindings'] = array_values($policy['bindings']);
        $bucket->iam()->setPolicy($policy);
        print('Conditional Binding was removed.' . PHP_EOL);
    } else {
        print('No matching conditional binding found.' . PHP_EOL);
    }
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

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

from google.cloud import storage


def remove_bucket_conditional_iam_binding(
    bucket_name, role, title, description, expression
):
    """Remove a conditional IAM binding from a bucket's IAM policy."""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # title = "Condition title."
    # description = "Condition description."
    # expression = "Condition expression."

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    # Set the policy's version to 3 to use condition in bindings.
    policy.version = 3

    condition = {
        "title": title,
        "description": description,
        "expression": expression,
    }
    policy.bindings = [
        binding
        for binding in policy.bindings
        if not (binding["role"] == role and binding.get("condition") == condition)
    ]

    bucket.set_iam_policy(policy)

    print("Conditional Binding was removed.")

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

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

def remove_bucket_conditional_iam_binding bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  role        = "roles/storage.objectViewer"
  title       = "Title"
  description = "Description"
  expression  = "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")"

  bucket.policy requested_policy_version: 3 do |policy|
    policy.version = 3

    binding_to_remove = nil
    policy.bindings.each do |b|
      condition = {
        title:       title,
        description: description,
        expression:  expression
      }
      if (b.role == role) && (b.condition &&
        b.condition.title == title &&
        b.condition.description == description &&
        b.condition.expression == expression)
        binding_to_remove = b
      end
    end
    if binding_to_remove
      policy.bindings.remove binding_to_remove
      puts "Conditional Binding was removed."
    else
      puts "No matching conditional binding found."
    end
  end
end

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. GET getIamPolicy 요청을 사용하여 버킷의 IAM 정책을 임시 JSON 파일에 저장합니다.

    curl \
    'https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam' \
    --header 'Authorization: Bearer OAUTH2_TOKEN' > tmp-policy.json

    각 항목의 의미는 다음과 같습니다.

    • BUCKET_NAME은 액세스 권한을 부여할 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
  3. 텍스트 편집기에서 tmp-policy.json 파일을 수정하여 IAM 정책에서 조건을 삭제합니다.

  4. PUT setIamPolicy 요청을 사용하여 버킷에서 수정된 IAM 정책을 설정합니다.

    curl -X PUT --data-binary @tmp-policy.json \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 IAM 정책을 수정하려는 버킷의 이름입니다. 예를 들면 my-bucket입니다.

관리 폴더에 IAM 사용

다음 섹션에서는 관리 폴더에서 기본 IAM 태스크를 완료하는 방법을 보여줍니다.

필요한 역할

관리 폴더에 대한 IAM 정책을 설정하고 관리하는 데 필요한 권한을 얻으려면 관리자에게 관리 폴더가 포함된 버킷의 스토리지 기존 버킷 소유자(roles/storage.legacyBucketOwner) IAM 역할을 부여해 달라고 요청하세요.

이 역할에는 관리 폴더의 IAM 정책을 설정하고 관리하는 데 필요한 다음 권한이 포함되어 있습니다.

  • storage.managedfolders.getIamPolicy

  • storage.managedfolders.setIamPolicy

커스텀 역할로도 이러한 권한을 얻을 수 있습니다.

버킷의 역할 부여에 대한 자세한 내용은 버킷에 IAM 사용을 참조하세요.

관리 폴더에 IAM 정책 설정

Console

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 IAM 정책을 설정하려는 관리 폴더가 포함된 버킷의 이름을 클릭합니다.

  3. 버킷 세부정보 페이지의 IAM 정책을 설정하려는 관리형 폴더 옆에 있는 폴더 브라우저 창에서 옵션 더보기 아이콘 을 클릭합니다.

    액세스를 제어하려는 폴더가 시뮬레이션된 폴더이면 먼저 관리형 폴더 만들기의 단계를 수행하여 시뮬레이션된 폴더를 관리형 폴더로 변환합니다.

  4. 액세스 수정을 클릭합니다.

  5. MANAGED_FOLDER_NAME 권한 창에서 주 구성원 추가 를 클릭합니다.

  6. 새 주 구성원 필드에 액세스 권한을 부여할 주 구성원을 입력합니다. 포함할 수 있는 주 구성원에 대한 자세한 내용은 IAM 개요를 참조하세요.

  7. 역할 할당 섹션에서 역할 선택 드롭다운을 사용하여 주 구성원에게 부여할 액세스 권한 수준을 지정합니다.

  8. 저장을 클릭합니다.

명령줄

  1. 다음 정보를 포함하는 JSON 파일을 만듭니다.

    {
      "bindings":[
        {
          "role": "IAM_ROLE",
          "members":[
            "PRINCIPAL_IDENTIFIER"
          ]
        }
      ]
    }

    각 항목의 의미는 다음과 같습니다.

    • IAM_ROLE은 부여할 IAM 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

    • PRINCIPAL_IDENTIFIER는 관리 폴더 액세스 권한을 부여할 사용자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

  2. gcloud storage managed-folders set-iam-policy 명령어를 사용합니다.

    gcloud storage managed-folders set-iam-policy gs://BUCKET_NAME/MANAGED_FOLDER_NAME POLICY_FILE

    각 항목의 의미는 다음과 같습니다.

    • BUCKET_NAME은 IAM 정책을 적용하려는 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    • MANAGED_FOLDER_NAME은 IAM 정책을 적용하려는 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

    • POLICY_FILE은 1단계에서 만든 JSON 파일의 경로입니다.

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 다음 정보를 포함하는 JSON 파일을 만듭니다.

    {
      "bindings":[
        {
          "role": "IAM_ROLE",
          "members":[
            "PRINCIPAL_IDENTIFIER"
          ]
        }
      ]
    }

    각 항목의 의미는 다음과 같습니다.

    • IAM_ROLE은 부여할 IAM 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

    • PRINCIPAL_IDENTIFIER는 관리 폴더 액세스 권한을 부여할 사용자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

  3. cURL을 사용하여 PUT setIamPolicy 요청으로 JSON API를 호출합니다.

    curl -X PUT --data-binary @POLICY_FILE \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders/MANAGED_FOLDER_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • POLICY_FILE은 2단계에서 만든 JSON 정책 파일의 경로입니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 IAM 정책을 적용하려는 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    • MANAGED_FOLDER_NAME은 주 구성원에게 액세스 권한을 부여할 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

관리 폴더의 IAM 정책 보기

Console

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 IAM 정책을 보려는 관리형 폴더가 포함된 버킷의 이름을 클릭합니다.

  3. 버킷 세부정보 페이지의 IAM 정책을 보려는 관리형 폴더 옆에 있는 폴더 브라우저 창에서 옵션 더보기 아이콘 을 클릭합니다.

  4. 액세스 수정을 클릭합니다.

FOLDER_NAME 권한 창에는 주 구성원, 역할, 상속된 역할, IAM 조건을 포함하여 관리형 폴더에 대한 권한이 표시됩니다.

명령줄

gcloud storage managed-folder get-iam-policy 명령어를 사용합니다.

gcloud storage managed-folders get-iam-policy gs://BUCKET_NAME/MANAGED_FOLDER_NAME

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 IAM 정책을 보려는 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • MANAGED_FOLDER_NAME은 IAM 정책을 보려는 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET getIamPolicy 요청으로 JSON API를 호출합니다.

    curl -X GET \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders/MANAGED_FOLDER_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 IAM 정책을 보려는 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    • MANAGED_FOLDER_NAME은 IAM 정책을 보려는 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

관리 폴더 정책에서 주 구성원 삭제

다음 단계를 수행하여 상속된 IAM 정책에서 주 구성원을 삭제할 수 없습니다. 상속된 정책에서 주 구성원을 삭제하려면 정책이 있는 리소스를 식별하고 리소스에서 주 구성원을 삭제합니다. 예를 들어 주 구성원에게 관리형 폴더가 포함된 버킷에 대한 스토리지 객체 사용자(roles/storage.objectUser) 역할이 있을 수 있습니다. 주 구성원을 삭제하려면 버킷 수준 정책에서 삭제해야 합니다.

Console

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 IAM 정책을 보려는 관리형 폴더가 포함된 버킷의 이름을 클릭합니다.

  3. 버킷 세부정보 페이지의 주 구성원을 삭제하려는 관리형 폴더 옆에 있는 폴더 브라우저 창에서 옵션 더보기 아이콘 을 클릭합니다.

  4. 액세스 수정을 클릭합니다.

  5. FOLDER_NAME 권한 창의 필터 필드에 주 구성원 이름을 입력합니다.

  6. 삭제 아이콘 을 클릭하여 주 구성원을 삭제합니다.

Cloud Storage가 관리형 폴더에서 주 구성원을 삭제합니다.

명령줄

gcloud storage managed-folder remove-iam-policy-binding 명령어를 사용합니다.

gcloud storage managed-folders remove-iam-policy-binding  gs://BUCKET_NAME/MANAGED_FOLDER_NAME --member=PRINCIPAL_IDENTIFIER --role=IAM_ROLE

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 액세스 권한을 취소하려는 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • MANAGED_FOLDER_NAME은 IAM 정책을 삭제하려는 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

  • PRINCIPAL_IDENTIFIER는 액세스 권한을 취소할 사용자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

  • IAM_ROLE은 취소할 IAM 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 관리 폴더에 적용된 기존 정책을 가져옵니다. 이렇게 하려면 cURL을 사용하여 GET getIamPolicy 요청으로 JSON API를 호출합니다.

    curl -X GET \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders/MANAGED_FOLDER_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 액세스 권한을 취소하려는 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    • MANAGED_FOLDER_NAME은 IAM 정책을 삭제하려는 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

  3. 이전 단계에서 검색한 정책을 포함하는 JSON 파일을 만듭니다.

  4. JSON 파일을 편집하여 정책에서 주 구성원을 삭제합니다.

  5. cURL을 사용하여 PUT setIamPolicy 요청으로 JSON API를 호출합니다.

    curl -X PUT --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders/MANAGED_FOLDER_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • JSON_FILE_NAME은 3단계에서 만든 파일의 경로입니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 액세스 권한을 취소하려는 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    • MANAGED_FOLDER_NAME은 IAM 정책을 삭제하려는 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

관리 폴더에 IAM 조건 사용

다음 섹션에서는 관리 폴더에 IAM 조건을 추가하고 삭제하는 방법을 보여줍니다. 관리 폴더의 IAM 조건을 보려면 관리 폴더에 대한 IAM 정책 보기를 참조하세요. Cloud Storage에 IAM 조건 사용에 대한 자세한 내용은 조건을 참조하세요.

관리 폴더에 조건을 추가하기 전에 버킷에 균일한 버킷 수준 액세스를 사용 설정해야 합니다.

관리 폴더에 새 조건 설정

명령줄

  1. 조건 title, 조건에 대한 속성 기반 논리 expression 및 선택적으로 조건에 대한 description을 포함하여 조건을 정의하는 JSON 또는 YAML 파일을 생성합니다.

    Cloud Storage는 날짜/시간,리소스 유형expression리소스 이름 속성만을 지원합니다.

  2. --condition-from-file 플래그와 함께 gcloud storage managed-folders add-iam-policy-binding 명령어를 사용합니다.

gcloud storage managed-folders add-iam-policy-binding  gs://BUCKET_NAME/MANAGED_FOLDER_NAME --member=PRINCIPAL_IDENTIFIER --role=IAM_ROLE --condition-from-file=CONDITION_FILE

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 주 구성원 액세스 권한을 부여할 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
  • MANAGED_FOLDER_NAME은 주 구성원에게 액세스 권한을 부여할 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.
  • PRINCIPAL_IDENTIFIER는 조건이 적용되는 사용자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.
  • IAM_ROLE은 주 구성원에게 부여할 IAM 역할입니다. 예를 들면 roles/storage.objectViewer입니다.
  • CONDITION_FILE은 이전 단계에서 만든 파일입니다.

또는 --condition-from-file 플래그 대신 --condition 플래그를 사용하여 명령어에 조건을 직접 포함할 수 있습니다.

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. GET getIamPolicy 요청을 사용하여 관리 폴더의 IAM 정책을 임시 JSON 파일에 저장합니다.

    curl \
    'https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders/MANAGED_FOLDER_NAMEiam' \
    --header 'Authorization: Bearer OAUTH2_TOKEN' > tmp-policy.json

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 IAM 조건을 설정하려는 관리 폴더가 포함된 버킷의 이름입니다.

    • MANAGED_FOLDER_NAME은 IAM 조건을 설정할 관리 폴더의 이름입니다.

  3. 텍스트 편집기에서 tmp-policy.json 파일을 수정하여 IAM 정책의 바인딩에 새 조건을 추가합니다.

    {
        "version": VERSION,
        "bindings": [
          {
            "role": "IAM_ROLE",
            "members": [
              "PRINCIPAL_IDENTIFIER"
            ],
            "condition": {
              "title": "TITLE",
              "description": "DESCRIPTION",
              "expression": "EXPRESSION"
            }
          }
        ],
        "etag": "ETAG"
    }

    각 항목의 의미는 다음과 같습니다.

    • VERSIONIAM 정책 버전으로, IAM 조건이 있는 관리 폴더의 경우 3이어야 합니다.

    • IAM_ROLE은 조건이 적용되는 역할입니다. 예를 들면 roles/storage.objectViewer입니다.

    • PRINCIPAL_IDENTIFIER는 조건이 적용되는 사용자를 식별합니다. 예를 들면 user:jane@gmail.com입니다. 주 구성원 식별자 형식 목록은 주 구성원 식별자를 참조하세요.

    • TITLE은 조건의 제목입니다. 예를 들면 expires in 2019입니다.

    • DESCRIPTION은 선택사항으로, 조건의 설명입니다. 예를 들면 Permission revoked on New Year's입니다.

    • EXPRESSION속성 기반 논리 표현식입니다. 예를 들면 request.time < timestamp(\"2019-01-01T00:00:00Z\")입니다. 표현식의 더 많은 예시는 조건 속성 참조를 확인하세요. Cloud Storage는 날짜/시간, 리소스 유형, 리소스 이름 속성만을 지원합니다.

    ETAG는 수정하지 마세요.

  4. PUT setIamPolicy 요청을 사용하여 버킷에서 수정된 IAM 정책을 설정합니다.

    curl -X PUT --data-binary @tmp-policy.json \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFoldersMANAGED_FOLDER_NAME/iam"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 IAM 조건을 설정하려는 관리 폴더가 포함된 버킷의 이름입니다.

    • MANAGED_FOLDER_NAME은 IAM 조건을 설정할 관리 폴더의 이름입니다.

관리 폴더에서 조건 삭제

명령줄

  1. gcloud storage managed-folders get-iam-policy 명령어를 사용하여 관리 폴더의 IAM 정책을 임시 JSON 파일에 저장합니다.

    gcloud storage managed-folders get-iam-policy gs://BUCKET_NAME/MANAGED_FOLDER_NAME > tmp-policy.json
  2. 텍스트 편집기에서 tmp-policy.json 파일을 수정하여 IAM 정책에서 조건을 삭제합니다.

  3. gcloud storage managed-folders set-iam-policy 명령어를 사용하여 관리 폴더에서 수정된 IAM 정책을 설정합니다.

    gcloud storage managed-folders set-iam-policy gs://BUCKET_NAME/MANAGED_FOLDER_NAME tmp-policy.json

REST API

JSON

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. GET getIamPolicy 요청을 사용하여 관리 폴더의 IAM 정책을 임시 JSON 파일에 저장합니다.

    curl \
    'https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders/MANAGED_FOLDER_NAMEiam' \
    --header 'Authorization: Bearer OAUTH2_TOKEN' > tmp-policy.json

    각 항목의 의미는 다음과 같습니다.

    • BUCKET_NAME은 액세스를 변경할 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    • MANAGED_FOLDER_NAME은 액세스를 변경할 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

  3. 텍스트 편집기에서 tmp-policy.json 파일을 수정하여 IAM 정책에서 조건을 삭제합니다.

  4. PUT setIamPolicy 요청을 사용하여 관리 폴더에서 수정된 IAM 정책을 설정합니다.

    curl -X PUT --data-binary @tmp-policy.json \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders/MANAGED_FOLDER_NAMEiam"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.

    • BUCKET_NAME은 액세스를 변경할 관리 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    • MANAGED_FOLDER_NAME은 액세스를 변경할 관리 폴더의 이름입니다. 예를 들면 my-managed-folder/입니다.

프로젝트에 IAM 사용

프로젝트 수준 이상에서 IAM 역할을 부여하고 취소하는 방법은 프로젝트, 관리 폴더, 조직에 대한 액세스 관리를 참조하세요.

권장사항

주 구성원에게 필요한 액세스 권한을 부여할 수 있는 최소한의 권한을 설정해야 합니다. 예를 들어 팀 구성원이 버킷에 저장된 객체를 읽기만 하면 되는 경우에는 스토리지 객체 뷰어 역할을 선택합니다. 마찬가지로, 팀 구성원에게 버킷의 객체를 관리할 전체 권한이 있어야 하지만 팀 구성원이 버킷 자체를 관리할 필요는 없는 경우에는 스토리지 객체 관리자를 선택합니다.

다음 단계