Meta tags:
description= Discover how to configure applications to use Compute Engine service accounts to connect to VM instances using SSH through this Google Cloud guide.;
Headings (most frequently used words):
ssh, app, and, configure, apps, to, use, stay, organized, with, collections, save, categorize, content, based, on, your, preferences, before, you, begin, set, up, an, run, the, what, next, console, gcloud, sample, products, pricing, support, resources, engage,
Text of the page (most frequently used words):
the (152), create (120), and (116), vms (104), for (86), with (75), instance (71), troubleshoot (62), about (60), ssh (49), manage (47), disk (43), using (42), view (39), server (39), google (37), cloud (35), use (35), configure (35), disks (35), set (34), compute (33), account (33), windows (33), mig (33), from (31), overview (31), performance (30), reservation (27), engine (26), run (25), command (25), app (24), machine (23), that (22), service (22), login (21), hyperdisk (21), sql (21), network (20), monitor (20), images (20), access (19), zone (18), you (18), instances (18), gpu (18), resources (17), str (17), import (17), image (17), linux (17), policies (16), key (16), configuration (16), connect (16), hostname (16), apply (16), reservations (16), project (15), install (15), host (15), time (15), virtual (15), snapshots (15), groups (15), recommendations (15), your (14), output (14), management (14), workload (14), creation (14), load (14), custom (14), storage (13), cmd (13), remote (13), bulk (13), microsoft (13), cluster (13), private_key_file (12), delete (12), subprocess (12), request (12), metadata (12), sole (12), availability (12), persistent (12), best (12), regional (12), samples (11), args (11), internal (11), based (11), type (11), practices (11), workloads (11), stateful (11), code (10), this (10), uses (10), update (10), authentication (10), keys (10), migs (10), machines (10), attached (10), migrate (10), add (10), logs (10), zones (10), name (9), optional (9), print (9), username (9), dns (9), high (9), application (9), licenses (9), managed (9), tenant (9), multiple (9), openshift (9), shutdown (9), start (9), hpc (9), system (8), sample (8), license (8), oslogin (8), parser (8), default (8), new (8), none (8), zonal (8), remove (8), enable (8), cpu (8), resource (8), optimize (8), choose (8), disaster (8), recovery (8), agent (8), existing (8), guest (8), boot (8), h4d (8), flexibility (8), optimized (8), tpu (8), thumb (7), change (7), following (7), requests (7), client (7), help (7), email (7), execute (7), return (7), get (7), files (7), networking (7), commitments (7), startup (7), balancing (7), benchmark (7), manually (7), idle (7), addresses (7), scale (7), deploy (7), back (7), mysql (7), maintenance (7), templates (7), snapshot (7), backup (7), events (6), all (6), send (6), how (6), example (6), can (6), process (6), target (6), add_argument (6), api (6), stdout (6), returncode (6), running (6), errors (6), accounts (6), method (6), build (6), options (6), console (6), between (6), usage (6), security (6), migration (6), data (6), updates (6), instant (6), nested (6), gpus (6), across (6), applications (6), group (6), mode (6), demand (6), pools (6), failover (6), extension (6), transfer (6), customized (6), spot (6), understand (5), details (5), work (5), python (5), oslogin_service_account_ssh (5), upgrade (5), runs (5), which (5), external (5), oslogin_v1 (5), err (5), env (5), should (5), local (5), region (5), gcloud (5), apps (5), monitoring (5), databases (5), future (5), drivers (5), virtualization (5), nvidia (5), operations (5), placement (5), node (5), highly (5), available (5), multi (5), modify (5), capacity (5), schedules (5), audit (5), symphony (5), scripts (5), manager (5), operating (5), systems (5), enhanced (5), capabilities (5), stop (5), tenancy (5), restore (5), regions (5), types (5), control (5), workstation (5), faq (5), flex (5), português (4), español (4), support (4), down (4), more (4), full (4), argparse (4), private (4), run_ssh (4), object (4), returns (4), used (4), def (4), tries (4), true (4), check (4), expiration (4), public (4), capture_output (4), cwd (4), list (4), authenticate (4), identity (4), services (4), apis (4), environment (4), cli (4), plan (4), tools (4), distributed (4), issues (4), ubuntu (4), bandwidth (4), tcp (4), pmu (4), number (4), ssd (4), share (4), projects (4), live (4), autoscaling (4), cross (4), calendar (4), single (4), metrics (4), health (4), active (4), clusters (4), containers (4), container (4), database (4), postgresql (4), extensions (4), suspend (4), location (4), resize (4), graceful (4), locations (4), plans (4), replication (4), review (4), bound (4), sign (3), terms (3), other (3), information (3), need (3), content (3), page (3), are (3), apache (3), connections (3), download (3), together (3), similar (3), connecting (3), sudo (3), apt (3), cowsay (3), googlecloudplatform (3), docs (3), pip (3), library (3), after (3), main (3), address (3), pub (3), pair (3), result (3), over (3), profile (3), create_ssh_key (3), not (3), text (3), headers (3), osloginserviceclient (3), created (3), else (3), ssh_command (3), oslogin_client (3), setting (3), expire_time (3), int (3), uuid (3), file (3), user (3), raise_errors (3), directory (3), names (3), development (3), provider (3), guide (3), guides (3), infrastructure (3), observability (3), analytics (3), automatic (3), troubleshooting (3), encryption (3), pro (3), serial (3), configurations (3), patterns (3), higher (3), discounts (3), cuds (3), manual (3), scalable (3), resilient (3), autoscale (3), balancer (3), prevent (3), policy (3), testing (3), ibm (3), spectrum (3), perform (3), deploying (3), during (3), prepare (3), deployment (3), rhel (3), protect (3), certificates (3), query (3), state (3), disable (3), properties (3), increase (3), schedule (3), lifecycle (3), design (3), size (3), non (3), pool (3), move (3), creating (3), workstations (3), series (3), tpus (3), product (3), 한국어 (2), 日本語 (2), עברית (2), brasil (2), italiano (2), indonesia (2), français (2), américa (2), latina (2), deutsch (2), english (2), join (2), site (2), youtube (2), center (2), started (2), github (2), status (2), pricing (2), see (2), products (2), last (2), updated (2), 2026 (2), utc (2), except (2), licensed (2), under (2), feedback (2), methods (2), free (2), next (2), works (2), vm_name (2), project_id (2), python3 (2), variables (2), line (2), https (2), libraries (2), where (2), located (2), shred (2), get_login_profile (2), posix (2), try (2), users (2), service_account_metadata_url (2), already (2), provided (2), commands (2), will (2), hosted (2), executed (2), raise (2), failed (2), out (2), calledprocesserror (2), sleep (2), stderr (2), pipe (2), false (2), ssh_public_key (2), public_key (2), original (2), path (2), generates (2), temporary (2), returned (2), captured (2), bool (2), vpc (2), implement (2), adds (2), initialize (2), one (2), make (2), when (2), documentation (2), sdk (2), languages (2), frameworks (2), costs (2), industry (2), solutions (2), hybrid (2), multicloud (2), pipelines (2), hosting (2), quota (2), commitment (2), consumption (2), standard (2), registration (2), sles (2), export (2), port (2), collecting (2), nodes (2), report (2), arm (2), core (2), rdp (2), general (2), latency (2), analyze (2), visible (2), cores (2), automatically (2), committed (2), generation (2), underutilized (2), insights (2), utilization (2), globally (2), web (2), autohealing (2), iis (2), shared (2), reserve (2), autoscaler (2), autoscalers (2), activity (2), kubernetes (2), place (2), redis (2), cloning (2), writer (2), always (2), alwayson (2), volumes (2), synchronization (2), global (2), switch (2), byol (2), payg (2), byos (2), changes (2), families (2), securing (2), event (2), simulate (2), topology (2), repairs (2), repair (2), failures (2), template (2), suspended (2), stopped (2), distribution (2), physical (2), cancel (2), once (2), limit (2), interfaces (2), ipv6 (2), static (2), decrease (2), basic (2), consistent (2), scoped (2), copy (2), appliances (2), asynchronous (2), throughput (2), encrypt (2), format (2), mount (2), memory (2), extreme (2), balanced (2), credentials (2), organization (2), through (2), advanced (2), rdma (2), specific (2), preemptible (2), provisioning (2), models (2), rtx (2), vws (2), constraints (2), accelerator (2), reference (2), technology (2), areas (2), close (2), subscribe, newsletter, our, third, decade, climate, action, cookies, privacy, tech, twitter, blog, engage, training, certification, architecture, getting, release, notes, community, forums, contact, sales, marketplace, easy, easytounderstand, solved, problem, solvedmyproblem, otherup, hard, hardtounderstand, incorrect, incorrectinformationorsamplecode, missing, missingtheinformationsamplesineed, otherdown, tell, otherwise, noted, java, registered, trademark, oracle, its, affiliates, developers, creative, commons, attribution, learn, including, includes, small, these, feel, suit, needs, what, ___________, _______, replace, service_account_ssh, accept, instruct, another, curl, raw, githubusercontent, com, master, hosts, alternatively, write, imports, directly, installs, may, differ, depending, programming, language, parse_args, uname, rawdescriptionhelpformatter, formatter_class, __doc__, description, argumentparser, __main__, __name__, finally, owns, posix_accounts, associate, startswith, identify, resides, west3, timed, received, isinstance, timeoutexpired, timeout, ssh_auth_sock, shell, while, userknownhostsfile, dev, null, stricthostkeychecking, want, let, properly, propagate, import_ssh_public_key, expiration_time_usec, parent, importsshpublickeyrequest, 1000000, microseconds, strip, read, open, rsa, keygen, uuid4, tmp, found, appending, many, seconds, now, valid, form, service_account_username, assigned, specified, 300, error, devnull, exceptions, environmental, passed, child, just, ignored, wrapper, tuple, dict, flavor, http, computemetadata, typing, annotations, __future__, same, demonstrates, possible, implementation, call, lets, initiate, level, haven, verifies, selecting, installed, previously, sure, have, latest, version, components, note, idp, must, first, federated, init, installation, don, select, tab, before, begin, document, describes, programmatically, two, enabling, useful, automating, processes, save, categorize, preferences, stay, organized, collections, home, concurrent, operation, renewal, nvme, resizing, common, pay, viewing, diagnostic, sudoers, screenshots, generate, bug, blackwell, soft, lockups, bus, locks, rescue, inaccessible, dumps, kernel, panic, fstab, unresponsive, suspension, reboots, shutdowns, connectivity, tips, nics, dpdk, improve, resiliency, communication, reduce, compact, idpf, interface, irdma, driver, nic, customize, threads, per, sustained, merge, split, extend, renew, without, purchase, cost, savings, dynamic, overcommit, cpus, floating, reliable, udp, backends, routing, scaling, consuming, consume, combine, cud, allow, sharing, decisions, signals, serving, predictions, organize, labels, replica, states, observe, reports, tensorflow, inference, tensorrt5, learning, monte, carlo, spark, forwarding, others, integrate, clustering, exchange, 2016, sharepoint, strategies, passive, inactive, setups, built, integrations, validation, were, deployed, transition, test, hammerdb, bucket, aws, ec2, pacemaker, s2d, block, netapp, hot, standby, drbd, architectures, mailjet, mailgun, sendgrid, sending, blue, green, deployments, lamp, joomla, asp, net, interactive, mongodb, flask, terraform, servers, mtls, random, generator, virtio, rng, accurate, protocol, ntp, append, els, restrictions, packages, deprecate, versions, family, trusted, red, hat, knowledgebase, functionality, risks, controls, confidential, kek, secure, shielded, attributes, predefined, handle, notices, faulty, unmanaged, affect, preserved, turn, off, alternate, fails, repairing, maintain, click, upgrades, override, selectively, applying, accelerate, outage, rebalance, reenable, proactive, redistribution, shape, distribute, define, info, accidental, deletion, spread, edit, rename, reset, resume, restart, referrers, source, recover, corrupted, duplicate, clones, alerts, backups, vss, regionally, different, protection, considerations, synchronous, consistency, failback, replicate, provisioned, iops, limits, evaluate, settings, kms, customer, supplied, symbolic, links, practice, device, ram, attach, additional, exapools, verify, ptr, record, failure, rates, tags, restrict, automate, password, require, powershell, sac, securely, root, vpn, bastion, iap, connection, only, browser, networks, within, iso, imported, prerequisites, importing, exporting, bring, own, detach, reattach, constraint, accounting, provision, examples, slurm, reserved, team, slice, slices, scenarios, deterministic, base, requirements, ready, aci, configured, preempted, historical, alternative, displays, ops, logging, subnet, has, gpudirect, enabled, ultra, specify, minimum, platform, quickstarts, iam, roles, permissions, office, licensing, premium, strategy, gemini, bare, metal, accelerators, platforms, scores, purpose, discover, skip,
Text of the page (random words):
cts modify a reservation request delete a reservation request future reservations in calendar mode about future reservations in calendar mode create a reservation request in calendar mode delete a reservation request in calendar mode view reservations or reservation requests consume a reservation prevent vms from consuming reservations load balancing about load balancing and scaling add an instance group to a load balancer request routing to a multi region external https load balancer cross region load balancing for microsoft iis backends set up internal tcp udp load balancing build reliable and scalable applications use autohealing for highly available applications use load balancing for highly available applications use autoscaling for highly scalable applications globally autoscale a web service on compute engine patterns for scalable and resilient applications patterns for using floating ip addresses on compute engine optimize resource utilization use recommendations to manage resources apply machine type recommendations to vms configure machine type recommendations apply machine type recommendations to migs view and apply idle resources recommendations view and understand vm insights view and understand mig insights manage idle vm recommendations idle vm recommendations overview view and apply idle vm recommendations configure idle vm recommendations manage reservation recommendations reservation recommendations overview view and apply idle reservation recommendations view and apply underutilized reservation recommendations configure idle reservation recommendations configure underutilized reservation recommendations overcommit cpus on sole tenant vms manual live migration about manual live migration manually live migrate vms share sole tenant node groups next generation dynamic resource management cost savings get discounts for committed usage about commitments and committed use discounts cuds resource based cuds purchase resource based commitments without attached reservations with attached reservations for os licenses manage resource based commitments renew commitments automatically extend commitment terms merge and split commitments upgrade commitments share resource based cuds across projects get discounts for sustained usage disk performance optimize hyperdisk performance optimize persistent disk performance optimize local ssd performance workload performance set the number of threads per core customize the number of visible cpu cores analyze the cpu performance using the pmu pmu overview enable the pmu in vms manage the pmu in vms network performance network bandwidth use google virtual nic use irdma network driver use idpf network interface configure a vm with higher bandwidth reduce latency by using compact placement policies optimize tcp network communication optimize tcp network performance optimize tcp network resiliency benchmark higher bandwidth vms optimize app latency with load balancing use dpdk to improve network performance network performance and gpu vms networking and gpu machines use higher network bandwidth patterns for using multiple host nics troubleshoot general tips troubleshoot connectivity troubleshoot rdp troubleshoot ssh troubleshoot os login troubleshoot vms troubleshoot vm operations troubleshoot vm creation troubleshoot resource availability errors troubleshoot bulk api vm creation troubleshoot vm reboots and shutdowns troubleshoot vm suspension troubleshoot vm updates troubleshoot unresponsive vms troubleshoot vm startup troubleshoot fstab errors troubleshoot kernel panic collecting core dumps rescue an inaccessible vm troubleshoot cpu bus locks troubleshoot cpu soft lockups troubleshoot vm configurations troubleshoot arm vms troubleshoot gpu vms troubleshoot nvidia gpu errors generate a nvidia bug report for blackwell gpus troubleshoot nested virtualization troubleshoot using vm screenshots troubleshoot sole tenant nodes troubleshoot vm performance issues troubleshoot sudoers files troubleshoot windows vms troubleshoot windows vms collecting diagnostic information troubleshoot using the serial console troubleshoot using the serial console viewing serial port output troubleshoot instance groups troubleshoot managed instance groups migs troubleshoot os management troubleshoot licenses troubleshoot image import and export troubleshooting sles pay as you go registration troubleshooting ubuntu pro registration troubleshoot metadata server troubleshoot metadata server troubleshoot networking issues troubleshoot common networking issues troubleshoot network drivers troubleshoot vm performance issues troubleshoot storage troubleshoot disk creation troubleshoot full disks and disk resizing troubleshoot disk encryption troubleshoot nvme disks troubleshoot instant snapshots troubleshoot standard snapshots troubleshoot reservations and commitments troubleshoot reservation creation troubleshoot reservation consumption troubleshooting reservation monitoring troubleshoot reservation updates troubleshoot future reservation creation and updates troubleshoot automatic commitment renewal troubleshoot quota errors troubleshoot concurrent operation quota errors troubleshoot workload authentication troubleshoot default service accounts troubleshoot workload to workload authentication ai and ml application development application hosting compute data analytics and pipelines databases distributed hybrid and multicloud industry solutions migration networking observability and monitoring security storage access and resources management costs and usage management infrastructure as code sdk languages frameworks and tools home documentation compute compute engine guides send feedback configure apps to use ssh stay organized with collections save and categorize content based on your preferences this document describes how to configure apps to programmatically connect between two virtual machine vm instances using ssh and os login enabling apps to use ssh can be useful for automating system management processes all code samples used in this guide are hosted on the googlecloudplatform python docs samples github page before you begin set up ssh for a service account set up os login on your project or on a vm that runs as a service account if you haven t already set up authentication authentication verifies your identity for access to google cloud services and apis to run code or samples from a local development environment you can authenticate to compute engine by selecting one of the following options select the tab for how you plan to use the samples on this page console when you use the google cloud console to access google cloud services and apis you don t need to set up authentication gcloud install the google cloud cli after installation initialize the google cloud cli by running the following command gcloud init if you re using an external identity provider idp you must first sign in to the gcloud cli with your federated identity note if you installed the gcloud cli previously make sure you have the latest version by running gcloud components update set a default region and zone set up an ssh app set up your app to manage ssh keys and initiate ssh connections to compute engine vms at a high level your app should do the following import the google os login library to build client libraries which lets you to authenticate with the os login api initialize the os login client object to enable your app to use os login implement a create_ssh_key method that generates an ssh key for the vm s service account and adds the public key to the service account call the get_login_profile method from the os login library to get the posix username that the service account uses implement a run_ssh method to execute a remote ssh command remove the temporary ssh key files sample ssh app the oslogin_service_account_ssh py sample app demonstrates a possible implementation of an ssh app in this example the app uses the run_ssh method to execute a command on a remote instance and return the command output example of using the os login api to apply public ssh keys for a service account and use that service account to run commands on a remote instance over ssh this example uses zonal dns names to address instances on the same internal vpc network from __future__ import annotations import argparse import subprocess import time from typing import optional import uuid from google cloud import oslogin_v1 import requests service_account_metadata_url http metadata google internal computemetadata v1 instance service accounts default email headers metadata flavor google def execute cmd list str cwd optional str none capture_output bool false env optional dict none raise_errors bool true tuple int str run an external command wrapper for python subprocess args cmd the command to be run cwd directory in which to run the command capture_output should the command output be captured and returned or just ignored env environmental variables passed to the child process raise_errors should errors in run command raise exceptions returns return code and captured output print f running command cmd process subprocess run cmd cwd cwd stdout subprocess pipe if capture_output else subprocess devnull stderr subprocess stdout text true env env check raise_errors output process stdout returncode process returncode if returncode print f command returned error status returncode if capture_output print f with output output return returncode output def create_ssh_key oslogin_client oslogin_v1 osloginserviceclient account str expire_time int 300 str generates a temporary ssh key pair and apply it to the specified account args oslogin_client os login client object account name of the service account this key will be assigned to this should be in form of user service_account_username expire_time how many seconds from now should this key be valid returns the path to private ssh key public key can be found by appending pub to the file name private_key_file f tmp key uuid uuid4 execute ssh keygen t rsa n f private_key_file with open f private_key_file pub as original public_key original read strip expiration time is in microseconds expiration int time time expire_time 1000000 request oslogin_v1 importsshpublickeyrequest request parent account request ssh_public_key key public_key request ssh_public_key expiration_time_usec expiration print f setting key for account oslogin_client import_ssh_public_key request let the key properly propagate time sleep 5 return private_key_file def run_ssh cmd str private_key_file str username str hostname str str runs a command on a remote system args cmd command to be run private_key_file private ssh key to be used for authentication username username to be used for authentication hostname hostname of the machine you want to run the command on returns output of the executed command ssh_command ssh i private_key_file o stricthostkeychecking no o userknownhostsfile dev null f username hostname cmd print f running ssh command join ssh_command tries 0 while tries 3 try ssh subprocess run ssh_command shell false stdout subprocess pipe stderr subprocess stdout text true check true env ssh_auth_sock timeout 10 except subprocess calledprocesserror subprocess timeoutexpired as err time sleep 10 tries 1 if tries 3 if isinstance err subprocess calledprocesserror print f failed to run ssh command return code err returncode output received err output else print failed to run ssh timed out raise err else return ssh stdout def main cmd str project str instance optional str none zone optional str none account optional str none hostname optional str none oslogin optional oslogin_v1 osloginserviceclient none str runs a command on a remote system args cmd command to be executed on the remote host project name of the project in which te remote instance is hosted instance name of the remote system instance zone zone in which the remote system resides i e us west3 a account account to be used for authentication hostname hostname of the remote system oslogin oslogin service client object if not provided a new client will be created returns the commands output create the os login api object if oslogin is none oslogin oslogin_v1 osloginserviceclient identify the service account id if it is not already provided account account or requests get service_account_metadata_url headers headers text if not account startswith users account f users account create a new ssh key pair and associate it with the service account private_key_file create_ssh_key oslogin account try using the os login api get the posix username from the login profile for the service account profile oslogin get_login_profile name account username profile posix_accounts 0 username create the hostname of the target instance using the instance name the zone where the instance is located and the project that owns the instance hostname hostname or f instance zone c project internal run a command on the remote instance over ssh result run_ssh cmd private_key_file username hostname print the command line output from the remote instance print result return result finally shred the private key and delete the pair execute shred private_key_file execute rm private_key_file execute rm f private_key_file pub if __name__ __main__ parser argparse argumentparser description __doc__ formatter_class argparse rawdescriptionhelpformatter parser add_argument cmd default uname a help the command to run on the remote instance parser add_argument project help your google cloud project id parser add_argument zone help the zone where the target instance is located parser add_argument instance help the target instance for the ssh command parser add_argument account help the service account email parser add_argument hostname help the external ip address or hostname for the target instance args parser parse_args main args cmd args project instance args instance zone args zone account args account hostname args hostname run the ssh app after you create an app that uses ssh you can run the app by following a process similar to the following example which installs and runs the oslogin_service_account_ssh py sample app the libraries you install may differ depending on the programming language the app uses alternatively you can write an app that imports oslogin_service_account_ssh py and runs it directly connect to the vm that hosts the ssh app on the vm install pip and the python 3 client library sudo apt update sudo apt install python3 pip y pip install upgrade google cloud os login requests optional if you are using the oslogin_service_account_ssh py sample app download it from googlecloudplatform python docs samples curl o https raw githubusercontent com googlecloudplatform python docs samples master compute oslogin oslogin_service_account_ssh py run the ssh app the sample app uses argparse to accept variables from the command line in this example instruct the app to install and run cowsay on another vm in your projec...
|