Debian Codegraph @

ansible_collections/amazon/aws/tests/unit/plugins/inventory/test_aws_ec2.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2017 Sloane Hertel <[email protected]>
4 #
5 # This file is part of Ansible
6 #
7 # Ansible is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Ansible is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
19
20 from unittest.mock import MagicMock
21 from unittest.mock import call
22 from unittest.mock import patch
23
24 import pytest
25
26 try:
27 import botocore
28 except ImportError:
29 # Handled by HAS_BOTO3
30 pass
31
32 from ansible.errors import AnsibleError
33
34 from ansible_collections.amazon.aws.plugins.inventory.aws_ec2 import InventoryModule
35 from ansible_collections.amazon.aws.plugins.inventory.aws_ec2 import _compile_values
36 from ansible_collections.amazon.aws.plugins.inventory.aws_ec2 import _get_boto_attr_chain
37 from ansible_collections.amazon.aws.plugins.inventory.aws_ec2 import _get_tag_hostname
38 from ansible_collections.amazon.aws.plugins.inventory.aws_ec2 import _prepare_host_vars
39 from ansible_collections.amazon.aws.plugins.inventory.aws_ec2 import _remove_trailing_dot
40
41
42 @pytest.fixture(name="inventory")
43 def fixture_inventory():
44 inventory = InventoryModule()
45 inventory._options = {
46 "aws_profile": "first_precedence",
47 "aws_access_key": "test_access_key",
48 "aws_secret_key": "test_secret_key",
49 "aws_session_token": "test_security_token",
50 "iam_role_arn": None,
51 "use_contrib_script_compatible_ec2_tag_keys": False,
52 "hostvars_prefix": "",
53 "hostvars_suffix": "",
54 "strict": True,
55 "compose": {},
56 "groups": {},
57 "keyed_groups": [],
58 "regions": ["us-east-1"],
59 "filters": [],
60 "include_filters": [],
61 "exclude_filters": [],
62 "hostnames": [],
63 "strict_permissions": False,
64 "allow_duplicated_hosts": False,
65 "cache": False,
66 "use_contrib_script_compatible_sanitization": False,
67 "route53_enabled": False,
68 }
69 inventory.inventory = MagicMock()
70 inventory.get_option = MagicMock()
71 inventory.get_option.side_effect = inventory._options.get
72 return inventory
73
74
75 @pytest.mark.parametrize(
76 "obj,expected",
77 [
78 (None, None),
79 ({}, None),
80 ({"GroupId": "test01"}, "test01"),
81 ({"GroupId": ["test01"]}, "test01"),
82 ({"GroupId": "test01"}, "test01"),
83 ({"GroupId": ["test01", "test02"]}, ["test01", "test02"]),
84 ([{"GroupId": ["test01", "test02"]}], ["test01", "test02"]),
85 ([{"GroupId": ["test01"]}], "test01"),
86 (
87 [{"GroupId": ["test01", "test02"]}, {"GroupId": ["test03", "test04"]}],
88 [["test01", "test02"], ["test03", "test04"]],
89 ),
90 (
91 ({"GroupId": ["test01", "test02"]}, {"GroupId": ["test03", "test04"]}),
92 [["test01", "test02"], ["test03", "test04"]],
93 ),
94 (({"GroupId": ["test01", "test02"]}, {}), ["test01", "test02"]),
95 ],
96 )
97 def test_compile_values(obj, expected):
98 assert _compile_values(obj, "GroupId") == expected
99
100
101 @pytest.mark.parametrize(
102 "filter_name,expected",
103 [
104 ("ansible.aws.unexpected.file", "ansible.aws.unexpected.file"),
105 ("instance.group-id", "sg-0123456789"),
106 ("instance.group-name", "default"),
107 ("owner-id", "id-012345678L"),
108 ],
109 )
110 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._compile_values")
111 def test_get_boto_attr_chain(m_compile_values, filter_name, expected):
112 m_compile_values.side_effect = lambda obj, attr: obj.get(attr)
113
114 instance = {"SecurityGroups": {"GroupName": "default", "GroupId": "sg-0123456789"}, "OwnerId": "id-012345678L"}
115
116 assert _get_boto_attr_chain(filter_name, instance) == expected
117
118
119 @pytest.mark.parametrize(
120 "hostnames,expected",
121 [
122 ([], "test-instance.ansible.com"),
123 (["private-dns-name"], "test-instance.localhost"),
124 (["tag:os_version"], "RHEL"),
125 (["tag:os_version", "dns-name"], "RHEL"),
126 ([{"name": "Name", "prefix": "Phase"}], "dev_test-instance-01"),
127 ([{"name": "Name", "prefix": "Phase", "separator": "-"}], "dev-test-instance-01"),
128 ([{"name": "Name", "prefix": "OSVersion", "separator": "-"}], "test-instance-01"),
129 ([{"name": "Name", "separator": "-"}], "test-instance-01"),
130 ([{"name": "Name", "prefix": "Phase"}, "private-dns-name"], "dev_test-instance-01"),
131 ([{"name": "Name", "prefix": "Phase"}, "tag:os_version"], "dev_test-instance-01"),
132 (["private-dns-name", "dns-name"], "test-instance.localhost"),
133 (["private-dns-name", {"name": "Name", "separator": "-"}], "test-instance.localhost"),
134 (["private-dns-name", "tag:os_version"], "test-instance.localhost"),
135 (["OSRelease"], None),
136 ],
137 )
138 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._get_tag_hostname")
139 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._get_boto_attr_chain")
140 def test_inventory_get_preferred_hostname(m_get_boto_attr_chain, m_get_tag_hostname, inventory, hostnames, expected):
141 instance = {
142 "Name": "test-instance-01",
143 "Phase": "dev",
144 "tag:os_version": ["RHEL", "CoreOS"],
145 "another_key": "another_value",
146 "dns-name": "test-instance.ansible.com",
147 "private-dns-name": "test-instance.localhost",
148 }
149
150 inventory._sanitize_hostname = MagicMock()
151 inventory._sanitize_hostname.side_effect = lambda x: x
152
153 m_get_boto_attr_chain.side_effect = lambda pref, instance: instance.get(pref)
154 m_get_tag_hostname.side_effect = lambda pref, instance: instance.get(pref)
155
156 assert expected == inventory._get_preferred_hostname(instance, hostnames)
157
158
159 def test_inventory_get_preferred_hostname_failure(inventory):
160 instance = {}
161 hostnames = [{"value": "saome_value"}]
162
163 inventory._sanitize_hostname = MagicMock()
164 inventory._sanitize_hostname.side_effect = lambda x: x
165
166 with pytest.raises(AnsibleError) as err:
167 inventory._get_preferred_hostname(instance, hostnames)
168 assert "A 'name' key must be defined in a hostnames dictionary." in str(err.value)
169
170
171 @pytest.mark.parametrize("base_verify_file_return", [True, False])
172 @pytest.mark.parametrize(
173 "filename,result",
174 [
175 ("inventory_aws_ec2.yml", True),
176 ("inventory_aws_ec2.yaml", True),
177 ("inventory_aws_EC2.yaml", False),
178 ("inventory_Aws_ec2.yaml", False),
179 ("aws_ec2_inventory.yml", False),
180 ("aws_ec2.yml_inventory", False),
181 ("aws_ec2.yml", True),
182 ("aws_ec2.yaml", True),
183 ],
184 )
185 @patch("ansible.plugins.inventory.BaseInventoryPlugin.verify_file")
186 def test_inventory_verify_file(m_base_verify_file, inventory, base_verify_file_return, filename, result):
187 m_base_verify_file.return_value = base_verify_file_return
188 if not base_verify_file_return:
189 assert not inventory.verify_file(filename)
190 else:
191 assert result == inventory.verify_file(filename)
192
193
194 @pytest.mark.parametrize(
195 "preference,instance,expected",
196 [
197 ("tag:os_provider", {"Tags": []}, []),
198 ("tag:os_provider", {}, []),
199 ("tag:os_provider", {"Tags": [{"Key": "os_provider", "Value": "RedHat"}]}, "RedHat"),
200 ("tag:OS_Provider", {"Tags": [{"Key": "os_provider", "Value": "RedHat"}]}, []),
201 ("tag:tag:os_provider", {"Tags": [{"Key": "os_provider", "Value": "RedHat"}]}, []),
202 ("tag:os_provider=RedHat", {"Tags": [{"Key": "os_provider", "Value": "RedHat"}]}, "os_provider_RedHat"),
203 ("tag:os_provider=CoreOS", {"Tags": [{"Key": "os_provider", "Value": "RedHat"}]}, []),
204 (
205 "tag:os_provider=RedHat,os_release=7",
206 {"Tags": [{"Key": "os_provider", "Value": "RedHat"}, {"Key": "os_release", "Value": "8"}]},
207 ["os_provider_RedHat"],
208 ),
209 (
210 "tag:os_provider=RedHat,os_release=7",
211 {"Tags": [{"Key": "os_provider", "Value": "RedHat"}, {"Key": "os_release", "Value": "7"}]},
212 ["os_provider_RedHat", "os_release_7"],
213 ),
214 (
215 "tag:os_provider,os_release",
216 {"Tags": [{"Key": "os_provider", "Value": "RedHat"}, {"Key": "os_release", "Value": "7"}]},
217 ["RedHat", "7"],
218 ),
219 (
220 "tag:os_provider=RedHat,os_release",
221 {"Tags": [{"Key": "os_provider", "Value": "RedHat"}, {"Key": "os_release", "Value": "7"}]},
222 ["os_provider_RedHat", "7"],
223 ),
224 ],
225 )
226 def test_get_tag_hostname(preference, instance, expected):
227 assert expected == _get_tag_hostname(preference, instance)
228
229
230 @pytest.mark.parametrize(
231 "_options, expected",
232 [
233 ({"filters": {}, "include_filters": []}, [{}]),
234 ({"filters": {}, "include_filters": [{"foo": "bar"}]}, [{"foo": "bar"}]),
235 (
236 {
237 "filters": {"from_filter": 1},
238 "include_filters": [{"from_include_filter": "bar"}],
239 },
240 [{"from_filter": 1}, {"from_include_filter": "bar"}],
241 ),
242 ],
243 )
244 def test_inventory_build_include_filters(inventory, _options, expected):
245 inventory.get_option = MagicMock()
246 inventory.get_option.side_effect = _options.get
247 assert inventory.build_include_filters() == expected
248
249
250 @pytest.mark.parametrize("hostname,expected", [(1, "1"), ("a:b", "a_b"), ("a:/b", "a__b"), ("example", "example")])
251 def test_sanitize_hostname(inventory, hostname, expected):
252 assert inventory._sanitize_hostname(hostname) == expected
253
254
255 def test_sanitize_hostname_legacy(inventory):
256 inventory._sanitize_group_name = inventory._legacy_script_compatible_group_sanitization
257 assert inventory._sanitize_hostname("a:/b") == "a__b"
258
259
260 @pytest.mark.parametrize(
261 "hostvars_prefix,hostvars_suffix,use_contrib_script_compatible_ec2_tag_keys,expectation",
262 [
263 (
264 None,
265 None,
266 False,
267 {
268 "my_var": 1,
269 "placement": {"availability_zone": "us-east-1a", "region": "us-east-1"},
270 "ec2_tags": {"Name": "my-name"},
271 "tags": {"Name": "my-name"},
272 },
273 ),
274 (
275 "pre",
276 "post",
277 False,
278 {
279 "premy_varpost": 1,
280 "preplacementpost": {
281 "availability_zone": "us-east-1a",
282 "region": "us-east-1",
283 },
284 "preec2_tagspost": {"Name": "my-name"},
285 "pretagspost": {"Name": "my-name"},
286 },
287 ),
288 (
289 None,
290 None,
291 True,
292 {
293 "my_var": 1,
294 "ec2_tag_Name": "my-name",
295 "placement": {"availability_zone": "us-east-1a", "region": "us-east-1"},
296 "ec2_tags": {"Name": "my-name"},
297 "tags": {"Name": "my-name"},
298 },
299 ),
300 ],
301 )
302 def test_prepare_host_vars(
303 hostvars_prefix,
304 hostvars_suffix,
305 use_contrib_script_compatible_ec2_tag_keys,
306 expectation,
307 ):
308 original_host_vars = {
309 "my_var": 1,
310 "placement": {"availability_zone": "us-east-1a"},
311 "Tags": [{"Key": "Name", "Value": "my-name"}],
312 }
313 assert (
314 _prepare_host_vars(
315 original_host_vars,
316 hostvars_prefix,
317 hostvars_suffix,
318 use_contrib_script_compatible_ec2_tag_keys,
319 )
320 == expectation
321 )
322
323
324 def test_iter_entry(inventory):
325 hosts = [
326 {
327 "Placement": {
328 "AvailabilityZone": "us-east-1a",
329 },
330 "PublicDnsName": "first-host://",
331 },
332 {
333 "Placement": {
334 "AvailabilityZone": "us-east-1a",
335 },
336 "PublicDnsName": "second-host",
337 "Tags": [{"Key": "Name", "Value": "my-name"}],
338 },
339 ]
340
341 entries = list(inventory.iter_entry(hosts, hostnames=[]))
342 assert len(entries) == 2
343 assert entries[0][0] == "first_host___"
344 assert entries[1][0] == "second-host"
345 assert entries[1][1]["ec2_tags"]["Name"] == "my-name"
346 assert entries[1][1]["tags"]["Name"] == "my-name"
347
348 entries = list(
349 inventory.iter_entry(
350 hosts,
351 hostnames=[],
352 hostvars_prefix="a_",
353 hostvars_suffix="_b",
354 use_contrib_script_compatible_ec2_tag_keys=True,
355 )
356 )
357 assert len(entries) == 2
358 assert entries[0][0] == "first_host___"
359 assert entries[1][1]["a_ec2_tags_b"]["Name"] == "my-name"
360 assert entries[1][1]["a_tags_b"]["Name"] == "my-name"
361
362
363 @pytest.mark.parametrize(
364 "include_filters,exclude_filters,instances_by_region,instances",
365 [
366 ([], [], [], []),
367 (
368 [4, 1, 2],
369 [],
370 [
371 [{"InstanceId": 4, "name": "instance-4"}],
372 [{"InstanceId": 1, "name": "instance-1"}],
373 [{"InstanceId": 2, "name": "instance-2"}],
374 ],
375 [
376 {"InstanceId": 1, "name": "instance-1"},
377 {"InstanceId": 2, "name": "instance-2"},
378 {"InstanceId": 4, "name": "instance-4"},
379 ],
380 ),
381 (
382 [],
383 [4, 1, 2],
384 [
385 [{"InstanceId": 4, "name": "instance-4"}],
386 [{"InstanceId": 1, "name": "instance-1"}],
387 [{"InstanceId": 2, "name": "instance-2"}],
388 ],
389 [],
390 ),
391 (
392 [1, 2],
393 [4],
394 [
395 [{"InstanceId": 4, "name": "instance-4"}],
396 [{"InstanceId": 1, "name": "instance-1"}],
397 [{"InstanceId": 2, "name": "instance-2"}],
398 ],
399 [{"InstanceId": 1, "name": "instance-1"}, {"InstanceId": 2, "name": "instance-2"}],
400 ),
401 (
402 [1, 2],
403 [1],
404 [
405 [{"InstanceId": 1, "name": "instance-1"}],
406 [{"InstanceId": 1, "name": "instance-1"}],
407 [{"InstanceId": 2, "name": "instance-2"}],
408 ],
409 [{"InstanceId": 2, "name": "instance-2"}],
410 ),
411 ],
412 )
413 def test_inventory_query(inventory, include_filters, exclude_filters, instances_by_region, instances):
414 inventory._get_instances_by_region = MagicMock()
415 inventory._get_instances_by_region.side_effect = instances_by_region
416
417 regions = ["us-east-1", "us-east-2"]
418 strict = False
419
420 params = {
421 "regions": regions,
422 "strict_permissions": strict,
423 "include_filters": [],
424 "exclude_filters": [],
425 "use_ssm_inventory": False,
426 }
427
428 for u in include_filters:
429 params["include_filters"].append({"Name": f"in_filters_{int(u)}", "Values": [u]})
430
431 for u in exclude_filters:
432 params["exclude_filters"].append({"Name": f"ex_filters_{int(u)}", "Values": [u]})
433
434 assert inventory._query(**params) == {"aws_ec2": instances}
435 if not instances_by_region:
436 inventory._get_instances_by_region.assert_not_called()
437
438
439 @pytest.mark.parametrize(
440 "filters",
441 [
442 [],
443 [{"Name": "provider", "Values": "sample"}, {"Name": "instance-state-name", "Values": ["active"]}],
444 [
445 {"Name": "tags", "Values": "one_tag"},
446 ],
447 ],
448 )
449 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._describe_ec2_instances")
450 def test_inventory_get_instances_by_region(m_describe_ec2_instances, inventory, filters):
451 boto3_conn = [(MagicMock(), "us-east-1"), (MagicMock(), "us-east-2")]
452
453 inventory.all_clients = MagicMock()
454 inventory.all_clients.return_value = boto3_conn
455
456 m_describe_ec2_instances.side_effect = [
457 {
458 "Reservations": [
459 {
460 "OwnerId": "owner01",
461 "RequesterId": "requester01",
462 "ReservationId": "id-0123",
463 "Instances": [
464 {"name": "id-1-0", "os": "RedHat"},
465 {"name": "id-1-1", "os": "CoreOS"},
466 {"name": "id-1-2", "os": "Fedora"},
467 ],
468 },
469 {
470 "OwnerId": "owner01",
471 "ReservationId": "id-0456",
472 "Instances": [{"name": "id-2-0", "phase": "uat"}, {"name": "id-2-1", "phase": "prod"}],
473 },
474 ]
475 },
476 {
477 "Reservations": [
478 {
479 "OwnerId": "owner02",
480 "ReservationId": "id-0789",
481 "Instances": [
482 {"name": "id012345789", "tags": {"phase": "units"}},
483 ],
484 }
485 ],
486 "Metadata": {"Status": "active"},
487 },
488 ]
489
490 expected = [
491 {
492 "name": "id-1-0",
493 "os": "RedHat",
494 "OwnerId": "owner01",
495 "RequesterId": "requester01",
496 "ReservationId": "id-0123",
497 },
498 {
499 "name": "id-1-1",
500 "os": "CoreOS",
501 "OwnerId": "owner01",
502 "RequesterId": "requester01",
503 "ReservationId": "id-0123",
504 },
505 {
506 "name": "id-1-2",
507 "os": "Fedora",
508 "OwnerId": "owner01",
509 "RequesterId": "requester01",
510 "ReservationId": "id-0123",
511 },
512 {"name": "id-2-0", "phase": "uat", "OwnerId": "owner01", "ReservationId": "id-0456", "RequesterId": ""},
513 {"name": "id-2-1", "phase": "prod", "OwnerId": "owner01", "ReservationId": "id-0456", "RequesterId": ""},
514 {
515 "name": "id012345789",
516 "tags": {"phase": "units"},
517 "OwnerId": "owner02",
518 "ReservationId": "id-0789",
519 "RequesterId": "",
520 },
521 ]
522
523 default_filter = {"Name": "instance-state-name", "Values": ["running", "pending", "stopping", "stopped"]}
524 regions = ["us-east-2", "us-east-4"]
525
526 assert inventory._get_instances_by_region(regions, filters, False) == expected
527 inventory.all_clients.assert_called_with("ec2")
528
529 if any((f["Name"] == "instance-state-name" for f in filters)):
530 filters.append(default_filter)
531
532 m_describe_ec2_instances.assert_has_calls([call(conn, filters) for conn, region in boto3_conn], any_order=True)
533
534
535 @pytest.mark.parametrize("strict", [True, False])
536 @pytest.mark.parametrize(
537 "error",
538 [
539 botocore.exceptions.ClientError(
540 {"Error": {"Code": 1, "Message": "Something went wrong"}, "ResponseMetadata": {"HTTPStatusCode": 404}},
541 "some_botocore_client_error",
542 ),
543 botocore.exceptions.ClientError(
544 {
545 "Error": {"Code": "UnauthorizedOperation", "Message": "Something went wrong"},
546 "ResponseMetadata": {"HTTPStatusCode": 403},
547 },
548 "some_botocore_client_error",
549 ),
550 botocore.exceptions.PaginationError(message="some pagination error"),
551 ],
552 )
553 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._describe_ec2_instances")
554 def test_inventory_get_instances_by_region_failures(m_describe_ec2_instances, inventory, strict, error):
555 inventory.all_clients = MagicMock()
556 inventory.all_clients.return_value = [(MagicMock(), "us-west-2")]
557 inventory.fail_aws = MagicMock()
558 inventory.fail_aws.side_effect = SystemExit(1)
559
560 m_describe_ec2_instances.side_effect = error
561 regions = ["us-east-2", "us-east-4"]
562
563 if (
564 isinstance(error, botocore.exceptions.ClientError)
565 and error.response["ResponseMetadata"]["HTTPStatusCode"] == 403
566 and not strict
567 ):
568 assert inventory._get_instances_by_region(regions, [], strict) == []
569 else:
570 with pytest.raises(SystemExit):
571 inventory._get_instances_by_region(regions, [], strict)
572
573
574 @pytest.mark.parametrize(
575 "hostnames,expected",
576 [
577 ([], ["test-instance.ansible.com", "test-instance.localhost"]),
578 (["private-dns-name"], ["test-instance.localhost"]),
579 (["tag:os_version"], ["RHEL", "CoreOS"]),
580 (["tag:os_version", "dns-name"], ["RHEL", "CoreOS", "test-instance.ansible.com"]),
581 ([{"name": "Name", "prefix": "Phase"}], ["dev_test-instance-01"]),
582 ([{"name": "Name", "prefix": "Phase", "separator": "-"}], ["dev-test-instance-01"]),
583 ([{"name": "Name", "prefix": "OSVersion", "separator": "-"}], ["test-instance-01"]),
584 ([{"name": "Name", "separator": "-"}], ["test-instance-01"]),
585 (
586 [{"name": "Name", "prefix": "Phase"}, "private-dns-name"],
587 ["dev_test-instance-01", "test-instance.localhost"],
588 ),
589 ([{"name": "Name", "prefix": "Phase"}, "tag:os_version"], ["dev_test-instance-01", "RHEL", "CoreOS"]),
590 (["private-dns-name", {"name": "Name", "separator": "-"}], ["test-instance.localhost", "test-instance-01"]),
591 (["OSRelease"], []),
592 ],
593 )
594 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._get_tag_hostname")
595 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._get_boto_attr_chain")
596 def test_inventory_get_all_hostnames(m_get_boto_attr_chain, m_get_tag_hostname, inventory, hostnames, expected):
597 instance = {
598 "Name": "test-instance-01",
599 "Phase": "dev",
600 "tag:os_version": ["RHEL", "CoreOS"],
601 "another_key": "another_value",
602 "dns-name": "test-instance.ansible.com",
603 "private-dns-name": "test-instance.localhost",
604 }
605
606 inventory._sanitize_hostname = MagicMock()
607 inventory._sanitize_hostname.side_effect = lambda x: x
608
609 m_get_boto_attr_chain.side_effect = lambda pref, instance: instance.get(pref)
610 m_get_tag_hostname.side_effect = lambda pref, instance: instance.get(pref)
611
612 assert expected == inventory._get_all_hostnames(instance, hostnames)
613
614
615 def test_inventory_get_all_hostnames_failure(inventory):
616 instance = {}
617 hostnames = [{"value": "some_value"}]
618
619 with pytest.raises(AnsibleError) as err:
620 inventory._get_all_hostnames(instance, hostnames)
621 assert "A 'name' key must be defined in a hostnames dictionary." in str(err.value)
622
623
624 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._get_ssm_information")
625 def test_inventory__add_ssm_information(m_get_ssm_information, inventory):
626 instances = [
627 {"InstanceId": "i-001", "Name": "first-instance"},
628 {"InstanceId": "i-002", "Name": "another-instance"},
629 ]
630
631 result = {
632 "StatusCode": 200,
633 "Entities": [
634 {"Id": "i-001", "Data": {}},
635 {
636 "Id": "i-002",
637 "Data": {
638 "AWS:InstanceInformation": {
639 "Content": [{"os_type": "Linux", "os_name": "Fedora", "os_version": 37}]
640 }
641 },
642 },
643 ],
644 }
645 m_get_ssm_information.return_value = result
646
647 connection = MagicMock()
648
649 expected = [
650 {"InstanceId": "i-001", "Name": "first-instance"},
651 {
652 "InstanceId": "i-002",
653 "Name": "another-instance",
654 "SsmInventory": {"os_type": "Linux", "os_name": "Fedora", "os_version": 37},
655 },
656 ]
657
658 inventory._add_ssm_information(connection, instances)
659 assert expected == instances
660
661 filters = [{"Key": "AWS:InstanceInformation.InstanceId", "Values": [x["InstanceId"] for x in instances]}]
662 m_get_ssm_information.assert_called_once_with(connection, filters)
663
664
665 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._get_ssm_information")
666 def test_inventory__get_multiple_ssm_inventories(m_get_ssm_information, inventory):
667 instances = [{"InstanceId": f"i-00{i}", "Name": f"instance {i}"} for i in range(41)]
668 result = {
669 "StatusCode": 200,
670 "Entities": [
671 {
672 "Id": f"i-00{i}",
673 "Data": {
674 "AWS:InstanceInformation": {
675 "Content": [{"os_type": "Linux", "os_name": "Fedora", "os_version": 37}]
676 }
677 },
678 }
679 for i in range(41)
680 ],
681 }
682 m_get_ssm_information.return_value = result
683
684 connection = MagicMock()
685
686 expected = [
687 {
688 "InstanceId": f"i-00{i}",
689 "Name": f"instance {i}",
690 "SsmInventory": {"os_type": "Linux", "os_name": "Fedora", "os_version": 37},
691 }
692 for i in range(41)
693 ]
694
695 inventory._add_ssm_information(connection, instances)
696 assert expected == instances
697
698 assert 2 == m_get_ssm_information.call_count
699
700
701 @pytest.mark.parametrize(
702 "data,expected",
703 [
704 ("an.example.com.", "an.example.com"),
705 ("an.example.com..", "an.example.com."),
706 ("an.example.com", "an.example.com"),
707 ],
708 )
709 def test__remove_trailing_dot(data, expected):
710 assert expected == _remove_trailing_dot(data)
711
712
713 @pytest.mark.parametrize(
714 "route53_excluded_zones,expected",
715 [
716 (
717 [],
718 {
719 "cloud.org": set(("ansible.test.aaa", "ansible.test.bbb")),
720 "cloud.com": set(("ansible.test.ccc", "ansible.test.aaa")),
721 "cloud.net": set(("ansible.test.ccc",)),
722 },
723 ),
724 (
725 ["ansible.test.ccc"],
726 {"cloud.org": set(("ansible.test.aaa", "ansible.test.bbb")), "cloud.com": set(("ansible.test.aaa",))},
727 ),
728 ],
729 )
730 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._list_hosted_zones")
731 @patch("ansible_collections.amazon.aws.plugins.inventory.aws_ec2._list_resource_record_sets")
732 def test___map_route53_records(
733 m__list_resource_record_sets, m__list_hosted_zones, inventory, route53_excluded_zones, expected
734 ):
735 inventory._options.update({"route53_excluded_zones": route53_excluded_zones})
736 connection = MagicMock()
737 region = MagicMock()
738 inventory.all_clients = MagicMock()
739 inventory.all_clients.return_value = [(connection, region)]
740
741 hosted_zones = [
742 {"Name": "ansible.test.aaa", "Id": "/hostedzone/aaa"},
743 {"Name": "ansible.test.bbb.", "Id": "/hostedzone/bbb"},
744 {"Name": "ansible.test.ccc.", "Id": "/hostedzone/ccc"},
745 ]
746 m__list_hosted_zones.return_value = hosted_zones
747 rr_sets = {
748 "/hostedzone/aaa": [
749 {"Name": "ansible.test.aaa", "ResourceRecords": [{"Value": "cloud.org."}, {"Value": "cloud.com."}]},
750 {"Name": "ansible.test.aaa"},
751 ],
752 "/hostedzone/bbb": [
753 {"Name": "ansible.test.bbb", "ResourceRecords": [{"Value": "cloud.org"}]},
754 ],
755 "/hostedzone/ccc": [
756 {"Name": "ansible.test.ccc", "ResourceRecords": [{"Value": "cloud.com."}]},
757 {"Name": "ansible.test.ccc", "ResourceRecords": [{"Value": "cloud.net."}]},
758 ],
759 }
760 m__list_resource_record_sets.side_effect = lambda client, hosted_zone_id: rr_sets.get(hosted_zone_id)
761
762 assert inventory._map_route53_records() == expected
763 inventory.all_clients.assert_called_once_with("route53")
764 m__list_hosted_zones.assert_called_once_with(connection)
765
766
767 @pytest.mark.parametrize(
768 "instance,hostnames",
769 [
770 ({"PublicDnsName": "", "PrivateDnsName": "", "PrivateIpAddress": "10.1.0.92"}, ["ansible.test.local"]),
771 (
772 {"PublicDnsName": "instance.public.dns.com", "PrivateDnsName": "", "PrivateIpAddress": "10.1.0.92"},
773 ["ansible.test.local", "ansible.test.public.dns"],
774 ),
775 (
776 {"PublicDnsName": "", "PrivateDnsName": "cloud.com", "PrivateIpAddress": "10.1.0.92"},
777 ["ansible.test.com", "ansible.test.local", "ansible.test.org"],
778 ),
779 (
780 {"PublicIpAddress": "172.13.1.0", "PrivateDnsName": "", "PrivateIpAddress": "10.1.0.92"},
781 ["ansible.test.local"],
782 ),
783 ],
784 )
785 def test__get_instance_route53_hostnames(inventory, instance, hostnames):
786 inventory._is_matching_route53_hostname = MagicMock()
787 inventory._is_matching_route53_hostname.side_effect = lambda x: True
788
789 inventory.route53_resource_record_mapping = {
790 "cloud.com": set(("ansible.test.com", "ansible.test.org")),
791 "10.1.0.92": set(("ansible.test.local",)),
792 "instance.public.dns.com": set(("ansible.test.public.dns",)),
793 }
794 result = inventory._get_instance_route53_hostnames(instance)
795 assert sorted(hostnames) == sorted(result)