Disable a custom role

Demonstrates disabling a custom role.

Code sample

Python

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Python API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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"

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.