Repository navigation
Expand file tree
/
Copy pathtest_ec2.py
More file actions
4744 lines (4014 loc) · 197 KB
/
Copy pathtest_ec2.py
File metadata and controls
4744 lines (4014 loc) · 197 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
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 ipaddress
import json
import os
import time
import urllib.error
import urllib.request
import uuid as _uuid_mod
from urllib.parse import urlencode
import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
def _ec2_client(region, account_id="test"):
return boto3.client(
"ec2",
endpoint_url=ENDPOINT,
region_name=region,
aws_access_key_id=account_id,
aws_secret_access_key="test",
config=Config(region_name=region),
)
def _create_ec2_iam_instance_profile(iam, suffix):
assume = json.dumps(
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole",
}
],
}
)
role_name = f"ec2-ip-role-{suffix}"
profile_name = f"ec2-ip-{suffix}"
iam.create_role(RoleName=role_name, AssumeRolePolicyDocument=assume)
profile = iam.create_instance_profile(
InstanceProfileName=profile_name
)["InstanceProfile"]
iam.add_role_to_instance_profile(
InstanceProfileName=profile_name,
RoleName=role_name,
)
return role_name, profile_name, profile
def _delete_ec2_iam_instance_profile(iam, role_name, profile_name):
try:
iam.remove_role_from_instance_profile(
InstanceProfileName=profile_name,
RoleName=role_name,
)
except ClientError:
pass
try:
iam.delete_instance_profile(InstanceProfileName=profile_name)
except ClientError:
pass
try:
iam.delete_role(RoleName=role_name)
except ClientError:
pass
def test_ec2_describe_vpcs_default(ec2):
resp = ec2.describe_vpcs()
vpcs = resp["Vpcs"]
assert any(v["IsDefault"] for v in vpcs)
def test_ec2_describe_subnets_default(ec2):
resp = ec2.describe_subnets()
assert len(resp["Subnets"]) >= 1
def test_ec2_describe_availability_zones(ec2):
resp = ec2.describe_availability_zones()
azs = [az["ZoneName"] for az in resp["AvailabilityZones"]]
assert any("us-east-1" in az for az in azs)
def test_ec2_availability_zone_ids_are_region_coded(ec2):
"""ZoneId is the account-stable id ("use1-az1"), never the account-local ZoneName: code
handed an id has to resolve it here, and an id that equals the name hides that requirement
until it runs against real AWS."""
zones = ec2.describe_availability_zones()["AvailabilityZones"]
assert [z["ZoneId"] for z in zones] == ["use1-az1", "use1-az2", "use1-az3"]
assert all(z["ZoneId"] != z["ZoneName"] for z in zones)
assert [z["ZoneName"] for z in zones] == ["us-east-1a", "us-east-1b", "us-east-1c"]
assert all(z["RegionName"] == "us-east-1" and z["State"] == "available" for z in zones)
# The prefix follows AWS's own coding, including the compound directions.
from ministack.services.ec2 import _az_id_prefix
assert _az_id_prefix("eu-central-1") == "euc1"
assert _az_id_prefix("ap-southeast-2") == "apse2"
assert _az_id_prefix("ap-northeast-1") == "apne1"
assert _az_id_prefix("us-west-2") == "usw2"
assert _az_id_prefix("ca-central-1") == "cac1"
assert _az_id_prefix("sa-east-1") == "sae1"
# A partitioned region keeps every part between the geography and the index.
assert _az_id_prefix("us-gov-west-1") == "usgw1"
assert _az_id_prefix("cn-northwest-1") == "cnnw1"
def test_ec2_availability_zones_carry_group_and_opt_in(ec2):
"""GroupName / NetworkBorderGroup / OptInStatus are optional members, so leaving
them out reads to an SDK as "no value" rather than as an error: a caller filtering
on opt_in_status or grouping by group_names gets a wrong answer, not a failure."""
zones = ec2.describe_availability_zones()["AvailabilityZones"]
assert all(z["GroupName"] == "us-east-1-zg-1" for z in zones)
assert all(z["NetworkBorderGroup"] == "us-east-1" for z in zones)
assert all(z["OptInStatus"] == "opt-in-not-required" for z in zones)
def test_ec2_availability_zones_carry_zone_type(ec2):
"""ZoneType is another optional member: a consumer that branches on it (the AWS
Load Balancer Controller's subnet locale resolution) gets an empty string, not
an error, when it's missing — and fails its own validation on that empty value.
Every zone ministack fabricates is a standard Availability Zone."""
zones = ec2.describe_availability_zones()["AvailabilityZones"]
assert all(z["ZoneType"] == "availability-zone" for z in zones)
def test_ec2_describe_regions_returns_commercial_regions(ec2):
"""DescribeRegions must list at least the four legacy us-* regions
with opt-in-not-required, and emit the shape AWS returns."""
resp = ec2.describe_regions()
regions = {r["RegionName"]: r for r in resp["Regions"]}
for name in ("us-east-1", "us-east-2", "us-west-1", "us-west-2"):
assert name in regions
assert regions[name]["OptInStatus"] == "opt-in-not-required"
assert regions[name]["Endpoint"] == f"ec2.{name}.amazonaws.com"
def test_ec2_describe_regions_with_filter(ec2):
resp = ec2.describe_regions(RegionNames=["us-east-1", "eu-west-1"])
names = {r["RegionName"] for r in resp["Regions"]}
assert names == {"us-east-1", "eu-west-1"}
def test_ec2_describe_regions_all_regions_includes_opt_in(ec2):
base = len(ec2.describe_regions()["Regions"])
full = len(ec2.describe_regions(AllRegions=True)["Regions"])
assert full == base
assert base >= 30
def test_ec2_default_network_resources_are_region_scoped():
east = _ec2_client("us-east-1")
west = _ec2_client("us-west-2")
east_vpcs = east.describe_vpcs(
Filters=[{"Name": "is-default", "Values": ["true"]}]
)["Vpcs"]
west_vpcs = west.describe_vpcs(
Filters=[{"Name": "is-default", "Values": ["true"]}]
)["Vpcs"]
assert len(east_vpcs) == 1
assert len(west_vpcs) == 1
east_subnets = east.describe_subnets(
Filters=[{"Name": "vpc-id", "Values": [east_vpcs[0]["VpcId"]]}]
)["Subnets"]
west_subnets = west.describe_subnets(
Filters=[{"Name": "vpc-id", "Values": [west_vpcs[0]["VpcId"]]}]
)["Subnets"]
west_default_sgs = west.describe_security_groups(
Filters=[
{"Name": "vpc-id", "Values": [west_vpcs[0]["VpcId"]]},
{"Name": "group-name", "Values": ["default"]},
]
)["SecurityGroups"]
assert {s["AvailabilityZone"] for s in east_subnets} == {
"us-east-1a",
"us-east-1b",
"us-east-1c",
}
assert {s["AvailabilityZone"] for s in west_subnets} == {
"us-west-2a",
"us-west-2b",
"us-west-2c",
}
assert len(west_default_sgs) == 1
assert west_default_sgs[0]["VpcId"] == west_vpcs[0]["VpcId"]
def test_ec2_named_resources_and_tags_are_region_scoped():
east = _ec2_client("us-east-1")
west = _ec2_client("us-west-2")
suffix = _uuid_mod.uuid4().hex[:8]
key_name = f"qa-ec2-key-region-{suffix}"
pg_name = f"qa-ec2-pg-region-{suffix}"
sg_name = f"qa-ec2-sg-region-{suffix}"
east.create_key_pair(KeyName=key_name)
west.create_key_pair(KeyName=key_name)
east.create_placement_group(GroupName=pg_name, Strategy="cluster")
west.create_placement_group(GroupName=pg_name, Strategy="cluster")
east_sg = east.create_security_group(GroupName=sg_name, Description="east")
west_sg = west.create_security_group(GroupName=sg_name, Description="west")
east.create_tags(Resources=[east_sg["GroupId"]], Tags=[{"Key": "Region", "Value": "east"}])
west.create_tags(Resources=[west_sg["GroupId"]], Tags=[{"Key": "Region", "Value": "west"}])
east_instance = east.run_instances(
ImageId="ami-00000000",
MinCount=1,
MaxCount=1,
InstanceType="t2.micro",
)["Instances"][0]
try:
east_key = east.describe_key_pairs(KeyNames=[key_name])["KeyPairs"][0]
west_key = west.describe_key_pairs(KeyNames=[key_name])["KeyPairs"][0]
east_pg = east.describe_placement_groups(GroupNames=[pg_name])["PlacementGroups"][0]
west_pg = west.describe_placement_groups(GroupNames=[pg_name])["PlacementGroups"][0]
east_group = east.describe_security_groups(GroupIds=[east_sg["GroupId"]])[
"SecurityGroups"
][0]
west_group = west.describe_security_groups(GroupIds=[west_sg["GroupId"]])[
"SecurityGroups"
][0]
east_instances = east.describe_instances(InstanceIds=[east_instance["InstanceId"]])[
"Reservations"
][0]["Instances"]
assert east_key["KeyPairId"] != west_key["KeyPairId"]
assert ":us-east-1:" in east_pg["GroupArn"]
assert ":us-west-2:" in west_pg["GroupArn"]
assert east_group["Description"] == "east"
assert west_group["Description"] == "west"
assert east_instances[0]["InstanceId"] == east_instance["InstanceId"]
assert east.describe_tags(
Filters=[{"Name": "resource-id", "Values": [east_sg["GroupId"]]}]
)["Tags"][0]["Value"] == "east"
assert west.describe_tags(
Filters=[{"Name": "resource-id", "Values": [west_sg["GroupId"]]}]
)["Tags"][0]["Value"] == "west"
with pytest.raises(ClientError):
east.describe_security_groups(GroupIds=[west_sg["GroupId"]])
with pytest.raises(ClientError):
west.describe_instances(InstanceIds=[east_instance["InstanceId"]])
finally:
try:
east.terminate_instances(InstanceIds=[east_instance["InstanceId"]])
except ClientError:
pass
for client, sg_id in ((east, east_sg["GroupId"]), (west, west_sg["GroupId"])):
try:
client.delete_security_group(GroupId=sg_id)
except ClientError:
pass
for client in (east, west):
try:
client.delete_key_pair(KeyName=key_name)
except ClientError:
pass
try:
client.delete_placement_group(GroupName=pg_name)
except ClientError:
pass
def test_ec2_run_describe_terminate_instances(ec2):
resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1, InstanceType="t2.micro")
assert len(resp["Instances"]) == 1
instance_id = resp["Instances"][0]["InstanceId"]
assert instance_id.startswith("i-")
assert resp["Instances"][0]["State"]["Name"] == "running"
desc = ec2.describe_instances(InstanceIds=[instance_id])
assert len(desc["Reservations"]) == 1
assert desc["Reservations"][0]["Instances"][0]["InstanceId"] == instance_id
term = ec2.terminate_instances(InstanceIds=[instance_id])
assert term["TerminatingInstances"][0]["CurrentState"]["Name"] == "terminated"
def test_ec2_run_instances_honors_private_ip_and_iam_profile(ec2):
"""RunInstances must reflect --private-ip-address and --iam-instance-profile
on the created instance and in DescribeInstances. Regression for issue #594."""
profile_arn = "arn:aws:iam::000000000000:instance-profile/ec2-test-profile"
resp = ec2.run_instances(
ImageId="ami-12345678",
MinCount=1,
MaxCount=1,
InstanceType="t3.micro",
PrivateIpAddress="172.31.0.42",
IamInstanceProfile={"Arn": profile_arn},
)
inst = resp["Instances"][0]
iid = inst["InstanceId"]
try:
# PrivateIpAddress is the value the caller passed, not a random one,
# and is well-formed (4 octets ≤ 255).
assert inst["PrivateIpAddress"] == "172.31.0.42"
assert all(0 <= int(o) <= 255 for o in inst["PrivateIpAddress"].split("."))
# PrivateDnsName is derived from the assigned IP, not malformed.
assert inst["PrivateDnsName"] == "ip-172-31-0-42.ec2.internal"
# IamInstanceProfile is attached and surfaced.
assert inst["IamInstanceProfile"]["Arn"] == profile_arn
assert inst["IamInstanceProfile"]["Id"]
# DescribeInstances surfaces the same.
desc = ec2.describe_instances(InstanceIds=[iid])
d_inst = desc["Reservations"][0]["Instances"][0]
assert d_inst["PrivateIpAddress"] == "172.31.0.42"
assert d_inst["IamInstanceProfile"]["Arn"] == profile_arn
finally:
ec2.terminate_instances(InstanceIds=[iid])
def test_ec2_run_instances_with_real_iam_profile_creates_association(iam, ec2):
suffix = f"launch-{_uuid_mod.uuid4().hex[:8]}"
role_name, profile_name, profile = _create_ec2_iam_instance_profile(iam, suffix)
resp = ec2.run_instances(
ImageId="ami-12345678",
MinCount=1,
MaxCount=1,
InstanceType="t3.micro",
IamInstanceProfile={"Name": profile_name},
)
inst = resp["Instances"][0]
iid = inst["InstanceId"]
try:
assert inst["IamInstanceProfile"]["Arn"] == profile["Arn"]
assert inst["IamInstanceProfile"]["Id"] == profile["InstanceProfileId"]
described = ec2.describe_iam_instance_profile_associations(
Filters=[{"Name": "instance-id", "Values": [iid]}]
)["IamInstanceProfileAssociations"]
assert len(described) == 1
assoc = described[0]
assert assoc["AssociationId"].startswith("iip-assoc-")
assert assoc["InstanceId"] == iid
assert assoc["State"] == "associated"
assert assoc["IamInstanceProfile"]["Arn"] == profile["Arn"]
assert assoc["IamInstanceProfile"]["Id"] == profile["InstanceProfileId"]
ec2.terminate_instances(InstanceIds=[iid])
active = ec2.describe_iam_instance_profile_associations(
Filters=[
{"Name": "instance-id", "Values": [iid]},
{"Name": "state", "Values": ["associated"]},
]
)["IamInstanceProfileAssociations"]
assert active == []
all_states = ec2.describe_iam_instance_profile_associations(
AssociationIds=[assoc["AssociationId"]]
)["IamInstanceProfileAssociations"]
assert len(all_states) == 1
assert all_states[0]["State"] == "disassociated"
finally:
try:
ec2.terminate_instances(InstanceIds=[iid])
except ClientError:
pass
_delete_ec2_iam_instance_profile(iam, role_name, profile_name)
def test_ec2_iam_instance_profile_association_lifecycle(iam, ec2):
suffix = _uuid_mod.uuid4().hex[:8]
role_a, profile_a_name, profile_a = _create_ec2_iam_instance_profile(
iam, f"a-{suffix}"
)
role_b, profile_b_name, profile_b = _create_ec2_iam_instance_profile(
iam, f"b-{suffix}"
)
resp = ec2.run_instances(ImageId="ami-12345678", MinCount=1, MaxCount=1)
iid = resp["Instances"][0]["InstanceId"]
try:
assoc = ec2.associate_iam_instance_profile(
InstanceId=iid,
IamInstanceProfile={"Name": profile_a_name},
)["IamInstanceProfileAssociation"]
assert assoc["State"] == "associated"
assert assoc["IamInstanceProfile"]["Arn"] == profile_a["Arn"]
assert assoc["IamInstanceProfile"]["Id"] == profile_a["InstanceProfileId"]
all_assocs = ec2.describe_iam_instance_profile_associations()[
"IamInstanceProfileAssociations"
]
assert any(
item["AssociationId"] == assoc["AssociationId"] for item in all_assocs
)
by_instance = ec2.describe_iam_instance_profile_associations(
Filters=[{"Name": "instance-id", "Values": [iid]}]
)["IamInstanceProfileAssociations"]
assert len(by_instance) == 1
assert by_instance[0]["AssociationId"] == assoc["AssociationId"]
replaced = ec2.replace_iam_instance_profile_association(
AssociationId=assoc["AssociationId"],
IamInstanceProfile={"Arn": profile_b["Arn"]},
)["IamInstanceProfileAssociation"]
assert replaced["AssociationId"] == assoc["AssociationId"]
assert replaced["State"] == "associated"
assert replaced["IamInstanceProfile"]["Arn"] == profile_b["Arn"]
assert replaced["IamInstanceProfile"]["Id"] == profile_b["InstanceProfileId"]
inst = ec2.describe_instances(InstanceIds=[iid])["Reservations"][0]["Instances"][0]
assert inst["IamInstanceProfile"]["Arn"] == profile_b["Arn"]
assert inst["IamInstanceProfile"]["Id"] == profile_b["InstanceProfileId"]
disassoc = ec2.disassociate_iam_instance_profile(
AssociationId=assoc["AssociationId"]
)["IamInstanceProfileAssociation"]
assert disassoc["AssociationId"] == assoc["AssociationId"]
assert disassoc["State"] == "disassociated"
active = ec2.describe_iam_instance_profile_associations(
Filters=[
{"Name": "association-id", "Values": [assoc["AssociationId"]]},
{"Name": "state", "Values": ["associated"]},
]
)["IamInstanceProfileAssociations"]
assert active == []
described = ec2.describe_iam_instance_profile_associations(
AssociationIds=[assoc["AssociationId"]]
)["IamInstanceProfileAssociations"]
assert len(described) == 1
assert described[0]["State"] == "disassociated"
inst = ec2.describe_instances(InstanceIds=[iid])["Reservations"][0]["Instances"][0]
assert "IamInstanceProfile" not in inst or not inst["IamInstanceProfile"]
finally:
try:
ec2.terminate_instances(InstanceIds=[iid])
except ClientError:
pass
_delete_ec2_iam_instance_profile(iam, role_a, profile_a_name)
_delete_ec2_iam_instance_profile(iam, role_b, profile_b_name)
def test_ec2_run_instances_default_private_ip_is_well_formed(ec2):
"""When the caller does not pass --private-ip-address, the auto-generated
address must still be a valid IPv4. Regression for the 10.0193.216 bug
in #594 (missing dot separator in _random_ip prefix)."""
resp = ec2.run_instances(ImageId="ami-1", MinCount=1, MaxCount=1)
inst = resp["Instances"][0]
try:
octets = inst["PrivateIpAddress"].split(".")
assert len(octets) == 4, f"malformed IP: {inst['PrivateIpAddress']}"
assert all(0 <= int(o) <= 255 for o in octets)
finally:
ec2.terminate_instances(InstanceIds=[inst["InstanceId"]])
def test_ec2_run_instances_source_dest_check_defaults_true(ec2):
resp = ec2.run_instances(ImageId="ami-12345678", MinCount=1, MaxCount=1)
inst = resp["Instances"][0]
iid = inst["InstanceId"]
try:
assert inst["SourceDestCheck"] is True
described = ec2.describe_instances(InstanceIds=[iid])["Reservations"][0]["Instances"][0]
assert described["SourceDestCheck"] is True
finally:
ec2.terminate_instances(InstanceIds=[iid])
def test_ec2_run_instances_emits_default_root_block_device_mapping(ec2):
"""RunInstances without an explicit BDM must auto-attach a root EBS volume,
matching real AWS. Cloud Custodian / AWS Config use BlockDeviceMappings to
classify EBS-backed vs ephemeral instances; a missing BDM breaks them."""
resp = ec2.run_instances(
ImageId="ami-12345678", MinCount=1, MaxCount=1, InstanceType="t2.micro"
)
iid = resp["Instances"][0]["InstanceId"]
bdms = resp["Instances"][0].get("BlockDeviceMappings")
assert bdms, "RunInstances response must include BlockDeviceMappings"
assert len(bdms) == 1
root = bdms[0]
assert root["DeviceName"] == "/dev/xvda"
ebs = root["Ebs"]
assert ebs["VolumeId"].startswith("vol-")
assert ebs["Status"] == "attached"
assert ebs["DeleteOnTermination"] is True
assert "AttachTime" in ebs
desc = ec2.describe_instances(InstanceIds=[iid])
inst = desc["Reservations"][0]["Instances"][0]
desc_bdms = inst.get("BlockDeviceMappings", [])
assert len(desc_bdms) == 1
assert desc_bdms[0]["DeviceName"] == "/dev/xvda"
assert desc_bdms[0]["Ebs"]["VolumeId"] == ebs["VolumeId"]
assert desc_bdms[0]["Ebs"]["Status"] == "attached"
vols = ec2.describe_volumes(VolumeIds=[ebs["VolumeId"]])["Volumes"]
assert len(vols) == 1
atts = vols[0]["Attachments"]
assert atts and atts[0]["InstanceId"] == iid
assert atts[0]["Device"] == "/dev/xvda"
def test_ec2_describe_instance_status(ec2):
resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1, InstanceType="t2.micro")
iid = resp["Instances"][0]["InstanceId"]
# Running instance should appear by default
status = ec2.describe_instance_status(InstanceIds=[iid])
assert len(status["InstanceStatuses"]) == 1
s = status["InstanceStatuses"][0]
assert s["InstanceId"] == iid
assert s["InstanceState"]["Name"] == "running"
assert s["SystemStatus"]["Status"] == "ok"
assert s["InstanceStatus"]["Status"] == "ok"
# Stopped instance should NOT appear without IncludeAllInstances
ec2.stop_instances(InstanceIds=[iid])
status2 = ec2.describe_instance_status(InstanceIds=[iid])
assert len(status2["InstanceStatuses"]) == 0
# With IncludeAllInstances=True it should appear
status3 = ec2.describe_instance_status(InstanceIds=[iid], IncludeAllInstances=True)
assert len(status3["InstanceStatuses"]) == 1
assert status3["InstanceStatuses"][0]["InstanceState"]["Name"] == "stopped"
ec2.terminate_instances(InstanceIds=[iid])
def test_ec2_stop_start_instances(ec2):
resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1)
iid = resp["Instances"][0]["InstanceId"]
stop = ec2.stop_instances(InstanceIds=[iid])
assert stop["StoppingInstances"][0]["CurrentState"]["Name"] == "stopped"
start = ec2.start_instances(InstanceIds=[iid])
assert start["StartingInstances"][0]["CurrentState"]["Name"] == "running"
ec2.terminate_instances(InstanceIds=[iid])
def test_ec2_run_multiple_instances(ec2):
resp = ec2.run_instances(ImageId="ami-00000000", MinCount=3, MaxCount=3)
assert len(resp["Instances"]) == 3
ids = [i["InstanceId"] for i in resp["Instances"]]
assert len(set(ids)) == 3
ec2.terminate_instances(InstanceIds=ids)
def test_ec2_describe_images(ec2):
resp = ec2.describe_images()
assert len(resp["Images"]) >= 3
assert all("ImageId" in img for img in resp["Images"])
def test_ec2_describe_images_amazon_owner_matches_aws_shape(ec2):
"""Owners=["amazon"] selects the Amazon-published images with their real
publishing accounts and ImageOwnerAlias, as on AWS — a Terraform aws_ami
data source with owners = ["amazon"] must find them."""
amazon = ec2.describe_images(Owners=["amazon"])["Images"]
names = {img["Name"] for img in amazon}
assert any(n.startswith("amzn2-ami-hvm") for n in names)
assert any(n.startswith("Windows_Server") for n in names)
assert not any("ubuntu" in n for n in names)
by_name = {img["Name"]: img for img in amazon}
al2 = next(img for n, img in by_name.items() if n.startswith("amzn2-ami-hvm"))
assert al2["OwnerId"] == "137112412989"
assert al2["ImageOwnerAlias"] == "amazon"
# Canonical's Ubuntu carries its real account and no amazon alias.
ubuntu = ec2.describe_images(Owners=["099720109477"])["Images"]
assert any("ubuntu" in img["Name"] for img in ubuntu)
assert all("ImageOwnerAlias" not in img or img["ImageOwnerAlias"] != "amazon"
for img in ubuntu)
# owner-alias filter, same selection.
via_filter = ec2.describe_images(
Filters=[{"Name": "owner-alias", "Values": ["amazon"]}])["Images"]
assert {img["ImageId"] for img in via_filter} == {img["ImageId"] for img in amazon}
# The seeded public images are not the caller's: self selects only
# registered/created images, empty when there are none — as on AWS.
mine = ec2.describe_images(Owners=["self"])["Images"]
assert not any(img["Name"].startswith(("amzn2-ami-hvm", "Windows_Server"))
or "ubuntu" in img["Name"] for img in mine)
def test_ec2_describe_images_has_root_device_and_block_mappings(ec2):
# Terraform's AWS provider resolves these before aws_instance creation;
# absence produced "finding Root Device Name for AMI" and blocked apply.
resp = ec2.describe_images(ImageIds=["ami-0abcdef1234567890"])
img = resp["Images"][0]
assert img["RootDeviceType"] == "ebs"
assert img["RootDeviceName"] == "/dev/xvda"
bdms = img["BlockDeviceMappings"]
assert bdms and bdms[0]["DeviceName"] == "/dev/xvda"
assert bdms[0]["Ebs"]["VolumeSize"] == 8
assert bdms[0]["Ebs"]["VolumeType"] == "gp2"
# Windows AMI uses /dev/sda1 and exposes Platform=windows.
resp = ec2.describe_images(ImageIds=["ami-0fedcba9876543210"])
win = resp["Images"][0]
assert win["RootDeviceName"] == "/dev/sda1"
assert win.get("Platform") == "windows"
assert win["BlockDeviceMappings"][0]["DeviceName"] == "/dev/sda1"
def test_ec2_security_group_crud(ec2):
created = ec2.create_security_group(GroupName="qa-ec2-sg", Description="test sg")
sg_id = created["GroupId"]
assert sg_id.startswith("sg-")
assert created["SecurityGroupArn"] == f"arn:aws:ec2:us-east-1:000000000000:security-group/{sg_id}"
desc = ec2.describe_security_groups(GroupIds=[sg_id])
assert desc["SecurityGroups"][0]["GroupName"] == "qa-ec2-sg"
assert desc["SecurityGroups"][0]["Description"] == "test sg"
deleted = ec2.delete_security_group(GroupId=sg_id)
assert deleted["Return"] is True
assert deleted["GroupId"] == sg_id
desc2 = ec2.describe_security_groups()
assert not any(sg["GroupId"] == sg_id for sg in desc2["SecurityGroups"])
def test_ec2_security_group_duplicate(ec2):
ec2.create_security_group(GroupName="qa-ec2-sg-dup", Description="d")
with pytest.raises(ClientError) as exc:
ec2.create_security_group(GroupName="qa-ec2-sg-dup", Description="d")
assert exc.value.response["Error"]["Code"] == "InvalidGroup.Duplicate"
def test_ec2_describe_security_groups_malformed_id(ec2):
with pytest.raises(ClientError) as exc:
ec2.describe_security_groups(GroupIds=["sg-0123456789abcdef0"])
error = exc.value.response["Error"]
assert error["Code"] == "InvalidGroupId.Malformed"
assert error["Message"] == 'Invalid id: "sg-0123456789abcdef0"'
def test_ec2_sg_authorize_revoke_ingress(ec2):
sg_id = ec2.create_security_group(GroupName="qa-ec2-sg-rules", Description="rules test")["GroupId"]
ec2.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{
"IpProtocol": "tcp",
"FromPort": 80,
"ToPort": 80,
"IpRanges": [{"CidrIp": "0.0.0.0/0"}],
}
],
)
desc = ec2.describe_security_groups(GroupIds=[sg_id])
perms = desc["SecurityGroups"][0]["IpPermissions"]
assert any(p["FromPort"] == 80 for p in perms)
ec2.revoke_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{
"IpProtocol": "tcp",
"FromPort": 80,
"ToPort": 80,
"IpRanges": [{"CidrIp": "0.0.0.0/0"}],
}
],
)
desc2 = ec2.describe_security_groups(GroupIds=[sg_id])
assert not any(p.get("FromPort") == 80 for p in desc2["SecurityGroups"][0]["IpPermissions"])
ec2.delete_security_group(GroupId=sg_id)
def test_ec2_describe_security_groups_reports_every_range_family(ec2):
"""DescribeSecurityGroups reports each family the permission carries.
IpPermission has ipRanges, ipv6Ranges and prefixListIds, and each range
carries its description; the read rendered the last two as empty
elements, so a configured IPv6 or prefix-list rule was invisible and
Terraform planned the same egress update on every run.
Reported by @edersonbrilhante."""
import uuid as _uuid
suffix = _uuid.uuid4().hex[:8]
sg_id = ec2.create_security_group(
GroupName=f"qa-ec2-sg-families-{suffix}", Description="families")["GroupId"]
try:
# The shape Terraform's egress block sends for a dual-stack allow-all.
ec2.revoke_security_group_egress(GroupId=sg_id, IpPermissions=[
{"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}]}])
ec2.authorize_security_group_egress(GroupId=sg_id, IpPermissions=[{
"IpProtocol": "-1",
"IpRanges": [{"CidrIp": "0.0.0.0/0", "Description": "all v4"}],
"Ipv6Ranges": [{"CidrIpv6": "::/0", "Description": "all v6"}],
}])
ec2.authorize_security_group_ingress(GroupId=sg_id, IpPermissions=[{
"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,
"Ipv6Ranges": [{"CidrIpv6": "2001:db8::/32"}],
}])
described = ec2.describe_security_groups(GroupIds=[sg_id])["SecurityGroups"][0]
egress = described["IpPermissionsEgress"]
assert len(egress) == 1, egress
assert egress[0]["IpRanges"] == [{"CidrIp": "0.0.0.0/0", "Description": "all v4"}]
assert egress[0]["Ipv6Ranges"] == [{"CidrIpv6": "::/0", "Description": "all v6"}]
ingress = described["IpPermissions"]
assert len(ingress) == 1, ingress
assert ingress[0]["Ipv6Ranges"] == [{"CidrIpv6": "2001:db8::/32"}]
assert ingress[0]["IpRanges"] == []
finally:
ec2.delete_security_group(GroupId=sg_id)
def test_ec2_revoke_security_group_egress_returns_revoked_rules(ec2):
sg_id = ec2.create_security_group(GroupName="qa-ec2-sg-revoke-egress", Description="egress")["GroupId"]
resp = ec2.revoke_security_group_egress(
GroupId=sg_id,
IpPermissions=[
{
"IpProtocol": "-1",
"IpRanges": [{"CidrIp": "0.0.0.0/0"}],
}
],
)
assert resp["Return"] is True
revoked = resp["RevokedSecurityGroupRules"]
assert len(revoked) == 1
assert revoked[0]["SecurityGroupRuleId"].startswith("sgr-")
assert revoked[0]["GroupId"] == sg_id
assert revoked[0]["IsEgress"] is True
assert revoked[0]["IpProtocol"] == "-1"
assert revoked[0]["CidrIpv4"] == "0.0.0.0/0"
ec2.delete_security_group(GroupId=sg_id)
def test_ec2_revoke_sg_ingress_by_rule_id(ec2):
"""RevokeSecurityGroupIngress(SecurityGroupRuleIds=[...]) must remove exactly
the addressed rules — previously the ids were ignored and the call returned
Return=true while revoking nothing."""
suffix = _uuid_mod.uuid4().hex[:8]
sg_id = ec2.create_security_group(
GroupName=f"qa-ec2-sg-revoke-by-id-{suffix}", Description="revoke by id")["GroupId"]
ec2.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80,
"IpRanges": [{"CidrIp": "0.0.0.0/0"}]},
{"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,
"IpRanges": [{"CidrIp": "0.0.0.0/0"}]},
],
)
sgr = ec2.describe_security_group_rules(
Filters=[{"Name": "group-id", "Values": [sg_id]}])["SecurityGroupRules"]
rule_id = next(r["SecurityGroupRuleId"] for r in sgr
if not r["IsEgress"] and r["FromPort"] == 80)
resp = ec2.revoke_security_group_ingress(GroupId=sg_id, SecurityGroupRuleIds=[rule_id])
assert resp["Return"] is True
revoked = resp["RevokedSecurityGroupRules"]
assert len(revoked) == 1
assert revoked[0]["SecurityGroupRuleId"] == rule_id
assert revoked[0]["GroupId"] == sg_id
assert revoked[0]["IsEgress"] is False
assert revoked[0]["CidrIpv4"] == "0.0.0.0/0"
perms = ec2.describe_security_groups(GroupIds=[sg_id])["SecurityGroups"][0]["IpPermissions"]
assert not any(p.get("FromPort") == 80 for p in perms)
assert any(p.get("FromPort") == 443 for p in perms)
ec2.delete_security_group(GroupId=sg_id)
def test_ec2_revoke_sg_ingress_unknown_rule_id_rejects_whole_call(ec2):
"""One unknown SecurityGroupRuleId rejects the whole revoke with
InvalidSecurityGroupRuleId.NotFound — the valid ids in the same call must
not be revoked (AWS validates before mutating)."""
suffix = _uuid_mod.uuid4().hex[:8]
sg_id = ec2.create_security_group(
GroupName=f"qa-ec2-sg-revoke-bad-id-{suffix}", Description="bad rule id")["GroupId"]
ec2.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22,
"IpRanges": [{"CidrIp": "10.0.0.0/8"}]},
],
)
sgr = ec2.describe_security_group_rules(
Filters=[{"Name": "group-id", "Values": [sg_id]}])["SecurityGroupRules"]
rule_id = next(r["SecurityGroupRuleId"] for r in sgr if not r["IsEgress"])
with pytest.raises(ClientError) as exc:
ec2.revoke_security_group_ingress(
GroupId=sg_id,
SecurityGroupRuleIds=[rule_id, "sgr-00000000000000000"])
assert exc.value.response["Error"]["Code"] == "InvalidSecurityGroupRuleId.NotFound"
perms = ec2.describe_security_groups(GroupIds=[sg_id])["SecurityGroups"][0]["IpPermissions"]
assert any(p.get("FromPort") == 22 for p in perms)
ec2.delete_security_group(GroupId=sg_id)
def test_ec2_revoke_sg_rules_by_id_derives_missing_stored_ids():
"""A rule dict carrying no stored SecurityGroupRuleId is matched by the
content-derived id instead, and direction is part of that identity: an id
derived for egress never matches an ingress rule. Exercised over the
handlers' in-memory shape so both outcomes are asserted on the group state;
the seeded default egress rule takes the same derive path over the wire
(test_ec2_revoke_sg_default_egress_rule_by_id)."""
from ministack.services.ec2 import _revoke_sg_rules_by_id, _sg_rule_id
sg_id = "sg-0unit000000000000"
rule_80 = {"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80,
"IpRanges": [{"CidrIp": "0.0.0.0/0"}]}
rule_443 = {"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,
"IpRanges": [{"CidrIp": "0.0.0.0/0"}]}
# Pre-fix persisted state: no stored SecurityGroupRuleId on either rule.
assert "SecurityGroupRuleId" not in rule_80
sg = {"IpPermissions": [rule_80, rule_443], "IpPermissionsEgress": []}
derived = _sg_rule_id(sg_id, False, rule_80)
assert derived.startswith("sgr-")
revoked, err = _revoke_sg_rules_by_id(sg, sg_id, [derived], is_egress=False)
assert err is None
assert revoked == [rule_80]
assert sg["IpPermissions"] == [rule_443]
# An id derived for the egress direction must NOT match the ingress rule.
revoked, err = _revoke_sg_rules_by_id(
sg, sg_id, [_sg_rule_id(sg_id, True, rule_443)], is_egress=False)
assert revoked is None
assert err is not None
assert sg["IpPermissions"] == [rule_443]
def test_ec2_revoke_sg_default_egress_rule_by_id(ec2):
"""The allow-all egress rule CreateSecurityGroup seeds is stored without a
SecurityGroupRuleId, so revoking it by the id DescribeSecurityGroupRules
reports drives the content-derived fallback over the wire. It is also the
rule an aws_vpc_security_group_egress_rule plan destroys first, and the
revoke used to be a no-op that left it in place forever."""
suffix = _uuid_mod.uuid4().hex[:8]
sg_id = ec2.create_security_group(
GroupName=f"qa-ec2-sg-default-egress-{suffix}", Description="default egress")["GroupId"]
def _rule_ids():
return [r["SecurityGroupRuleId"] for r in ec2.describe_security_group_rules(
Filters=[{"Name": "group-id", "Values": [sg_id]}])["SecurityGroupRules"]]
rules = ec2.describe_security_group_rules(
Filters=[{"Name": "group-id", "Values": [sg_id]}])["SecurityGroupRules"]
default_egress = next(r for r in rules if r["IsEgress"] and r["IpProtocol"] == "-1")
rule_id = default_egress["SecurityGroupRuleId"]
assert rule_id.startswith("sgr-")
resp = ec2.revoke_security_group_egress(GroupId=sg_id, SecurityGroupRuleIds=[rule_id])
assert resp["Return"] is True
assert [r["SecurityGroupRuleId"] for r in resp["RevokedSecurityGroupRules"]] == [rule_id]
assert rule_id not in _rule_ids()
assert ec2.describe_security_groups(
GroupIds=[sg_id])["SecurityGroups"][0]["IpPermissionsEgress"] == []
# Re-authorizing the rule brings it back under the same content-derived id,
# so a destroy-then-recreate cycle round-trips.
reauth = ec2.authorize_security_group_egress(
GroupId=sg_id,
IpPermissions=[{"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}]}],
)
assert [r["SecurityGroupRuleId"] for r in reauth["SecurityGroupRules"]] == [rule_id]
assert _rule_ids() == [rule_id]
ec2.delete_security_group(GroupId=sg_id)
def test_ec2_revoke_sg_egress_by_rule_id(ec2):
"""RevokeSecurityGroupEgress(SecurityGroupRuleIds=[...]) removes the addressed
rule and echoes it in RevokedSecurityGroupRules; an unknown id is rejected
with InvalidSecurityGroupRuleId.NotFound."""
suffix = _uuid_mod.uuid4().hex[:8]
sg_id = ec2.create_security_group(
GroupName=f"qa-ec2-sg-revoke-egress-id-{suffix}", Description="egress by id")["GroupId"]
ec2.authorize_security_group_egress(
GroupId=sg_id,
IpPermissions=[
{"IpProtocol": "tcp", "FromPort": 5432, "ToPort": 5432,
"IpRanges": [{"CidrIp": "10.2.0.0/16"}]},
],
)
sgr = ec2.describe_security_group_rules(
Filters=[{"Name": "group-id", "Values": [sg_id]}])["SecurityGroupRules"]
rule_id = next(r["SecurityGroupRuleId"] for r in sgr
if r["IsEgress"] and r.get("FromPort") == 5432)
resp = ec2.revoke_security_group_egress(GroupId=sg_id, SecurityGroupRuleIds=[rule_id])
assert resp["Return"] is True
revoked = resp["RevokedSecurityGroupRules"]
assert len(revoked) == 1
assert revoked[0]["SecurityGroupRuleId"] == rule_id
assert revoked[0]["GroupId"] == sg_id
assert revoked[0]["IsEgress"] is True
assert revoked[0]["CidrIpv4"] == "10.2.0.0/16"
egress = ec2.describe_security_groups(GroupIds=[sg_id])["SecurityGroups"][0]["IpPermissionsEgress"]
assert not any(p.get("FromPort") == 5432 for p in egress)
with pytest.raises(ClientError) as exc:
ec2.revoke_security_group_egress(
GroupId=sg_id, SecurityGroupRuleIds=["sgr-00000000000000000"])
assert exc.value.response["Error"]["Code"] == "InvalidSecurityGroupRuleId.NotFound"
ec2.delete_security_group(GroupId=sg_id)
def test_ec2_sg_authorize_ingress_idempotent_duplicate(ec2):
"""Re-authorizing the same ingress rule must succeed (Terraform may re-apply unchanged rules)."""
sg_id = ec2.create_security_group(GroupName="qa-ec2-sg-dup-auth", Description="dup auth")["GroupId"]
perm = {
"IpProtocol": "tcp",
"FromPort": 5432,
"ToPort": 5432,
"IpRanges": [{"CidrIp": "10.1.0.0/16"}],
}
ec2.authorize_security_group_ingress(GroupId=sg_id, IpPermissions=[perm])
ec2.authorize_security_group_ingress(GroupId=sg_id, IpPermissions=[perm])
desc = ec2.describe_security_groups(GroupIds=[sg_id])
ingress = desc["SecurityGroups"][0]["IpPermissions"]
matching = [p for p in ingress if p.get("FromPort") == 5432 and p.get("ToPort") == 5432]
assert len(matching) == 1
ec2.delete_security_group(GroupId=sg_id)
def test_ec2_sg_authorize_ingress_legacy_source_group(ec2):
"""Legacy top-level --source-group params (CLI/Terraform) must create a real
referenced-group rule visible in DescribeSecurityGroups AND
DescribeSecurityGroupRules, with a SecurityGroupRuleId matching the Authorize
response. Regression for issue #916."""
vpc = ec2.create_vpc(CidrBlock="10.111.0.0/16")["Vpc"]
sg_a = ec2.create_security_group(
GroupName="sg-a-916", Description="a", VpcId=vpc["VpcId"])["GroupId"]
sg_b = ec2.create_security_group(
GroupName="sg-b-916", Description="b", VpcId=vpc["VpcId"])["GroupId"]
# The AWS CLI `authorize-security-group-ingress --protocol tcp --port 8080
# --source-group <id>` (and older SDKs) serialize to legacy top-level
# parameters rather than the nested IpPermissions.N.Groups.M form. Inject
# exactly that wire shape so the test exercises the same code path.
def _inject_legacy(request, **kwargs):
request.data = (
f"Action=AuthorizeSecurityGroupIngress&Version=2016-11-15"
f"&GroupId={sg_b}&IpProtocol=tcp&FromPort=8080&ToPort=8080"
f"&SourceSecurityGroupId={sg_a}"
)
ec2.meta.events.register(
"before-sign.ec2.AuthorizeSecurityGroupIngress", _inject_legacy)
try:
resp = ec2.authorize_security_group_ingress(GroupId=sg_b)
finally:
ec2.meta.events.unregister(
"before-sign.ec2.AuthorizeSecurityGroupIngress", _inject_legacy)
assert resp.get("Return") is True
auth_rules = resp.get("SecurityGroupRules", [])
assert len(auth_rules) == 1, f"expected 1 rule from Authorize, got {auth_rules}"
auth_rule_id = auth_rules[0]["SecurityGroupRuleId"]
assert auth_rules[0].get("ReferencedGroupInfo", {}).get("GroupId") == sg_a
# DescribeSecurityGroups must show the UserIdGroupPairs reference.
perms = ec2.describe_security_groups(
GroupIds=[sg_b])["SecurityGroups"][0]["IpPermissions"]
pairs = [pair for p in perms for pair in p.get("UserIdGroupPairs", [])]
assert any(pair.get("GroupId") == sg_a for pair in pairs), \
f"UserIdGroupPairs missing reference to {sg_a}: {perms}"
# DescribeSecurityGroupRules must return the rule with ReferencedGroupInfo
# and a SecurityGroupRuleId matching the Authorize response.
sgr = ec2.describe_security_group_rules(
Filters=[{"Name": "group-id", "Values": [sg_b]}])["SecurityGroupRules"]
ref_rules = [r for r in sgr if r.get("ReferencedGroupInfo", {}).get("GroupId") == sg_a]
assert len(ref_rules) == 1, \
f"DescribeSecurityGroupRules missing referenced-group rule: {sgr}"
assert ref_rules[0]["SecurityGroupRuleId"] == auth_rule_id
assert ref_rules[0]["IsEgress"] is False
assert ref_rules[0]["IpProtocol"] == "tcp"
assert ref_rules[0]["FromPort"] == 8080
assert ref_rules[0]["ToPort"] == 8080
ec2.delete_security_group(GroupId=sg_b)
ec2.delete_security_group(GroupId=sg_a)