Google Cloud OS Login

2.20.0 · active · verified Sun Mar 29

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.

Warnings

Install

Imports

Quickstart

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()

view raw JSON →