Google Cloud OS Login

raw JSON →
2.20.0 verified Tue May 12 auth: no python install: verified quickstart: stale

The `google-cloud-os-login` library is the Python client for the Google Cloud OS Login API, which enables managing SSH access to Google Compute Engine instances using IAM identities. It simplifies SSH key management, unifies Linux user accounts across multiple VMs, and integrates with Google Cloud IAM for granular authorization, two-factor authentication (2FA), and comprehensive audit logging. The library maintains a frequent release cadence, often receiving updates weekly or bi-weekly as part of the larger `google-cloud-python` client ecosystem.

pip install google-cloud-os-login
error Permission denied (publickey)
cause This error often indicates that the user attempting to SSH into a VM with OS Login enabled does not have the necessary IAM roles assigned, such as `roles/compute.osLogin` or `roles/compute.osAdminLogin`, or `roles/iam.serviceAccountUser` if using a service account.
fix
Ensure the user has the appropriate OS Login IAM roles (e.g., roles/compute.osLogin for standard access or roles/compute.osAdminLogin for sudo access) on the project or instance, and roles/iam.serviceAccountUser if the instance uses a service account. For external users (outside the organization), the roles/compute.osLoginExternalUser role must also be granted at the organization level.
gcloud projects add-iam-policy-binding PROJECT_ID \
    --member='user:YOUR_USER_EMAIL' \
    --role='roles/compute.osLogin'
# Or for admin access:
gcloud projects add-iam-policy-binding PROJECT_ID \
    --member='user:YOUR_USER_EMAIL' \
    --role='roles/compute.osAdminLogin'
# If using a service account, also add:
gcloud projects add-iam-policy-binding PROJECT_ID \
    --member='user:YOUR_USER_EMAIL' \
    --role='roles/iam.serviceAccountUser'
error ModuleNotFoundError: No module named 'google.cloud'
cause This error occurs when the `google-cloud-os-login` library, or its parent `google-cloud` namespace package, is not installed or not accessible in the Python environment where the code is being run.
fix
Install the google-cloud-os-login library using pip in your active Python environment.
pip install google-cloud-os-login
error ERROR: (gcloud.compute.ssh) INVALID_ARGUMENT: Login profile size exceeds 32 KiB. Delete profile values to make additional space.
cause This error indicates that the user's OS Login profile has accumulated too many SSH keys or other metadata, exceeding the 32 KiB size limit.
fix
Remove unused or expired SSH keys from the OS Login profile using the gcloud compute os-login ssh-keys remove command.
gcloud compute os-login describe-profile
# Identify the key's fingerprint or string to remove
gcloud compute os-login ssh-keys remove --key=KEY_FINGERPRINT_OR_STRING
error ERROR: (gcloud.beta.compute.ssh) INVALID_ARGUMENT: This region is not supported by the OS Login Sign API at this time.
cause This error occurs when attempting to use OS Login to connect to a VM instance located in a Google Cloud region or zone that does not currently support the OS Login Sign API.
fix
Deploy your VM instance in a region that supports the OS Login Sign API (e.g., us-central1, europe-west1, asia-east1). Alternatively, if using that region is unavoidable, temporarily disable OS Login for the instance and revert to traditional metadata-based SSH keys, or add your SSH key to your OS Login profile and use regular SSH.
# Option 1: Disable OS Login for the instance (if regional support is critical and you can't change region)
gcloud compute instances add-metadata INSTANCE_NAME \
    --metadata enable-oslogin=FALSE \
    --zone=REGION-ZONE

# Option 2: Add an SSH key to your OS Login profile and use standard SSH client (if OS Login is still desired but not via gcloud in unsupported region)
gcloud compute os-login ssh-keys add --key-file=~/.ssh/id_rsa.pub
# Then connect via standard SSH
ssh -i ~/.ssh/id_rsa YOUR_OS_LOGIN_USERNAME@YOUR_VM_EXTERNAL_IP
error ERROR: (gcloud.compute.ssh) FAILED_PRECONDITION: The specified username or UID is not unique within given system ID.
cause This error arises when OS Login attempts to generate a username for a user, but that username or its associated UID already exists within the organization's user accounts. This can happen if a user account was recently deleted and recreated with the same email address, as POSIX information can take up to 48 hours to be fully removed.
fix
Wait up to 48 hours for the old POSIX user information to be fully removed after a user deletion, then retry. Alternatively, if the user account was deleted, consider restoring it or ensuring that the account's POSIX information was explicitly removed before deletion.
gotcha When OS Login is enabled for a VM, it will *not* accept SSH keys stored in instance or project metadata. Conversely, VMs without OS Login enabled will not accept SSH keys from OS Login profiles. Ensure consistency in your key management strategy.
fix Use OS Login for SSH key management if enabled, or revert to metadata-based keys if OS Login is disabled. Do not mix methods for a single VM.
gotcha Encountering 'The specified username or UID is not unique within given system ID' error when connecting via SSH to an OS Login-enabled VM. This can happen if a user account is deleted and a new one with the same email is created soon after, as POSIX information can take up to 48 hours to be fully removed.
fix Wait at least 48 hours for POSIX information to clear, or restore the deleted account and explicitly remove its POSIX information before re-deleting. For G Suite organizations, manage username formats via Cloud Identity administrators.
gotcha The 'Login profile size exceeds 32 KiB' error can occur if too many SSH keys or other profile values are associated with a user's OS Login profile.
fix Review the OS Login profile using `gcloud compute os-login describe-profile` and remove any unused or redundant SSH keys using `gcloud compute os-login ssh-keys remove`.
gotcha The OS Login Sign API may not be supported in all GCP regions/zones, leading to 'This region is not supported by the OS Login Sign API at this time' errors when attempting to connect via `gcloud compute ssh`.
fix Prefer deploying VMs in regions known to support the OS Login Sign API (e.g., `us-central1`, `europe-west1`, `asia-east1`). Alternatively, disable OS Login for the instance/project or add keys directly to your OS Login profile and use regular SSH if locked to an unsupported region.
gotcha Users might require the `roles/iam.serviceAccountUser` IAM role in addition to `roles/compute.osLogin` or `roles/compute.osAdminLogin` to successfully SSH into an OS Login-enabled instance, especially if service account impersonation is involved or the VM uses a specific service account.
fix Ensure the user or the service account acting on their behalf has the `roles/iam.serviceAccountUser` role granted on the relevant service account or project.
gotcha By default, OS Login generates a Linux username by combining the user's email username and domain (e.g., `user@example.com` becomes `user_example_com`). If you expect a simpler username (e.g., `user`), this behavior can be confusing.
fix For G Suite organizations, administrators can change the default setting to remove the domain suffix for newly generated usernames. This is not configurable for individual consumer accounts.
breaking The application failed to find Application Default Credentials (ADC) to authenticate with Google Cloud APIs, resulting in a `google.auth.exceptions.DefaultCredentialsError`. This often occurs when running applications outside of a properly configured Google Cloud environment (e.g., locally without `gcloud auth application-default login`, or in an environment without appropriate service account configuration).
fix Ensure that Application Default Credentials are properly configured in the execution environment. This can involve running `gcloud auth application-default login` for local development, setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to a service account key file, or deploying the application in a Google Cloud environment (like Compute Engine, Cloud Run, GKE) that automatically provides credentials.
breaking The application failed to find default credentials to authenticate with Google Cloud APIs, resulting in a `google.auth.exceptions.DefaultCredentialsError`. This means Application Default Credentials (ADC) were not properly configured or found in the execution environment.
fix Ensure Application Default Credentials (ADC) are configured in the execution environment. This typically involves authenticating `gcloud` (e.g., `gcloud auth application-default login`), setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to a service account key file, or ensuring the environment (e.g., GCE VM, Cloud Run) has appropriate scopes and metadata for implicit ADC.
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 1.56s 68.1M
3.10 alpine (musl) - - 1.43s 67.0M
3.10 slim (glibc) wheel 5.9s 1.00s 66M
3.10 slim (glibc) - - 0.98s 65M
3.11 alpine (musl) wheel - 2.06s 72.6M
3.11 alpine (musl) - - 2.41s 71.5M
3.11 slim (glibc) wheel 5.4s 1.49s 70M
3.11 slim (glibc) - - 1.48s 69M
3.12 alpine (musl) wheel - 2.06s 64.0M
3.12 alpine (musl) - - 2.33s 62.9M
3.12 slim (glibc) wheel 4.4s 1.74s 62M
3.12 slim (glibc) - - 1.94s 61M
3.13 alpine (musl) wheel - 2.05s 63.8M
3.13 alpine (musl) - - 2.39s 62.6M
3.13 slim (glibc) wheel 4.6s 1.69s 62M
3.13 slim (glibc) - - 2.04s 60M
3.9 alpine (musl) wheel - 1.34s 68.1M
3.9 alpine (musl) - - 1.25s 67.0M
3.9 slim (glibc) wheel 6.9s 1.22s 66M
3.9 slim (glibc) - - 1.01s 65M

This quickstart demonstrates how to initialize the `OsLoginServiceClient` and retrieve the OS Login profile for the currently authenticated user. This profile includes POSIX account information and associated SSH public keys. For this to work, OS Login must be enabled on your Google Cloud project/instance, and the executing user or service account must have appropriate IAM permissions (e.g., `roles/compute.osLogin` or `roles/compute.osAdminLogin`). Authentication is typically handled automatically via `gcloud auth application-default login` or `GOOGLE_APPLICATION_CREDENTIALS`.

import os
from google.cloud.oslogin_v1 import OsLoginServiceClient

def get_current_user_login_profile():
    """Retrieves the OS Login profile for the authenticated user."""
    # Instantiate a client
    client = OsLoginServiceClient()

    # The 'name' field identifies the user whose login profile is to be retrieved.
    # 'users/me' refers to the currently authenticated user.
    # For a specific user, use 'users/{email_address}' or 'users/{uid}'.
    user_name = 'users/me'
    
    try:
        login_profile = client.get_login_profile(name=user_name)
        print(f"Retrieved Login Profile for {user_name}:")
        print(f"  Name: {login_profile.name}")
        print(f"  Posix Accounts:")
        for account in login_profile.posix_accounts:
            print(f"    - Username: {account.username}, UID: {account.uid}, GID: {account.gid}")
        print(f"  SSH Public Keys:")
        if login_profile.ssh_public_keys:
            for key_id, ssh_key in login_profile.ssh_public_keys.items():
                print(f"    - Key ID: {key_id}, Key: {ssh_key.key}")
        else:
            print("    No SSH public keys found.")

    except Exception as e:
        print(f"Error retrieving login profile: {e}")
        print("Please ensure OS Login is enabled for the user/project and correct IAM roles are granted.")

if __name__ == '__main__':
    # Before running, ensure default authentication is set up, e.g., by running 'gcloud auth application-default login'
    # or by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable.
    # This example assumes the 'users/me' identifier will work with the authenticated credential.
    get_current_user_login_profile()