0
# Environment Operations
1
2
Core operations for managing Cloud Shell environments including getting environment details, starting environments, and handling OAuth authorization.
3
4
## Capabilities
5
6
### Get Environment
7
8
Retrieve information about a Cloud Shell environment.
9
10
```python { .api }
11
def get_environment(
12
self,
13
request: Optional[Union[cloudshell.GetEnvironmentRequest, dict]] = None,
14
*,
15
name: Optional[str] = None,
16
retry: OptionalRetry = gapic_v1.method.DEFAULT,
17
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
18
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
19
) -> cloudshell.Environment:
20
"""
21
Get environment details. Returns NOT_FOUND if environment does not exist.
22
23
Args:
24
request: GetEnvironmentRequest object or dict
25
name: Environment resource name (users/{user}/environments/{environment})
26
retry: Retry configuration for the request
27
timeout: Timeout for the request
28
metadata: Additional metadata to send with the request
29
30
Returns:
31
Environment object with current state and connection details
32
33
Raises:
34
google.api_core.exceptions.NotFound: Environment does not exist
35
"""
36
```
37
38
### Start Environment
39
40
Start a Cloud Shell environment (long-running operation).
41
42
```python { .api }
43
def start_environment(
44
self,
45
request: Optional[Union[cloudshell.StartEnvironmentRequest, dict]] = None,
46
*,
47
retry: OptionalRetry = gapic_v1.method.DEFAULT,
48
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
49
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
50
) -> operation.Operation:
51
"""
52
Start an existing environment. This is a long-running operation.
53
54
Args:
55
request: StartEnvironmentRequest object or dict
56
retry: Retry configuration for the request
57
timeout: Timeout for the request
58
metadata: Additional metadata to send with the request
59
60
Returns:
61
Long-running operation that resolves to StartEnvironmentResponse
62
63
Raises:
64
google.api_core.exceptions.GoogleAPICallError: API call failed
65
"""
66
```
67
68
### Authorize Environment
69
70
Send OAuth credentials to a running environment (long-running operation).
71
72
```python { .api }
73
def authorize_environment(
74
self,
75
request: Optional[Union[cloudshell.AuthorizeEnvironmentRequest, dict]] = None,
76
*,
77
retry: OptionalRetry = gapic_v1.method.DEFAULT,
78
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
79
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
80
) -> operation.Operation:
81
"""
82
Send OAuth credentials to running environment. This is a long-running operation.
83
84
Args:
85
request: AuthorizeEnvironmentRequest object or dict
86
retry: Retry configuration for the request
87
timeout: Timeout for the request
88
metadata: Additional metadata to send with the request
89
90
Returns:
91
Long-running operation that resolves to AuthorizeEnvironmentResponse
92
93
Raises:
94
google.api_core.exceptions.GoogleAPICallError: API call failed
95
"""
96
```
97
98
## Request Types
99
100
### GetEnvironmentRequest
101
102
```python { .api }
103
class GetEnvironmentRequest(proto.Message):
104
"""Request to get environment details."""
105
106
name: str # Required. Environment resource name (e.g., users/me/environments/default)
107
```
108
109
### StartEnvironmentRequest
110
111
```python { .api }
112
class StartEnvironmentRequest(proto.Message):
113
"""Request to start environment."""
114
115
name: str # Environment name to start
116
access_token: str # Optional initial access token
117
public_keys: MutableSequence[str] # Public keys to add before starting
118
```
119
120
### AuthorizeEnvironmentRequest
121
122
```python { .api }
123
class AuthorizeEnvironmentRequest(proto.Message):
124
"""Request to send OAuth credentials to environment."""
125
126
name: str # Environment name
127
access_token: str # OAuth access token
128
id_token: str # OAuth ID token
129
expire_time: google.protobuf.timestamp_pb2.Timestamp # Token expiration time
130
```
131
132
## Response Types
133
134
### Environment
135
136
```python { .api }
137
class Environment(proto.Message):
138
"""A Cloud Shell environment combining Docker image and persistent home directory."""
139
140
name: str # Immutable resource name: users/{owner}/environments/{id}
141
id: str # Output only environment identifier
142
docker_image: str # Required immutable Docker image path
143
state: Environment.State # Output only current execution state
144
web_host: str # Output only HTTPS/WSS connection host
145
ssh_username: str # Output only SSH username
146
ssh_host: str # Output only SSH connection host
147
ssh_port: int # Output only SSH connection port
148
public_keys: MutableSequence[str] # Output only associated public keys
149
150
class State(proto.Enum):
151
"""Possible execution states for an environment."""
152
STATE_UNSPECIFIED = 0 # Unknown state
153
SUSPENDED = 1 # Not running, can be started
154
PENDING = 2 # Starting but not ready
155
RUNNING = 3 # Running and ready for connections
156
DELETING = 4 # Being deleted
157
```
158
159
### StartEnvironmentResponse
160
161
```python { .api }
162
class StartEnvironmentResponse(proto.Message):
163
"""Response from start environment operation."""
164
165
environment: Environment # Started environment
166
```
167
168
### AuthorizeEnvironmentResponse
169
170
```python { .api }
171
class AuthorizeEnvironmentResponse(proto.Message):
172
"""Response from authorize environment operation."""
173
# Empty message
174
```
175
176
## Operation Metadata Types
177
178
### StartEnvironmentMetadata
179
180
```python { .api }
181
class StartEnvironmentMetadata(proto.Message):
182
"""Metadata for start environment operation."""
183
184
state: StartEnvironmentMetadata.State # Current startup state
185
186
class State(proto.Enum):
187
"""Current startup state."""
188
STATE_UNSPECIFIED = 0 # Unknown state
189
STARTING = 1 # Starting without details
190
UNARCHIVING_DISK = 2 # Unarchiving user disk
191
AWAITING_COMPUTE_RESOURCES = 4 # Waiting for compute resources
192
FINISHED = 3 # Startup complete
193
```
194
195
### Other Metadata Types
196
197
```python { .api }
198
class CreateEnvironmentMetadata(proto.Message):
199
"""Operation metadata for create operations."""
200
# Empty message
201
202
class DeleteEnvironmentMetadata(proto.Message):
203
"""Operation metadata for delete operations."""
204
# Empty message
205
206
class AuthorizeEnvironmentMetadata(proto.Message):
207
"""Operation metadata for authorize operations."""
208
# Empty message
209
```
210
211
## Usage Examples
212
213
### Get Environment Information
214
215
```python
216
from google.cloud.shell import CloudShellServiceClient
217
218
client = CloudShellServiceClient()
219
220
# Get default environment
221
environment = client.get_environment(
222
name="users/me/environments/default"
223
)
224
225
print(f"Environment ID: {environment.id}")
226
print(f"State: {environment.state}")
227
print(f"Docker Image: {environment.docker_image}")
228
229
if environment.state == environment.State.RUNNING:
230
print(f"SSH: {environment.ssh_username}@{environment.ssh_host}:{environment.ssh_port}")
231
print(f"Web Host: {environment.web_host}")
232
print(f"Public Keys: {len(environment.public_keys)} keys")
233
```
234
235
### Start Environment
236
237
```python
238
from google.cloud.shell import CloudShellServiceClient, StartEnvironmentRequest
239
240
client = CloudShellServiceClient()
241
242
# Start environment with SSH keys
243
request = StartEnvironmentRequest(
244
name="users/me/environments/default",
245
public_keys=[
246
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC... user@example.com"
247
]
248
)
249
250
operation = client.start_environment(request=request)
251
print(f"Operation name: {operation.name}")
252
253
# Wait for completion
254
response = operation.result(timeout=300) # 5 minute timeout
255
print(f"Started environment: {response.environment.name}")
256
print(f"Environment state: {response.environment.state}")
257
258
# Monitor operation metadata
259
metadata = operation.metadata
260
if hasattr(metadata, 'state'):
261
print(f"Startup state: {metadata.state}")
262
```
263
264
### Authorize Environment with OAuth
265
266
```python
267
from google.cloud.shell import CloudShellServiceClient, AuthorizeEnvironmentRequest
268
from google.protobuf import timestamp_pb2
269
import datetime
270
271
client = CloudShellServiceClient()
272
273
# Create expiration timestamp (1 hour from now)
274
expire_time = timestamp_pb2.Timestamp()
275
expire_time.FromDatetime(datetime.datetime.utcnow() + datetime.timedelta(hours=1))
276
277
request = AuthorizeEnvironmentRequest(
278
name="users/me/environments/default",
279
access_token="ya29.c.KqKB...",
280
id_token="eyJhbGciOiJSUzI1NiI...",
281
expire_time=expire_time
282
)
283
284
operation = client.authorize_environment(request=request)
285
response = operation.result()
286
print("OAuth credentials sent to environment")
287
```
288
289
### Async Environment Operations
290
291
```python
292
import asyncio
293
from google.cloud.shell import CloudShellServiceAsyncClient
294
295
async def start_environment_async():
296
async with CloudShellServiceAsyncClient() as client:
297
# Get environment status
298
environment = await client.get_environment(
299
name="users/me/environments/default"
300
)
301
302
if environment.state != environment.State.RUNNING:
303
# Start if not running
304
operation = await client.start_environment(
305
name="users/me/environments/default"
306
)
307
response = await operation.result()
308
print(f"Started: {response.environment.name}")
309
else:
310
print("Environment already running")
311
312
asyncio.run(start_environment_async())
313
```
314
315
### Error Handling
316
317
```python
318
from google.cloud.shell import CloudShellServiceClient
319
from google.api_core import exceptions
320
321
client = CloudShellServiceClient()
322
323
try:
324
environment = client.get_environment(
325
name="users/me/environments/nonexistent"
326
)
327
except exceptions.NotFound:
328
print("Environment not found")
329
except exceptions.GoogleAPICallError as e:
330
print(f"API call failed: {e}")
331
```