授予 tagTemplateUser 角色

在项目中创建 Data Catalog 标记模板后,您可以向组织成员授予 Data Catalog tagTemplateUser 角色,以使他们能够使用您的模板来标记数据资源(请参阅将标记附加到 GCP 资源)。

下一部分介绍了如何向成员授予 tagTemplateUser 角色。

授予 tagTemplateUser 角色

控制台

要向项目成员授予 Data Catalog tagTemplateUser 角色,请在 Google Cloud Console 中的 IAM 页面上,点击列表中成员右侧的“编辑”(铅笔)图标。

此时会打开“修改权限”对话框。点击“添加其他角色”,然后点击“选择角色”框。通过输入“data catalog”过滤条件来列出可用的 Data Catalog 角色。点击“Data Catalog TagTemplate User”角色以选择角色,然后点击“保存”关闭对话框。

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)

Java

/*
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 方法和网址:

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