-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
750 lines (564 loc) · 24.1 KB
/
utils.py
File metadata and controls
750 lines (564 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
from datetime import datetime, timezone
from functools import lru_cache
from typing import TYPE_CHECKING, Any, cast
import boto3
import typer
from botocore.exceptions import ClientError, NoCredentialsError
from rich.console import Console
from .exceptions import (
AWSServiceError,
InstanceNotFoundError,
MultipleInstancesFoundError,
ResourceNotFoundError,
ValidationError,
)
from .validation import (
ensure_non_empty_array,
safe_get_array_item,
validate_aws_response_structure,
validate_instance_id,
validate_instance_name,
validate_snapshot_id,
validate_volume_id,
)
if TYPE_CHECKING:
from mypy_boto3_ec2.client import EC2Client
from mypy_boto3_sts.client import STSClient
console = Console(force_terminal=True, width=200)
app = typer.Typer()
@lru_cache
def get_ec2_client() -> "EC2Client":
"""Get or create the EC2 client.
Uses lazy initialization and caches the client for reuse.
Returns:
boto3 EC2 client instance
"""
return boto3.client("ec2")
@lru_cache
def get_sts_client() -> "STSClient":
"""Get or create the STS client.
Uses lazy initialization and caches the client for reuse.
Returns:
boto3 STS client instance
"""
return boto3.client("sts")
# Backwards compatibility: ec2_client is now accessed lazily via __getattr__
# to avoid creating the client at import time (which breaks tests without AWS region)
# The module-level ec2_client attribute is still available for backwards compatibility
# but is deprecated and will be removed in v0.5.0
def __getattr__(name: str) -> Any:
"""Lazy module attribute access for backwards compatibility.
Provides lazy access to ec2_client for backwards compatibility.
This pattern allows the client to be created on first access rather
than at module import time, which is necessary for testing.
"""
if name == "ec2_client":
return get_ec2_client()
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
def get_account_id() -> str:
"""Returns the caller id, this is the AWS account id not the AWS user id.
Returns:
The AWS account ID
Raises:
AWSServiceError: If AWS API call fails
"""
try:
response = boto3.client("sts").get_caller_identity()
# Validate response structure
validate_aws_response_structure(response, ["Account"], "get_caller_identity")
return response["Account"]
except ClientError as e:
error_code = e.response["Error"]["Code"]
error_message = e.response["Error"]["Message"]
raise AWSServiceError("STS", "get_caller_identity", error_code, error_message)
except NoCredentialsError:
raise AWSServiceError(
"STS", "get_caller_identity", "NoCredentials", "AWS credentials not found or invalid"
)
def get_instance_id(instance_name: str) -> str:
"""Returns the id of the instance.
Args:
instance_name: The name of the instance to find
Returns:
The instance ID
Raises:
InstanceNotFoundError: If no instance found with the given name
MultipleInstancesFoundError: If multiple instances found with the same name
AWSServiceError: If AWS API call fails
"""
# Validate input
instance_name = validate_instance_name(instance_name)
try:
response = get_ec2_client().describe_instances(
Filters=[
{"Name": "tag:Name", "Values": [instance_name]},
{
"Name": "instance-state-name",
"Values": ["pending", "stopping", "stopped", "running"],
},
]
)
# Validate response structure
validate_aws_response_structure(response, ["Reservations"], "describe_instances")
reservations = response["Reservations"]
if not reservations:
raise InstanceNotFoundError(instance_name)
if len(reservations) > 1:
raise MultipleInstancesFoundError(instance_name, len(reservations))
# Safely access the instance ID
instances = reservations[0].get("Instances", [])
if not instances:
raise InstanceNotFoundError(
instance_name, "Instance reservation found but no instances in reservation"
)
return instances[0]["InstanceId"]
except ClientError as e:
error_code = e.response["Error"]["Code"]
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_instances", error_code, error_message)
except NoCredentialsError:
raise AWSServiceError(
"EC2", "describe_instances", "NoCredentials", "AWS credentials not found or invalid"
)
def get_instance_status(instance_id: str | None = None) -> dict[str, Any]:
"""Returns the status of the instance.
Args:
instance_id: Optional instance ID to get status for. If None, gets all instance statuses
Returns:
The instance status response from AWS
Raises:
AWSServiceError: If AWS API call fails
"""
try:
if instance_id:
# Validate input if provided
instance_id = validate_instance_id(instance_id)
response = get_ec2_client().describe_instance_status(InstanceIds=[instance_id])
else:
response = get_ec2_client().describe_instance_status()
return dict(response)
except ClientError as e:
error_code = e.response["Error"]["Code"]
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_instance_status", error_code, error_message)
except NoCredentialsError:
raise AWSServiceError(
"EC2",
"describe_instance_status",
"NoCredentials",
"AWS credentials not found or invalid",
)
def get_instances(exclude_terminated: bool = False) -> list[dict[str, Any]]:
"""
Get all instances, optionally excluding those in a 'terminated' state.
Uses pagination to handle large numbers of instances (>100).
Args:
exclude_terminated: Whether to exclude terminated instances
Returns:
List of reservation dictionaries
Raises:
AWSServiceError: If AWS API call fails
"""
try:
filters: list[dict[str, Any]] = []
if exclude_terminated:
filters.append(
{
"Name": "instance-state-name",
"Values": ["pending", "running", "shutting-down", "stopping", "stopped"],
}
)
# Use paginator to handle >100 instances
paginator = get_ec2_client().get_paginator("describe_instances")
reservations: list[dict[str, Any]] = []
if filters:
page_iterator = paginator.paginate(Filters=filters) # type: ignore[arg-type]
else:
page_iterator = paginator.paginate()
for page in page_iterator:
reservations.extend(cast(list[dict[str, Any]], page.get("Reservations", [])))
return reservations
except ClientError as e:
error_code = e.response["Error"]["Code"]
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_instances", error_code, error_message)
except NoCredentialsError:
raise AWSServiceError(
"EC2", "describe_instances", "NoCredentials", "AWS credentials not found or invalid"
)
def get_instance_dns(instance_id: str) -> str:
"""Returns the public DNS name of the instance.
Args:
instance_id: The instance ID to get DNS for
Returns:
The public DNS name of the instance
Raises:
ResourceNotFoundError: If instance not found
AWSServiceError: If AWS API call fails
"""
# Validate input
instance_id = validate_instance_id(instance_id)
try:
response = get_ec2_client().describe_instances(InstanceIds=[instance_id])
# Validate response structure
validate_aws_response_structure(response, ["Reservations"], "describe_instances")
reservations = ensure_non_empty_array(
list(response["Reservations"]), "instance reservations"
)
instances = ensure_non_empty_array(list(reservations[0].get("Instances", [])), "instances")
return str(instances[0].get("PublicDnsName", ""))
except ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code == "InvalidInstanceID.NotFound":
raise ResourceNotFoundError("Instance", instance_id)
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_instances", error_code, error_message)
def get_instance_name() -> str:
"""Returns the name of the instance as defined in the config file.
Returns:
str: Instance name if found
Raises:
typer.Exit: If no instance name is configured
"""
from remote.config import config_manager
instance_name = config_manager.get_instance_name()
if instance_name:
return instance_name
else:
typer.secho("No default instance configured.", fg=typer.colors.RED)
typer.secho("Run `remote config add` to set up your default instance.", fg=typer.colors.RED)
raise typer.Exit(1)
def get_instance_info(
instances: list[dict[str, Any]], name_filter: str | None = None, drop_nameless: bool = False
) -> tuple[list[str], list[str], list[str], list[str], list[str | None]]:
"""
Get all instance names for the given account from aws cli.
Args:
instances: List of instances returned by get_instances()
name_filter: Filter to apply to the instance names. If not found in the
instance name, it will be excluded from the list.
drop_nameless: Whether to exclude instances without a Name tag
Returns:
Tuple of (names, public_dnss, statuses, instance_types, launch_times)
Raises:
ValidationError: If instances data is malformed
"""
names = []
public_dnss = []
statuses = []
instance_types = []
launch_times = []
for reservation in instances:
# Safely access Instances array
reservation_instances = reservation.get("Instances", [])
for instance in reservation_instances:
try:
# Check whether there is a Name tag
tags = {k["Key"]: k["Value"] for k in instance.get("Tags", [])}
if not tags or "Name" not in tags:
# Skip instances without a Name tag and continue to next instance
continue
instance_name = tags["Name"]
# Apply name filter if provided
if name_filter and name_filter not in instance_name:
continue
names.append(instance_name)
public_dnss.append(instance.get("PublicDnsName", ""))
# Safely access state information
state_info = instance.get("State", {})
status = state_info.get("Name", "unknown")
statuses.append(status)
# Handle launch time for running instances
if status == "running" and "LaunchTime" in instance:
try:
launch_time = instance["LaunchTime"].timestamp()
launch_time = datetime.fromtimestamp(launch_time, tz=timezone.utc)
launch_time = launch_time.strftime("%Y-%m-%d %H:%M:%S UTC")
except (AttributeError, ValueError):
launch_time = None
else:
launch_time = None
launch_times.append(launch_time)
instance_types.append(instance.get("InstanceType", "unknown"))
except (KeyError, TypeError) as e:
# Skip malformed instance data but continue processing others
console.print(f"[yellow]Warning: Skipping malformed instance data: {e}[/yellow]")
continue
return names, public_dnss, statuses, instance_types, launch_times
def get_instance_ids(instances: list[dict[str, Any]]) -> list[str]:
"""Returns a list of instance ids extracted from the output of get_instances().
Args:
instances: List of reservation dictionaries from describe_instances()
Returns:
List of instance IDs
Raises:
ValidationError: If any reservation has no instances
"""
instance_ids = []
for _i, reservation in enumerate(instances):
instances_list = reservation.get("Instances", [])
if not instances_list:
# Skip reservations with no instances instead of crashing
continue
instance_ids.append(instances_list[0]["InstanceId"])
return instance_ids
def is_instance_running(instance_id: str) -> bool | None:
"""Returns True if the instance is running, False if not, None if unknown.
Args:
instance_id: The instance ID to check
Returns:
True if running, False if not running, None if status unknown
Raises:
AWSServiceError: If AWS API call fails
"""
# Validate input
instance_id = validate_instance_id(instance_id)
try:
status = get_instance_status(instance_id)
# Handle case where InstanceStatuses is empty (instance not running)
instance_statuses = status.get("InstanceStatuses", [])
if not instance_statuses:
return False
# Safely access the state information
first_status = safe_get_array_item(instance_statuses, 0, "instance statuses")
instance_state = first_status.get("InstanceState", {})
state_name = instance_state.get("Name", "unknown")
return bool(state_name == "running")
except (AWSServiceError, ResourceNotFoundError, ValidationError):
# Re-raise specific errors
raise
except (KeyError, TypeError, AttributeError) as e:
# For data structure errors, log and return None
console.print(f"[yellow]Warning: Unexpected instance status structure: {e}[/yellow]")
return None
def is_instance_stopped(instance_id: str) -> bool | None:
"""Returns True if the instance is stopped, False if not, None if unknown.
Args:
instance_id: The instance ID to check
Returns:
True if stopped, False if not stopped, None if status unknown
Raises:
AWSServiceError: If AWS API call fails
"""
# Validate input
instance_id = validate_instance_id(instance_id)
try:
status = get_instance_status(instance_id)
# Handle case where InstanceStatuses is empty
instance_statuses = status.get("InstanceStatuses", [])
if not instance_statuses:
return None # Status unknown
# Safely access the state information
first_status = safe_get_array_item(instance_statuses, 0, "instance statuses")
instance_state = first_status.get("InstanceState", {})
state_name = instance_state.get("Name", "unknown")
return bool(state_name == "stopped")
except (AWSServiceError, ResourceNotFoundError, ValidationError):
# Re-raise specific errors
raise
except (KeyError, TypeError, AttributeError) as e:
# For data structure errors, log and return None
console.print(f"[yellow]Warning: Unexpected instance status structure: {e}[/yellow]")
return None
def get_instance_type(instance_id: str) -> str:
"""Returns the instance type of the instance.
Args:
instance_id: The instance ID to get type for
Returns:
The instance type (e.g., 't2.micro')
Raises:
ResourceNotFoundError: If instance not found
AWSServiceError: If AWS API call fails
"""
# Validate input
instance_id = validate_instance_id(instance_id)
try:
response = get_ec2_client().describe_instances(InstanceIds=[instance_id])
# Validate response structure
validate_aws_response_structure(response, ["Reservations"], "describe_instances")
reservations = ensure_non_empty_array(
list(response["Reservations"]), "instance reservations"
)
instances = ensure_non_empty_array(list(reservations[0].get("Instances", [])), "instances")
return str(instances[0]["InstanceType"])
except ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code == "InvalidInstanceID.NotFound":
raise ResourceNotFoundError("Instance", instance_id)
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_instances", error_code, error_message)
def get_volume_ids(instance_id: str) -> list[str]:
"""Returns a list of volume ids attached to the instance.
Args:
instance_id: The instance ID to get volumes for
Returns:
List of volume IDs attached to the instance
Raises:
AWSServiceError: If AWS API call fails
"""
# Validate input
instance_id = validate_instance_id(instance_id)
try:
response = get_ec2_client().describe_volumes(
Filters=[{"Name": "attachment.instance-id", "Values": [instance_id]}]
)
# Validate response structure
validate_aws_response_structure(response, ["Volumes"], "describe_volumes")
# Safely extract volume IDs
volume_ids = []
for volume in response["Volumes"]:
if "VolumeId" in volume:
volume_ids.append(volume["VolumeId"])
return volume_ids
except ClientError as e:
error_code = e.response["Error"]["Code"]
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_volumes", error_code, error_message)
except NoCredentialsError:
raise AWSServiceError(
"EC2", "describe_volumes", "NoCredentials", "AWS credentials not found or invalid"
)
def get_volume_name(volume_id: str) -> str:
"""Returns the name of the volume.
Args:
volume_id: The volume ID to get name for
Returns:
The volume name from tags, or empty string if no name tag
Raises:
ResourceNotFoundError: If volume not found
AWSServiceError: If AWS API call fails
"""
# Validate input
volume_id = validate_volume_id(volume_id)
try:
response = get_ec2_client().describe_volumes(VolumeIds=[volume_id])
# Validate response structure
validate_aws_response_structure(response, ["Volumes"], "describe_volumes")
volumes = ensure_non_empty_array(list(response["Volumes"]), "volumes")
volume = volumes[0]
# Look for Name tag
for tag in volume.get("Tags", []):
if tag["Key"] == "Name":
return str(tag["Value"])
return "" # No name tag found
except ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code == "InvalidVolumeID.NotFound":
raise ResourceNotFoundError("Volume", volume_id)
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_volumes", error_code, error_message)
def get_snapshot_status(snapshot_id: str) -> str:
"""Returns the status of the snapshot.
Args:
snapshot_id: The snapshot ID to get status for
Returns:
The snapshot status (e.g., 'pending', 'completed', 'error')
Raises:
ResourceNotFoundError: If snapshot not found
AWSServiceError: If AWS API call fails
"""
# Validate input
snapshot_id = validate_snapshot_id(snapshot_id)
try:
response = get_ec2_client().describe_snapshots(SnapshotIds=[snapshot_id])
# Validate response structure
validate_aws_response_structure(response, ["Snapshots"], "describe_snapshots")
snapshots = ensure_non_empty_array(list(response["Snapshots"]), "snapshots")
return str(snapshots[0]["State"])
except ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code == "InvalidSnapshotID.NotFound":
raise ResourceNotFoundError("Snapshot", snapshot_id)
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_snapshots", error_code, error_message)
def get_launch_templates(name_filter: str | None = None) -> list[dict[str, Any]]:
"""Get launch templates, optionally filtered by name pattern.
Args:
name_filter: Optional string to filter templates by name (case-insensitive)
Returns:
List of launch template dictionaries
Raises:
AWSServiceError: If AWS API call fails
"""
try:
response = get_ec2_client().describe_launch_templates()
validate_aws_response_structure(response, ["LaunchTemplates"], "describe_launch_templates")
templates = response["LaunchTemplates"]
if name_filter:
templates = [
t for t in templates if name_filter.lower() in t["LaunchTemplateName"].lower()
]
return cast(list[dict[str, Any]], templates)
except ClientError as e:
error_code = e.response["Error"]["Code"]
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_launch_templates", error_code, error_message)
except NoCredentialsError:
raise AWSServiceError(
"EC2",
"describe_launch_templates",
"NoCredentials",
"AWS credentials not found or invalid",
)
def get_launch_template_versions(template_name: str) -> list[dict[str, Any]]:
"""Get all versions of a launch template.
Args:
template_name: Name of the launch template
Returns:
List of launch template version dictionaries
Raises:
ResourceNotFoundError: If template not found
AWSServiceError: If AWS API call fails
"""
try:
response = get_ec2_client().describe_launch_template_versions(
LaunchTemplateName=template_name
)
validate_aws_response_structure(
response, ["LaunchTemplateVersions"], "describe_launch_template_versions"
)
return cast(list[dict[str, Any]], response["LaunchTemplateVersions"])
except ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code == "InvalidLaunchTemplateName.NotFoundException":
raise ResourceNotFoundError("Launch Template", template_name)
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_launch_template_versions", error_code, error_message)
except NoCredentialsError:
raise AWSServiceError(
"EC2",
"describe_launch_template_versions",
"NoCredentials",
"AWS credentials not found or invalid",
)
def get_launch_template_id(launch_template_name: str) -> str:
"""Get the launch template ID corresponding to a given launch template name.
This function queries AWS EC2 to get details of all launch templates with the specified name.
It then retrieves and returns the ID of the first matching launch template.
Args:
launch_template_name: The name of the launch template
Returns:
The ID of the launch template
Raises:
ResourceNotFoundError: If no launch template found with the given name
AWSServiceError: If AWS API call fails
Example usage:
template_id = get_launch_template_id("my-template-name")
"""
# Validate input
if not launch_template_name or not launch_template_name.strip():
raise ValidationError("Launch template name cannot be empty")
try:
response = get_ec2_client().describe_launch_templates(
Filters=[{"Name": "tag:Name", "Values": [launch_template_name]}]
)
# Validate response structure
validate_aws_response_structure(response, ["LaunchTemplates"], "describe_launch_templates")
launch_templates = response["LaunchTemplates"]
if not launch_templates:
raise ResourceNotFoundError("Launch Template", launch_template_name)
return launch_templates[0]["LaunchTemplateId"]
except ClientError as e:
error_code = e.response["Error"]["Code"]
error_message = e.response["Error"]["Message"]
raise AWSServiceError("EC2", "describe_launch_templates", error_code, error_message)