【问题标题】:GCP lab setup using API call使用 API 调用的 GCP 实验室设置
【发布时间】:2022-12-16 23:20:03
【问题描述】:

我正在为学生构建一个 GCP 实验室环境。我想使用 GCP api 调用进行设置

1- 使用 GCP API 调用创建用户 2- 使用 GCP API 调用创建项目 3- 使用 API 调用为用户分配多个自定义角色 4- 将用户链接到项目

我没有找到任何文档来实现上述要求。请参考任何对我有帮助的文件。

【问题讨论】:

    标签: google-cloud-platform


    【解决方案1】:

    首先,您需要使用具有适当权限的服务帐户对您的 API 请求进行身份验证。您可以在 GCP 文档中找到有关如何执行此操作的更多信息。

    接下来,您可以使用以下代码 sn-p 使用 IAM API 创建用户:

    import google.auth
    import google.auth.transport.requests
    import google.auth.transport.grpc
    import google.auth.iam
    import google.auth.iam.credentials
    import google.auth.iam.credentials_pb2 as credentials_pb2
    import google.auth.iam.credentials_pb2_grpc as credentials_pb2_grpc
    import googleapiclient.discovery
    
    # Set the email address of the user you want to create
    user_email = "user@example.com"
    
    # Set the project ID of the project you want to create the user in
    project_id = "my-project-id"
    
    # Create a service client for the IAM API
    service = googleapiclient.discovery.build('iam', 'v1')
    
    # Create the user using the `create` method of the IAM API
    response = service.projects().serviceAccounts().create(
        name=f"projects/{project_id}",
        body={'accountId': user_email}
    ).execute()
    
    # Print the response from the API
    print(response)
    

    要使用 GCP API 创建项目,您可以使用 Cloud Resource Manager API 的 create 方法。以下是如何使用云资源管理器 API 创建项目的示例:

    import googleapiclient.discovery
    
    # Set the ID of the project you want to create
    project_id = "my-new-project"
    
    # Set the name of the project you want to create
    project_name = "My New Project"
    
    # Create a service client for the Cloud Resource Manager API
    service = googleapiclient.discovery.build('cloudresourcemanager', 'v1')
    
    # Create the project using the `create` method of the Cloud Resource Manager API
    response = service.projects().create(
        body={
            'projectId': project_id,
            'name': project_name
        }
    ).execute()
    
    # Print the response from the API
    print(response)
    
    

    要将自定义角色分配给用户,您可以使用 IAM API 的 projects.roles 资源的创建方法。下面是一个示例,说明如何使用 IAM API 将多个自定义角色分配给用户:

    import googleapiclient.discovery
    
    # Set the email address of the user you want to assign roles to
    user_email = "user@example.com"
    
    # Set the project ID of the project the user belongs to
    project_id = "my-project-id"
    
    # Set the names of the custom roles you want to assign to the user
    role_names = ["role1", "role2"]
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2018-02-28
      • 1970-01-01
      • 2019-04-30
      • 2017-09-16
      • 1970-01-01
      相关资源
      最近更新 更多