停用自定义角色

演示了如何停用自定义角色。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Java API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.Role;
import com.google.iam.admin.v1.UpdateRoleRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class DisableRole {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // Role ID must point to an existing role.
    String projectId = "your-project-id";
    String roleId = "testRole";

    Role role = disableRole(projectId, roleId);
    System.out.println("Role name: " + role.getName());
    System.out.println("Role stage: " + role.getStage());
  }

  public static Role disableRole(String projectId, String roleId)
          throws IOException {
    String roleName = "projects/" + projectId + "/roles/" + roleId;
    Role role = Role.newBuilder()
                    .setName(roleName)
                    .setStage(Role.RoleLaunchStage.DISABLED)
                    .build();

    FieldMask fieldMask = FieldMask.newBuilder().addPaths("stage").build();
    UpdateRoleRequest updateRoleRequest =
              UpdateRoleRequest.newBuilder()
                      .setName(roleName)
                      .setRole(role)
                      .setUpdateMask(fieldMask)
                      .build();

    // Initialize client for sending requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (IAMClient iamClient = IAMClient.create()) {
      return iamClient.updateRole(updateRoleRequest);
    }
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Python API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud.iam_admin_v1 import GetRoleRequest, IAMClient, Role, UpdateRoleRequest


def disable_role(project_id: str, role_id: str) -> Role:
    """
    Disables an IAM role in a GCP project.
    Args:
        project_id: GCP project ID
        role_id: ID of GCP IAM role

    Returns: Updated google.cloud.iam_admin_v1.Role object with disabled stage
    """
    client = IAMClient()
    name = f"projects/{project_id}/roles/{role_id}"
    get_request = GetRoleRequest(name=name)
    try:
        role = client.get_role(get_request)
        role.stage = Role.RoleLaunchStage.DISABLED
        update_request = UpdateRoleRequest(name=role.name, role=role)
        client.update_role(update_request)
        print(f"Disabled role: {role_id}: {role}")
        return role
    except NotFound:
        raise f"Role with id [{role_id}] not found, take some actions"

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器