-
Notifications
You must be signed in to change notification settings - Fork 81
/
ec2.py
1900 lines (1646 loc) · 64.9 KB
/
ec2.py
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import os
import re
from datetime import datetime
import boto3
from boto3 import client as boto3client
from boto3 import resource as boto3resource
from botocore.config import Config
from botocore.exceptions import ClientError
from wrapanapi.const import EC2_INSTANCE
from wrapanapi.entities import (
Instance,
Network,
NetworkMixin,
Stack,
StackMixin,
Template,
TemplateMixin,
VmMixin,
VmState,
Volume,
)
from wrapanapi.exceptions import ActionTimedOutError, MultipleItemsError, NotFoundError
from wrapanapi.systems.base import System
def _regions(regionmodule, regionname):
for region in regionmodule.regions():
if region.name == regionname:
return region
return None
class _SharedMethodsMixin:
"""
Mixin class that holds properties/methods EC2Entities share.
This should be listed first in the child class inheritance to satisfy
the methods required by the Entity abstract base class
"""
@property
def _identifying_attrs(self):
return {"uuid": self._uuid}
@property
def uuid(self):
return self._uuid
def refresh(self):
try:
self.raw.reload()
return True
except Exception:
return False
def get_details(self):
return self.raw
def rename(self, new_name):
self.logger.info(
"setting name of %s %s to %s", self.__class__.__name__, self.uuid, new_name
)
self.raw.create_tags(Tags=[{"Key": "Name", "Value": new_name}])
self.refresh() # update raw
return new_name
class _TagMixin:
def set_tag(self, key, value):
self.system.ec2_connection.create_tags(
Resources=[self.uuid], Tags=[{"Key": key, "Value": value}]
)
def get_tag_value(self, key):
self.refresh()
if self.raw.tags:
for tag in self.raw.tags:
if tag.get("Key") == key:
return tag.get("Value")
return None
def unset_tag(self, key, value):
self.system.ec2_connection.delete_tags(
Resources=[self.uuid], Tags=[{"Key": key, "Value": value}]
)
class EC2Instance(_TagMixin, _SharedMethodsMixin, Instance):
state_map = {
"pending": VmState.STARTING,
"stopping": VmState.STOPPING,
"shutting-down": VmState.STOPPING,
"running": VmState.RUNNING,
"stopped": VmState.STOPPED,
"terminated": VmState.DELETED,
}
def __init__(self, system, raw=None, **kwargs):
"""
Constructor for an EC2Instance tied to a specific system.
Args:
system: an EC2System object
raw: the boto.ec2.instance.Instance object if already obtained, or None
uuid: unique ID of instance
"""
self._uuid = raw.id if raw else kwargs.get("uuid")
if not self._uuid:
raise ValueError("missing required kwarg: 'uuid'")
super().__init__(system, raw, **kwargs)
self._api = self.system.ec2_connection
def __repr__(self):
return f"{type(self)} Id: {self.id}, Name: {self.name}"
@property
def id(self):
return self.raw.id
@property
def name(self):
tag_value = self.get_tag_value("Name")
return getattr(self.raw, "name", None) or tag_value if tag_value else self.id
def _get_state(self):
self.refresh()
return self._api_state_to_vmstate(self.raw.state.get("Name"))
@property
def ip(self):
self.refresh()
return self.raw.public_ip_address
@property
def all_ips(self):
"""Wrapping self.ip to meet abstractproperty requirement
Returns: (list) the addresses assigned to the machine
"""
return [self.ip]
@property
def type(self):
return self.raw.instance_type
@property
def creation_time(self):
self.refresh()
# Example instance.launch_time: datetime.datetime(2019, 3, 13, 14, 45, 33, tzinfo=tzutc())
return self.raw.launch_time
@property
def az(self):
return self.raw.placement["AvailabilityZone"]
def delete(self, timeout=240):
"""
Delete instance. Wait for it to move to 'deleted' state
Returns:
True if successful
False if otherwise, or action timed out
"""
self.logger.info("terminating EC2 instance '%s'", self.uuid)
try:
self.raw.terminate()
self.wait_for_state(VmState.DELETED, timeout=timeout)
return True
except ActionTimedOutError:
return False
def cleanup(self):
return self.delete()
def start(self, timeout=240):
"""
Start instance. Wait for it to move to 'running' state
Returns:
True if successful
False if otherwise, or action timed out
"""
self.logger.info("starting EC2 instance '%s'", self.uuid)
try:
self.raw.start()
self.wait_for_state(VmState.RUNNING, timeout=timeout)
return True
except ActionTimedOutError:
return False
def stop(self, timeout=360):
"""
Stop instance. Wait for it to move to 'stopped' state
Returns:
True if successful
False if otherwise, or action timed out
"""
self.logger.info("stopping EC2 instance '%s'", self.uuid)
try:
self.raw.stop()
self.wait_for_state(VmState.STOPPED, timeout=timeout)
return True
except ActionTimedOutError:
return False
def restart(self):
"""
Restart instance
The action is taken in two separate calls to EC2. A 'False' return can
indicate a failure of either the stop action or the start action.
Note: There is a reboot_instances call available on the API, but it provides
less insight than blocking on stop_vm and start_vm. Furthermore,
there is no "rebooting" state, so there are potential monitoring
issues that are avoided by completing these steps atomically
Returns:
True if stop and start succeeded
False if otherwise, or action timed out
"""
self.logger.info("restarting EC2 instance '%s'", self.uuid)
stopped = self.stop()
if not stopped:
self.logger.error("Stopping instance '%s' failed or timed out", self.uuid)
started = self.start()
if not started:
self.logger.error("Starting instance '%s' failed or timed out", self.uuid)
return stopped and started
def change_type(self, instance_type):
try:
self.raw.modify_attribute(InstanceType={"Value": instance_type})
return True
except Exception:
return False
class StackStates:
ACTIVE = ["CREATE_COMPLETE", "ROLLBACK_COMPLETE", "CREATE_FAILED", "UPDATE_ROLLBACK_COMPLETE"]
COMPLETE = ["CREATE_COMPLETE", "UPDATE_ROLLBACK_COMPLETE"]
FAILED = [
"ROLLBACK_COMPLETE",
"CREATE_FAILED",
"ROLLBACK_FAILED",
"DELETE_FAILED",
"UPDATE_ROLLBACK_FAILED",
]
DELETED = ["DELETE_COMPLETE"]
IN_PROGRESS = [
"CREATE_IN_PROGRESS",
"ROLLBACK_IN_PROGRESS",
"DELETE_IN_PROGRESS",
"UPDATE_IN_PROGRESS",
"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_ROLLBACK_IN_PROGRESS",
"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS",
"REVIEW_IN_PROGRESS",
]
ALL = [
"CREATE_IN_PROGRESS",
"CREATE_FAILED",
"CREATE_COMPLETE",
"ROLLBACK_IN_PROGRESS",
"ROLLBACK_FAILED",
"ROLLBACK_COMPLETE",
"DELETE_IN_PROGRESS",
"DELETE_FAILED",
"DELETE_COMPLETE",
"UPDATE_IN_PROGRESS",
"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_COMPLETE",
"UPDATE_ROLLBACK_IN_PROGRESS",
"UPDATE_ROLLBACK_FAILED",
"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_ROLLBACK_COMPLETE",
"REVIEW_IN_PROGRESS",
]
class CloudFormationStack(_TagMixin, _SharedMethodsMixin, Stack):
def __init__(self, system, raw=None, **kwargs):
"""
Represents a CloudFormation stack
Args:
system: instance of EC2System
raw: raw dict for this stack returned by boto CloudFormation.Client.describe_stacks()
uuid: the stack ID
"""
self._uuid = raw.stack_id if raw else kwargs.get("uuid")
if not self._uuid:
raise ValueError("missing required kwarg: 'uuid'")
super().__init__(system, raw, **kwargs)
self._api = self.system.cloudformation_connection
@property
def name(self):
return self.raw.name
@property
def creation_time(self):
self.refresh()
return self.raw.creation_time
@property
def status_active(self):
self.refresh()
return self.raw.stack_status in StackStates.ACTIVE
def delete(self):
"""
Removes the stack on the provider
Returns:
True if delete was successful
False otherwise
"""
self.logger.info("terminating EC2 stack '%s', id: '%s'", self.name, self.uuid)
try:
self.raw.delete()
return True
except ActionTimedOutError:
return False
def cleanup(self):
"""
Removes the stack on the provider and any of its associated resources
"""
return self.delete()
def rename(self, new_name):
raise NotImplementedError
class EC2Image(_TagMixin, _SharedMethodsMixin, Template):
def __init__(self, system, raw=None, **kwargs):
"""
Constructor for an EC2Image tied to a specific system.
Args:
system: an EC2System object
raw: the boto.ec2.image.Image object if already obtained, or None
uuid: unique ID of the image
"""
self._uuid = raw.id if raw else kwargs.get("uuid")
if not self._uuid:
raise ValueError("missing required kwarg: 'uuid'")
super().__init__(system, raw, **kwargs)
self._api = self.system.ec2_connection
@property
def name(self):
tag_value = self.get_tag_value("Name")
return tag_value if tag_value else self.raw.name
def delete(self):
"""
Deregister the EC2 image
"""
return self.raw.deregister()
def cleanup(self):
"""
Deregister the EC2 image and delete the snapshot
"""
return self.delete()
def deploy(self, *args, **kwargs):
"""
Deploy ec2 instance(s) using this template
Args/kwargs are passed to EC2System.create_vm(), the image_id arg
will be this image's ID
"""
return self.system.create_vm(image_id=self.uuid, *args, **kwargs)
class EC2Vpc(_TagMixin, _SharedMethodsMixin, Network):
def __init__(self, system, raw=None, **kwargs):
"""
Constructor for an EC2Network tied to a specific system.
Args:
system: an EC2System object
raw: the boto.ec2.network.Network object if already obtained, or None
uuid: unique ID of the network
"""
self._uuid = raw.id if raw else kwargs.get("uuid")
if not self._uuid:
raise ValueError("missing required kwarg: 'uuid'")
super().__init__(system, raw, **kwargs)
self._api = self.system.ec2_connection
@property
def name(self):
tag_value = self.get_tag_value("Name")
return tag_value if tag_value else self.raw.id
def delete(self):
"""
Delete Network
"""
self.logger.info("Deleting EC2Vpc '%s', id: '%s'", self.name, self.uuid)
try:
self.raw.delete()
return True
except ActionTimedOutError:
return False
def cleanup(self):
"""
Cleanup Network
"""
return self.delete()
class EBSVolume(_TagMixin, _SharedMethodsMixin, Volume):
def __init__(self, system, raw=None, **kwargs):
"""
Constructor for an EBSVolume tied to a specific system.
Args:
system: an EC2System object
raw: the boto.ec2.volume.Volume object if already obtained, or None
uuid: unique ID of the volume
"""
self._uuid = raw.id if raw else kwargs.get("uuid")
if not self._uuid:
raise ValueError("missing required kwarg: 'uuid'")
super().__init__(system, raw, **kwargs)
self._api = self.system.ec2_connection
@property
def name(self):
tag_value = self.get_tag_value("Name")
return tag_value if tag_value else self.raw.id
def resize(self, new_size):
try:
self._api.modify_volume(VolumeId=self.uuid, Size=new_size)
self.refresh()
return new_size
except Exception:
return False
def attach(self, instance_id, device="/dev/sdh"):
try:
self.raw.attach_to_instance(Device=device, InstanceId=instance_id)
self.refresh()
return True
except Exception:
return False
def detach(self, instance_id, device="/dev/sdh", force=False):
try:
self.raw.detach_from_instance(Device=device, InstanceId=instance_id, Force=force)
self.refresh()
return True
except Exception:
return False
def delete(self):
"""
Delete Volume
"""
self.logger.info("Deleting EBSVolume '%s', id: '%s'", self.name, self.uuid)
try:
self.raw.delete()
return True
except ActionTimedOutError:
return False
def cleanup(self):
"""
Cleanup Volume
"""
return self.delete()
class ResourceExplorerResource:
"""
This class represents a resource returned by Resource Explorer.
"""
def __init__(self, arn, region, resource_type, service, properties, **kwargs):
self.arn = arn
self.region = region
self.resource_type = resource_type
self.service = service
self.properties = properties
if self.resource_type == EC2_INSTANCE and kwargs:
if system := kwargs.get("system"):
kwargs["raw"] = system.ec2_resource.Instance(self.id)
kwargs["uuid"] = self.id
# When Calling the raw ec2_instance with non-matching AWS Client Region,
# the API call fails with a 'ClientError' (InvalidInstanceID.NotFound)
self.ec2_instance = EC2Instance(**kwargs)
@property
def id(self) -> str:
"""
Returns the last part of the arn.
This part is used as id in aws cli.
"""
# According to the docs:
# https://docs.aws.amazon.com/quicksight/latest/APIReference/qs-arn-format.html
# ARNs can end in either scheme: {ARN_VALUE}:resource-id, {ARN_VALUE}/resource-id
if self.arn:
arn = self.arn.split(":")[-1]
if "/" in arn:
arn = arn.split("/")[-1]
return arn
return None
def __repr__(self):
return f"{type(self)} Id: {self.id}, Type: {self.resource_type}"
def get_tag_value(self, key) -> str:
"""
Returns a tag value for a given tag key.
Tags are taken from the resource properties.
Args:
key: a tag key
"""
tags = self.get_tags(regex=f"^{key}$")
if len(tags) > 0:
return tags[0].get("Value")
return None
def get_tags(self, regex="") -> list[dict]:
"""
Returns a list of tags (a dict with keys 'Key' and 'Value').
Tags are taken from the resource properties.
Args:
regex: a regular expressions for keys, default is ""
"""
list = []
for property in self.properties:
data = property.get("Data")
for tag in data:
key = tag.get("Key")
if re.match(regex, key):
list.append(tag)
return list
@property
def name(self) -> str:
"""
Returns a name for the resource derived from the associated tag with key 'Name'.
If there is no such tag then the name is the id from arn.
"""
name = self.get_tag_value("Name")
if not name:
name = self.id
return name
@property
def date_modified(self) -> datetime:
"""
Returns the time reference of the "LastReportedAt" tag, by the latest value.
If the tag doesn't exist, returns the current time.
Used for filtering resources by the latest modified time recorded.
Example:
datetime.datetime(2019, 3, 13, 14, 45, 33, tzinfo=tzutc())
"""
modified_date = None
if self.properties:
modified_date = max(self.properties, key=lambda x: x == "LastReportedAt").get(
"LastReportedAt"
)
return modified_date
class EC2System(System, VmMixin, TemplateMixin, StackMixin, NetworkMixin):
"""EC2 Management System, powered by boto
Wraps the EC2 API
Instead of username and password, accepts access_key_id and
secret_access_key, the AWS analogs to those ideas. These are passed, along
with any kwargs, straight through to boto's EC2 connection factory. This
allows customization of the EC2 connection, to connect to another region,
for example.
For the purposes of the EC2 system, a VM's instance ID is its name because
EC2 instances don't have to have unique names.
Args:
*kwargs: Arguments to connect, usually, username, password, region.
Returns: A :py:class:`EC2System` object.
"""
_stats_available = {
"num_vm": lambda self: len(self.list_vms()),
"num_template": lambda self: len(self.list_templates()),
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._username = kwargs.get("username")
self._password = kwargs.get("password")
self._region_name = kwargs.get("region")
connection_config = Config(signature_version="s3v4", retries=dict(max_attempts=10))
connection_kwargs = {
"aws_access_key_id": self._username,
"aws_secret_access_key": self._password,
"region_name": self._region_name,
"config": connection_config,
}
self.sqs_connection = boto3client("sqs", **connection_kwargs)
self.elb_connection = boto3client("elb", **connection_kwargs)
self.s3_connection = boto3resource("s3", **connection_kwargs)
self.s3_client = boto3client("s3", **connection_kwargs)
self.ec2_connection = boto3client("ec2", **connection_kwargs)
self.ec2_resource = boto3resource("ec2", **connection_kwargs)
self.ecr_connection = boto3client("ecr", **connection_kwargs)
self.cloudformation_connection = boto3client("cloudformation", **connection_kwargs)
self.cloudformation_resource = boto3resource("cloudformation", **connection_kwargs)
self.ssm_connection = boto3client("ssm", **connection_kwargs)
self.sns_connection = boto3client("sns", **connection_kwargs)
self.cw_events_connection = boto3client("events", **connection_kwargs)
self.resource_explorer_connection = boto3client("resource-explorer-2", **connection_kwargs)
self.kwargs = kwargs
@property
def _identifying_attrs(self):
return {"username": self._username, "password": self._password, "region": self._region_name}
@property
def can_suspend(self):
return False
@property
def can_pause(self):
return False
def disconnect(self):
"""Disconnect from the EC2 API -- NOOP
AWS EC2 service is stateless, so there's nothing to disconnect from
"""
pass
def info(self):
"""Returns the current versions of boto3"""
return boto3.__version__
def _get_resource(self, resource, find_method, name=None, id=None, **kwargs):
"""
Get a single resource with name equal to 'name' or id equal to 'id'
Must be a unique name or id
Args:
resource: Class of entity to get
find_method: Find method of entity get will use
name: name of resource
id: id of resource
Returns:
resource object
Raises:
NotFoundError if no resource exists with this name/id
MultipleItemsError if name/id is not unique
"""
resource_name = resource.__name__
if not name and not id or name and id:
raise ValueError("Either name or id must be set and not both!")
resources = find_method(name=name, id=id, **kwargs)
name_or_id = name if name else id
if not resources:
raise NotFoundError(
"{} with {} {} not found".format(
resource_name, "name" if name else "id", name_or_id
)
)
elif len(resources) > 1:
raise MultipleItemsError(
"Multiple {}s with {} {} found".format(
resource_name, "name" if name else "id", name_or_id
)
)
return resources[0]
def _get_instances(self, **kwargs):
"""
Gets instance reservations and parses instance objects
"""
reservations = self.ec2_connection.describe_instances(**kwargs).get("Reservations")
instances = list()
for reservation in reservations:
for instance in reservation.get("Instances"):
instance_id = instance.get("InstanceId")
instances.append(
EC2Instance(
system=self, raw=self.ec2_resource.Instance(instance_id), uuid=instance_id
)
)
return instances
@staticmethod
def _add_filter_for_terminated(kwargs_dict):
new_filter = {
"Name": "instance-state-name",
"Values": [
api_state
for api_state, vm_state in EC2Instance.state_map.items()
if vm_state is not VmState.DELETED
],
}
if "Filters" not in kwargs_dict:
kwargs_dict["Filters"] = [new_filter]
else:
kwargs_dict["Filters"].append(new_filter)
return kwargs_dict
def find_vms(self, name=None, id=None, filters=None, hide_deleted=True):
"""
Find instance on ec2 system
Supported queries include searching by name tag, id, or passing
in a specific filters dict to the system API. You can only
select one of these methods.
Args:
name (str): name of instance (which is a tag)
id (str): id of instance
filters (dict): filters to pass along to system.api.get_all_instances()
hide_deleted: do not list an instance if it has been terminated
Returns:
List of EC2Instance objects that match
"""
# Validate args
filled_args = [
arg
for arg in (
name,
id,
filters,
)
if arg
]
if not filled_args or len(filled_args) > 1:
raise ValueError("You must select one of these search methods: name, id, or filters")
if id:
kwargs = {"InstanceIds": [id]}
elif filters:
kwargs = {"Filters": filters}
elif name:
# Quick validation that the instance name isn't actually an ID
pattern = re.compile(r"^i-\w{8,17}$")
if pattern.match(name):
# Switch to using the id search method
kwargs = {"InstanceIds": [name]}
else:
kwargs = {"Filters": [{"Name": "tag:Name", "Values": [name]}]}
if hide_deleted:
self._add_filter_for_terminated(kwargs)
instances = self._get_instances(**kwargs)
return instances
def get_vm(self, name=None, id=None):
"""
Get a single EC2Instance with name or id equal to 'name'
Must be a unique name
Args:
name: name or id of instance
Returns:
EC2Instance object
Raises:
NotFoundError if no instance exists with this name/id
MultipleItemsError if name is not unique
"""
return self._get_resource(name=name, id=id, resource=EC2Instance, find_method=self.find_vms)
def list_vms(self, hide_deleted=True):
"""
Returns a list of instances currently active on EC2 (not terminated)
"""
kwargs = {}
if hide_deleted:
self._add_filter_for_terminated(kwargs)
return [inst for inst in self._get_instances(**kwargs)]
def create_vm(
self, image_id, min_count=1, max_count=1, instance_type="t1.micro", vm_name="", **kwargs
):
"""
Creates aws instances.
TODO:
Check whether instances were really created.
Add additional arguments to be able to modify settings for instance creation.
Args:
image_id: ID of AMI
min_count: Minimal count of instances - useful only if creating thousand of instances
max_count: Maximal count of instances - defaults to 1
instance_type: Type of instances, catalog of instance types is here:
https://aws.amazon.com/ec2/instance-types/
Defaults to 't1.micro' which is the least expensive instance type
vm_name: Name of instances, can be blank
Returns:
List of EC2Instance objects for all instances created
"""
self.logger.debug("ec2.create_vm() -- Ignored kwargs: %s", kwargs)
self.logger.info(
"Creating instances[%d] with name %s,type %s and image ID: %s ",
max_count,
vm_name,
instance_type,
image_id,
)
try:
result = self.ec2_connection.run_instances(
ImageId=image_id,
MinCount=min_count,
MaxCount=max_count,
InstanceType=instance_type,
TagSpecifications=[
{
"ResourceType": "instance",
"Tags": [
{
"Key": "Name",
"Value": vm_name,
},
],
},
],
)
except Exception:
self.logger.exception("Create of instance '%s' failed.", vm_name)
raise
try:
instances_json = result["Instances"]
instance_ids = [entry["InstanceId"] for entry in instances_json]
except KeyError:
self.logger.exception("Unable to parse all InstanceId's from response json")
raise
instances = [
EC2Instance(system=self, raw=self.ec2_resource.Instance(uuid), uuid=uuid)
for uuid in instance_ids
]
for instance in instances:
self.logger.info("Waiting for instance '%s' to reach steady state", instance.uuid)
instance.wait_for_steady_state()
if len(instances) == 1:
return instances[0]
else:
return instances
def list_stacks(self, stack_status_filter=StackStates.ACTIVE):
"""
Returns a list of Stack objects
stack_status_filter: list of stack statuses to filter for. See ``StackStates``
"""
stack_list = [
CloudFormationStack(
system=self,
uuid=stack_summary["StackId"],
raw=self.cloudformation_resource.Stack(stack_summary["StackName"]),
)
for stack_summary in self.cloudformation_connection.list_stacks()["StackSummaries"]
if stack_summary["StackStatus"] in stack_status_filter
]
return stack_list
def find_stacks(self, name=None, id=None):
"""
Return list of all stacks with given name or id
According to boto3 docs, you can use name or ID in these situations:
"Running stacks: You can specify either the stack's name or its unique stack ID.
Deleted stacks: You must specify the unique stack ID."
If 'name' kwarg is given and we fail to locate the stack initially, we will retry with
'list_stacks' to get the list of all stacks with this name (even if they are deleted)
If 'id' kwarg is given and we hit an error finding it, we don't call list_stacks. This
is the more efficient kwarg to use if you are searching specifically by id.
Args:
name: name to search for
id: id to search for
Returns:
List of CloudFormationStack objects
"""
if not name and not id:
raise ValueError("missing one of required kwargs: name, id")
if name:
searching_by_name = True
name_or_id = name
elif id:
searching_by_name = False
name_or_id = id
stack_list = []
try:
# Try to find by name/id directly by using describe_stacks
stack_list = [
CloudFormationStack(
system=self,
uuid=stack["StackId"],
raw=self.cloudformation_resource.Stack(stack["StackName"]),
)
for stack in self.cloudformation_connection.describe_stacks(StackName=name_or_id)[
"Stacks"
]
]
except ClientError as error:
# Stack not found, if searching by name, look through deleted stacks...
if searching_by_name and f"Stack with id {name} does not exist" in str(error):
stack_list = [
CloudFormationStack(
system=self,
uuid=stack_summary["StackId"],
raw=self.cloudformation_resource.Stack(stack_summary["StackName"]),
)
for stack_summary in self.cloudformation_connection.list_stacks()[
"StackSummaries"
]
if stack_summary["StackName"] == name
]
return stack_list
def get_stack(self, name):
"""
Get single stack if it exists
Args:
name: unique name or id of the stack
Returns:
CloudFormationStack object
"""
return self._get_resource(
name=name, resource=CloudFormationStack, find_method=self.find_stacks
)
def list_templates(self, executable_by_me=True, owned_by_me=True, public=False):
"""
List images on ec2 of image-type 'machine'
Args:
executable_by_me: search images executable by me (default True)
owned_by_me: search images owned only by me (default True)
public: search public images (default False)
"""
img_filter = [{"Name": "image-type", "Values": ["machine"]}]
if not any([public, executable_by_me, owned_by_me]):
raise ValueError(
"One of the following must be 'True': owned_by_me, executable_by_me, public"
)
images = []
if public:
img_filter.append({"Name": "is-public", "Values": ["true"]})
images.extend(self.ec2_connection.describe_images(Filters=img_filter).get("Images"))
if executable_by_me:
images.extend(
self.ec2_connection.describe_images(
ExecutableUsers=["self"], Filters=img_filter
).get("Images")
)
if owned_by_me:
images.extend(