태그 템플릿 사용자 역할 부여

프로젝트에서 Data Catalog를 만든 후 조직의 구성원에게 Data Catalog tagTemplateUser 역할을 부여하고 템플릿을 사용하여 데이터 리소스를 태깅할 수 있도록 합니다(GCP 리소스에 태그 첨부하기를 참조하세요).

다음 섹션에서는 구성원에게 tagTemplateUser 역할을 부여하는 방법을 보여줍니다.

tagTemplateUser 역할 부여

Console

Google Cloud Console의 IAM 페이지에서 구성원 목록의 오른쪽에 있는 편집(연필) 아이콘을 클릭하여 Data Catalog tagTemplateUser 역할을 프로젝트 구성원에게 부여합니다.

'권한 수정' 대화상자가 열립니다. '다른 역할 추가'를 클릭한 다음 '역할 선택' 상자를 클릭합니다. 'data catalog'를 입력하여 필터를 추가하고 사용 가능한 Data Catalog 역할을 나열합니다. 'Data Catalog TagTemplate 사용자' 역할을 클릭하여 역할을 선택하고 저장을 클릭하여 대화상자를 닫습니다.

Python

"""This application demonstrates how to allow a project member to use a
Template in order to create Tags with the Cloud Data Catalog API.

For more information, see the README.md under /datacatalog and the
documentation at https://cloud.google.com/data-catalog/docs.
"""

import argparse
from google.cloud import datacatalog_v1

def grant_tag_template_user_role(project_id, template_id, member_id):
    """Grants a user the Tag Template User role for a given template."""
    datacatalog = datacatalog_v1.DataCatalogClient()

    # Currently, Data Catalog stores metadata in the us-central1 region.
    location = "us-central1"

    # Format the Template name.
    template_name = datacatalog_v1.DataCatalogClient.tag_template_path(
        project_id, location, template_id)

    # Retrieve Template's current IAM Policy.
    policy = datacatalog.get_iam_policy(template_name)

    # Add Tag Template User role and member to the policy.
    binding = policy.bindings.add()
    binding.role = 'roles/datacatalog.tagTemplateUser'
    binding.members.append(member_id)

    # Update Template's policy.
    datacatalog.set_iam_policy(template_name, policy)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    parser.add_argument('project_id', help='Your Google Cloud project ID')
    parser.add_argument('template_id', help='Your Template ID')
    parser.add_argument('member_id', help='Member who will be granted access,'
                                          ' e.g. \'user:test-user@gmail.com\'')

    args = parser.parse_args()

    grant_tag_template_user_role(
        args.project_id, args.template_id, args.member_id)

자바

/*
This application demonstrates how to allow a project member to use a
Template in order to create Tags with the Cloud Data Catalog API.

For more information, see the README.md under /datacatalog and the
documentation at https://cloud.google.com/data-catalog/docs.
*/

package com.example.datacatalog;

import com.google.cloud.datacatalog.v1.DataCatalogClient;
import com.google.cloud.datacatalog.v1.TagTemplateName;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;

public class AllowMemberUseTemplate {

  public static void grantTagTemplateUserRole() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String tagTemplateId = "my_tag_template";
    String memberId = "user:test-user@gmail.com";
    grantTagTemplateUserRole(projectId, tagTemplateId, memberId);
  }

  /**
   * Grant a project member the Tag Template User role for a given template.
   *
   * @param projectId  The project ID to which the Template belongs, e.g. 'my-project'.
   * @param templateId The template ID to grant access, e.g. 'my_template'.
   * @param memberId   The member ID who access will be granted to, e.g. 'user:test-user@gmail.com'.
   */
  public static void grantTagTemplateUserRole(
      String projectId, String templateId, String memberId) {

    // Currently, Data Catalog stores metadata in the us-central1 region.
    String location = "us-central1";

    // Format the Template name.
    String templateName =
        TagTemplateName.newBuilder()
            .setProject(projectId)
            .setLocation(location)
            .setTagTemplate(templateId)
            .build()
            .toString();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DataCatalogClient dataCatalogClient = DataCatalogClient.create()) {

      // Create a Binding to add the Tag Template User role and member to the policy.
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/datacatalog.tagTemplateUser")
              .addMembers(memberId)
              .build();

      // Create a Policy object to update Template's IAM policy by adding the new binding.
      Policy policyUpdate =
          Policy.newBuilder()
              .addBindings(binding)
              .build();

      SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder().setPolicy(policyUpdate)
          .setResource(templateName).build();

      // Update Template's policy.
      dataCatalogClient.setIamPolicy(request);

      System.out.println(String.format("Role successfully granted to %s", memberId));

    } catch (Exception e) {
      System.out.print("Error during AllowMemberUseTemplate:\n" + e.toString());
    }
  }
}

Node.js

/**
 * This application demonstrates how to grant a project member
 * the Tag Template User role for a given template.

 * For more information, see the README.md under /datacatalog and the
 * documentation at https://cloud.google.com/data-catalog/docs.
*/

const main = async (
    projectId = process.env.GCLOUD_PROJECT,
    templateId,
    memberId
) => {
    // -------------------------------
    // Import required modules.
    // -------------------------------
    const { DataCatalogClient } = require('@google-cloud/datacatalog').v1;
    const datacatalog = new DataCatalogClient();

    const location = 'us-central1';

    // Format the Template name.
    const templateName = datacatalog.tagTemplatePath(
        projectId,
        location,
        templateId
    );

    // Retrieve Template's current IAM Policy.
    const [getPolicyResponse] = await datacatalog.getIamPolicy({ resource: templateName });
    const policy = getPolicyResponse;

    // Add Tag Template User role and member to the policy.
    policy.bindings.push({
        role: 'roles/datacatalog.tagTemplateUser',
        members: [memberId],
    });

    const request = {
        resource: templateName,
        policy: policy,
    };

    // Update Template's policy.
    const [updatePolicyResponse] = await datacatalog.setIamPolicy(request);
    console.log(`Iam policy: ${JSON.stringify(updatePolicyResponse)}`);
};

// node grantTagTemplateUserRole.js   
// sample values:
// projectId = 'my-project';
// templateId = 'my-template';
// memberId = 'user:member@gmail.com';
main(...process.argv.slice(2));

REST 및 명령줄

해당 언어의 Cloud 클라이언트 라이브러리에 액세스할 수 없거나 REST 요청을 사용하여 API를 테스트하려는 경우 다음 예시를 참조하고 Data Catalog REST API 문서를 참조하세요.

아래의 요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID
  • template-id: 태그 템플릿 ID

HTTP 메서드 및 URL:

POST https://datacatalog.googleapis.com/v1/projects/project-id/locations/us-central1/tagTemplates/template-id:setIamPolicy

JSON 요청 본문:

{
  "policy":{
    "bindings":[
      {
        "role":"roles/datacatalog.tagTemplateUser",
        "members":[
          "user:username@gmail.com"
        ]
      }
    ]
  }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "version":1,
  "etag":"xxxxx.....",
  "bindings":[
    {
      "role":"roles/datacatalog.tagTemplateUser",
      "members":[
        "user:username@gmail.com"
      ]
    }
  ]
}