-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathoci.py
1872 lines (1664 loc) · 76.6 KB
/
oci.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
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
name: oci
plugin_type: inventory
short_description: Oracle Cloud Infrastructure (OCI) inventory plugin
extends_documentation_fragment:
- inventory_cache
- constructed
description:
- Get inventory hosts from oci.
- Uses a <name>.oci.yaml (or <name>.oci.yml) YAML configuration file.
options:
plugin:
description: token that ensures this is a source file for the 'oci' plugin.
required: True
choices: ['oracle.oci.oci']
config_file:
description: The oci config path.
env:
- name: OCI_CONFIG_FILE
config_profile:
description: The config profile to use.
env:
- name: OCI_CONFIG_PROFILE
api_user_key_file:
description: Full path and filename of the private key (in PEM format). If the key is encrypted with
a pass-phrase, the pass_phrase option must also be provided.
Preference order is .oci.yml > OCI_USER_KEY_FILE environment variable > settings from config file
This option is required if the private key is not specified through a configuration
file (See config_file)
type: str
env:
- name: OCI_USER_KEY_FILE
api_user_key_pass_phrase:
description: Passphrase used by the key referenced in api_user_key_file, if it is encrypted.
Preference order is .oci.yml > OCI_USER_KEY_PASS_PHRASE environment variable > settings from config file
This option is required if the passphrase is not specified through a configuration
file (See config_file)
type: str
env:
- name: OCI_USER_KEY_PASS_PHRASE
instance_principal_authentication:
description:
- This parameter is DEPRECATED. Please use auth_type instead.
- Use instance principal based authentication.
If not set, the API key in your config will be used.
auth_type:
description:
- The type of authentication to use for making API requests. By default C(auth_type="api_key") based
authentication is performed and the API key (see I(api_user_key_file)) in your config file will be
used. If this 'auth_type' module option is not specified, the value of the OCI_ANSIBLE_AUTH_TYPE,
if any, is used. Use C(auth_type="instance_principal") to use instance principal based authentication
when running ansible playbooks within an OCI compute instance.
choices: ['api_key', 'instance_principal', 'instance_obo_user', 'resource_principal']
default: 'api_key'
type: str
env:
- name: OCI_ANSIBLE_AUTH_TYPE
delegation_token_file:
description:
- Path to delegation_token file. If not set then the value of the OCI_DELEGATION_TOKEN_FILE environment variable,
if any, is used. Otherwise, defaults to config_file.
- This parameter is only applicable when C(auth_type=instance_obo_user) is set.
type: str
env:
- name: OCI_DELEGATION_TOKEN_FILE
enable_parallel_processing:
description: Use multiple threads to speedup lookup. Default is set to True
regions:
description: A list of regions to search. If not specified, the region is read from config file. Use 'all'
to generate inventory from all subscribed regions.
type: list
hostnames:
description: A list of hostnames to search for.
type: list
hostname_format_preferences:
description: A list of Jinja2 expressions in order of precedence to compose inventory_hostname.
Ignores expression if result is an empty string or None value.
hostname_format_preferences and hostname_format cannot be used together.
The instance is ignored if none of the hostname_format_preferences resulted in a non-empty value
type: list
hostname_format:
description: Host naming format to use. Use 'fqdn' to list hosts using the instance's
Fully Qualified Domain Name (FQDN). These FQDNs are resolvable within the VCN using the VCN
resolver specified through the subnet's DHCP options. Please see
https://docs.us-phoenix-1.oraclecloud.com/Content/Network/Concepts/dns.htm for more details.
Use 'public_ip' to list hosts using public IP address. Use 'private_ip' to list hosts using
private IP address. Use 'display_name' to list hosts using display_name of the Instances.
'display_name' cannot be used when fetch_db_hosts is True. By default, hosts are listed using public IP address.
hostname_format_preferences and hostname_format cannot be used together
env:
- name: OCI_HOSTNAME_FORMAT
filters:
description:
- A dictionary of filter value pairs.
- Available filters are display_name, lifecycle_state, availability_domain, defined_tags, freeform_tags.
- "Note: defined_tags and freeform_tags filters are not supported for db hosts. The db hosts will not
be returned when you use either of these filters."
type: list
exclude_host_filters:
description: A list of Jinja2 conditional expressions. Each expression in the list is evaluated for each host;
when any of the expressions is evaluated to Truthy value, the host is excluded from the inventory.
exclude_host_filters take priority over the include_host_filters and filters.
type: list
include_host_filters:
description: A list of Jinja2 conditional expressions. Each expression in the list is evaluated for each host;
when any of the expressions is evaluated to Truthy value, the host is included in the inventory.
include_host_filters and filters options cannot be used together.
type: list
fetch_db_hosts:
description: When set, the db nodes are also fetched. Default value set to False.
type: bool
fetch_compute_hosts:
description: When set, the compute nodes are fetched. Default value set to True.
type: bool
primary_vnic_only:
description: The default behavior of the plugin is to process all VNIC's attached to a compute instance.
This might result in instance having multiple entries. When this parameter is set to True,
the plugin will only process the primary VNIC and thus having only a single entry for
each compute instance.
type: bool
env:
- name: OCI_PRIMARY_VNIC_ONLY
debug:
description: Parameter to enable logs while running the inventory plugin. Default value is set to False
type: boolean
compartments:
description: A dictionary of compartment identifier to obtain list of hosts. This config parameter is optional.
If compartment is not specified, the plugin fetches all compartments from the tenancy.
type: list
suboptions:
compartment_ocid:
description: OCID of the compartment. If None, root compartment is assumed to be the default value.
type: str
compartment_name:
description: Name of the compartment. If None and `compartment_ocid` is not set, all the
compartments including the root compartment are returned.
type: str
fetch_hosts_from_subcompartments:
description: Flag used to fetch hosts from subcompartments. Default value is set to True
type: boolean
parent_compartment_ocid:
description: This option is not needed when the compartment_ocid option is used, it is needed when
compartment_name is used. OCID of the parent compartment. If None, root compartment
is assumed to be parent.
type: str
exclude_compartments:
description: A dictionary of compartment identifier to filter the compartments from which hosts should be listed from.
This config parameter is optional.
Suboption is not considered when both compartment_ocid, compartment_name are None
type: list
suboptions:
compartment_ocid:
description: OCID of the compartment.
type: str
compartment_name:
description: Name of the compartment. If None and `compartment_ocid` is not set,
this option is not considered for filtering the compartments.
If both compartment_ocid and compartment_name are passed, compartment_ocid is considered
type: str
skip_subcompartments:
description: Flag used to skip the sub-compartments. Default value is set to True
type: boolean
parent_compartment_ocid:
description: This option is not needed when the compartment_ocid option is used, it is needed when
compartment_name is used. OCID of the parent compartment. If None, root compartment
is assumed to be parent.
type: str
group_name_max_length:
description: Limit group name length
type: int
tags_to_group_by:
description: Group by specific tags only. Use group#tag notation for defined tags
type: list
tags_to_not_group_by:
description: Exclude certain tags from grouping. Use group#tag notation for defined tags
type: list
"""
EXAMPLES = """
# Fetch all hosts
plugin: oci
# Optional fields:
config_file: ~/.oci/config
config_profile: DEFAULT
# Example select regions
regions:
- us-ashburn-1
- us-phoenix-1
# Enable threads to speedup lookup
enable_parallel_processing: yes
# Select compartment by ocid or name
compartments:
- compartment_ocid: ocid1.compartment.oc1..xxxxxx
fetch_hosts_from_subcompartments: false
- compartment_name: "test_compartment"
parent_compartment_ocid: ocid1.tenancy.oc1..xxxxxx
# Sets the inventory_hostname to either "display_name+'.oci.com'" or id
# "'display_name+'.oci.com'" has more preference than id
hostname_format_preferences:
- "display_name+'.oci.com'"
- "id"
# Excludes host that is not in the region 'iad' from the inventory
exclude_host_filters:
- "region not in ['iad']"
# Includes only the hosts that has display_name ending with '.oci.com' in the inventory
include_host_filters:
- "display_name is match('.*.oci.com')"
# Example group results by key
keyed_groups:
- key: availability_domain
# Example to create and modify a host variable
compose:
ansible_host: display_name+'.oracle.com'
# Example flag to turn on debug mode
debug: true
# Enable Cache
cache: yes
cache_plugin: jsonfile
cache_timeout: 7200
cache_connection: /tmp/oci-cache
cache_prefix: oci_
# DB Hosts
fetch_db_hosts: True
# Compute Hosts (bool type)
fetch_compute_hosts: True
# Process only the primary vnic of a compute instance
primary_vnic_only: True
# Select compartment by ocid or name
exclude_compartments:
- compartment_ocid: ocid1.compartment.oc1..xxxxxx
skip_subcompartments: false
- compartment_name: "test_skip_compartment"
parent_compartment_ocid: ocid1.tenancy.oc1..xxxxxx
# Limit group name length to 128
group_name_max_length: 128
# Group by specific tags only. Use group#tag notation for defined tags
tags_to_group_by:
- department
- environment#name
# Exclude certain tags from grouping. Use group#tag notation for defined tags
tags_to_not_group_by:
- department
- environment#name
"""
import os
import re
import json
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.module_utils._text import to_bytes
from ansible.module_utils.six import string_types
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
from ansible.utils.display import Display
from ansible.module_utils import six
from collections import deque, defaultdict
from multiprocessing.pool import ThreadPool
from functools import partial
from contextlib import contextmanager
from ansible_collections.oracle.oci.plugins.module_utils import (
oci_config_utils,
oci_common_utils,
oci_version,
)
try:
import oci
from oci.core.compute_client import ComputeClient
from oci.identity.identity_client import IdentityClient
from oci.core.virtual_network_client import VirtualNetworkClient
from oci.database import DatabaseClient
from oci.util import to_dict
from oci.exceptions import ServiceError
from oci.auth.signers.resource_principals_signer import (
get_resource_principals_signer,
)
HAS_OCI_PY_SDK = True
except ImportError:
HAS_OCI_PY_SDK = False
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
NAME = "oracle.oci.oci"
LIFECYCLE_ACTIVE_STATE = "ACTIVE"
LIFECYCLE_RUNNING_STATE = "RUNNING"
LIFECYCLE_ATTACHED_STATE = "ATTACHED"
def __init__(self):
super(InventoryModule, self).__init__()
self.inventory = None
self.config = {}
self.compartments = None
self._identity_client = None
self._region_subscriptions = None
self.regions = {}
self.enable_parallel_processing = True
self.compartments_info = None
self.exclude_compartments_info = None
self.exclude_compartments = dict()
self.params = {
"config_file": os.path.join(os.path.expanduser("~"), ".oci", "config"),
"profile": "DEFAULT",
"user": None,
"fingerprint": None,
"key_file": None,
"tenancy": None,
"region": None,
"pass_phrase": None,
# other options
"compartment_ocid": None,
"compartment_name": None,
"parent_compartment_ocid": None,
"fetch_hosts_from_subcompartments": True,
"debug": False,
"hostname_format": None,
"sanitize_names": True,
"replace_dash_in_names": False,
"max_thread_count": 50,
"freeform_tags": None,
"defined_tags": None,
"regions": None,
"filters": None,
"group_name_max_length": 256,
"tags_to_group_by": [],
"tags_to_not_group_by": [],
"primary_vnic_only": False,
"auth_type": "api_key",
"delegation_token_file": None,
}
self.group_prefix = "oci_"
self.display = Display()
def _get_config_file(self):
"""
:param config_data: contents of the inventory config file
"""
# Preference order: .oci.yml > environment variable > settings from config file.
if self.get_option("config_file") is not None:
self.params["config_file"] = os.path.expanduser(
self.get_option("config_file")
)
elif "OCI_CONFIG_FILE" in os.environ:
self.params["config_file"] = os.path.expanduser(
os.path.expandvars(os.environ.get("OCI_CONFIG_FILE"))
)
if self.get_option("config_profile") is not None:
self.params["profile"] = self.get_option("config_profile")
elif "OCI_CONFIG_PROFILE" in os.environ:
self.params["profile"] = os.environ.get("OCI_CONFIG_PROFILE")
def _get_key_file(self):
# preference order: .oci.yml > environment variable > settings from config file.
if self.get_option("api_user_key_file") is not None:
self.params["key_file"] = os.path.expanduser(
self.get_option("api_user_key_file")
)
elif "OCI_USER_KEY_FILE" in os.environ:
self.params["key_file"] = os.path.expanduser(
os.path.expandvars(os.environ.get("OCI_USER_KEY_FILE"))
)
def _get_pass_phrase(self):
# preference order: .oci.yml > environment variable > settings from config file
if self.get_option("api_user_key_pass_phrase") is not None:
self.params["pass_phrase"] = self.get_option("api_user_key_pass_phrase")
elif "OCI_USER_KEY_PASS_PHRASE" in os.environ:
self.params["pass_phrase"] = os.path.expandvars(
os.environ.get("OCI_USER_KEY_PASS_PHRASE")
)
def _get_hostname_format(self):
# Preference order: .oci.yml > environment variable
if self.get_option("hostname_format"):
return self.get_option("hostname_format")
if os.environ.get("OCI_HOSTNAME_FORMAT"):
return os.environ.get("OCI_HOSTNAME_FORMAT")
return "public_ip"
def _get_hostname_from_preference(self, host_vars):
hostname_format_preferences = (
self.get_option("hostname_format_preferences") or []
)
host_vars = host_vars or {}
hostname = None
for preference in hostname_format_preferences:
try:
hostname = self._compose(preference, host_vars)
except Exception as e:
self.debug(
"Error occurred while composing hostname_format_preferences - {0} to hostname - {1}".format(
preference, str(e)
)
)
if self.get_option("strict"):
raise AnsibleError(
"Error occurred while composing hostname_format_preferences - {0} to hostname - {1}".format(
preference, str(e)
)
)
if hostname:
return hostname
return None
def _validate_hostname_format(self):
hostname_format = self.params.get("hostname_format")
hostname_format_preferences = self.get_option("hostname_format_preferences")
if hostname_format_preferences and self.get_option("hostname_format"):
raise AnsibleError(
"hostname_format and hostname_format_preferences cannot be used together"
)
if hostname_format == "display_name" and self._fetch_db_hosts():
raise AnsibleError(
"The hostname_format %s is not supported for db_hosts"
% (hostname_format)
)
def _validate_filters(self):
static_filter = self.get_option("filters")
include_filter = self.get_option("include_host_filters")
if static_filter and include_filter:
raise AnsibleError(
"The options filters and include_host_filters cannot be used together"
)
def _get_primary_vnic_only(self):
# Preference order: .oci.yml > environment variable
if self.get_option("primary_vnic_only"):
return self.get_option("primary_vnic_only")
if os.environ.get("OCI_PRIMARY_VNIC_ONLY"):
return os.environ.get("OCI_PRIMARY_VNIC_ONLY")
return False
def read_config(self):
self._get_config_file()
# Read values from config file
if os.path.isfile(to_bytes(self.params["config_file"])):
self.config = oci.config.from_file(
file_location=self.params["config_file"],
profile_name=self.params["profile"],
)
self.config["additional_user_agent"] = (
oci_config_utils.inventory_agent_name + oci_version.__version__
)
self.debug(self.config["additional_user_agent"])
for setting in self.config:
self.params[setting] = self.config[setting]
def read_settings_config(self, boolean_options, dict_options):
if self.settings_config.has_section("oci"):
for option in self.settings_config.options("oci"):
if option in boolean_options:
self.params[option] = self.settings_config.getboolean("oci", option)
elif option in dict_options:
self.params[option] = json.loads(
self.settings_config.get("oci", option)
)
else:
self.params[option] = self.settings_config.get("oci", option)
@property
def region_subscriptions(self):
if self._region_subscriptions:
return self._region_subscriptions
if not self.params["tenancy"]:
raise Exception("Tenancy OCID required to get the region subscriptions.")
self._region_subscriptions = oci_common_utils.call_with_backoff(
self.identity_client.list_region_subscriptions,
tenancy_id=self.params["tenancy"],
).data
return self._region_subscriptions
@property
def identity_client(self):
if self._identity_client:
return self._identity_client
self._identity_client = self.create_service_client(IdentityClient)
return self._identity_client
def debug(self, *args, **kwargs):
if self.params["debug"]:
self.display.display(*args, **kwargs)
pass
def setup_clients(self, regions):
"""
:param regions: A list of regions to create clients
"""
self.regions = regions
self._compute_clients = dict(
(region, self.create_service_client(ComputeClient, region=region))
for region in self.regions
)
self._virtual_nw_clients = dict(
(region, self.create_service_client(VirtualNetworkClient, region=region))
for region in self.regions
)
self._database_clients = dict(
(region, self.create_service_client(DatabaseClient, region=region))
for region in self.regions
)
def create_service_client(self, service_client_class, region=None):
"""
Creates a service client using the common module options provided by the user.
:param module: An AnsibleModule that represents user provided options for a Task
:param service_client_class: A class that represents a client to an OCI Service
:param client_kwargs: kwargs that would be passed to the client class
:return: A fully configured client
"""
if not region:
region = self.params["region"]
params = dict(self.params, region=region)
kwargs = {}
if self._is_instance_principal_auth():
self.params["auth_type"] = "instance_principal"
kwargs["signer"] = self.create_instance_principal_signer()
elif self._is_delegation_token_auth():
self.params["auth_type"] = "instance_obo_user"
delegation_token_location = self._get_delegation_token_file()
kwargs["signer"] = self.create_instance_principal_signer(
delegation_token_location=delegation_token_location
)
elif self._is_resource_principal_auth():
self.params["auth_type"] = "resource_principal"
kwargs["signer"] = get_resource_principals_signer()
self.debug("auth_type : {0}".format(self.params["auth_type"]))
# Create service client class with the signer.
client = service_client_class(params, **kwargs)
return client
def _is_instance_principal_auth(self):
# check if auth is set to `instance_principal`. Support for backward compatibility.
if self.get_option("instance_principal_authentication") == "instance_principal":
self.debug(
"instance_principal_authentication parameter is DEPRECATED. Please use auth_type parameter instead."
)
return True
# check if auth type is overridden via module params
if self.get_option("auth_type") == "instance_principal":
return True
elif (
self.get_option("auth_type") is None
and os.environ.get("OCI_ANSIBLE_AUTH_TYPE") == "instance_principal"
):
return True
return False
def _is_delegation_token_auth(self):
# check if auth type is overridden via module params
if self.get_option("auth_type") == "instance_obo_user":
return True
elif (
self.get_option("auth_type") is None
and os.environ.get("OCI_ANSIBLE_AUTH_TYPE") == "instance_obo_user"
):
return True
return False
def _is_resource_principal_auth(self):
if self.get_option("auth_type") == "resource_principal":
return True
elif (
self.get_option("auth_type") is None
and os.environ.get("OCI_ANSIBLE_AUTH_TYPE") == "resource_principal"
):
return True
return False
def _get_delegation_token_file(self):
if self.get_option("delegation_token_file") is not None:
self.params["delegation_token_file"] = os.path.expanduser(
self.get_option("delegation_token_file")
)
elif "OCI_DELEGATION_TOKEN_FILE" in os.environ:
self.params["delegation_token_file"] = os.environ.get(
"OCI_DELEGATION_TOKEN_FILE"
)
return self.params.get("delegation_token_file")
def _fetch_db_hosts(self):
# check if we should fetch db hosts
if self.get_option("fetch_db_hosts") is None:
return False
return self.get_option("fetch_db_hosts")
def _fetch_compute_hosts(self):
# check if we should fetch compute hosts
if self.get_option("fetch_compute_hosts") is None:
return True
return self.get_option("fetch_compute_hosts")
@staticmethod
def create_instance_principal_signer(delegation_token_location=None):
"""
Creates a signer for API authentication.
:param delegation_token_location: path for delegation_token file. If None, Instance_Principal signer will be created.
:return: A signer for authentication
"""
signer = None
try:
if delegation_token_location: # instance_obo_user
signer_kwargs = {}
delegation_token = None
# expand file location
expanded_location = os.path.expanduser(delegation_token_location)
if not os.path.exists(expanded_location):
raise IOError(
"ERROR: delegation_token_file not found at {0}".format(
expanded_location
)
)
# read from file
with open(expanded_location, "r") as delegation_token_file:
delegation_token = delegation_token_file.read().strip()
# check if token is there
if not delegation_token:
raise ValueError(
"ERROR: delegation_token not found in file {0}".format(
expanded_location
)
)
# fill up kwarg
signer_kwargs["delegation_token"] = delegation_token
# create instance_principal_delegation_auth signer
signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner(
**signer_kwargs
)
else:
signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner()
except (ValueError, IOError):
raise
except Exception as ex:
raise Exception(
"Failed retrieving certificates from localhost. Instance principal based authentication is only"
"possible from within OCI compute instances. Exception: {0}".format(
str(ex)
)
)
return signer
@contextmanager
def pool(self, **kwargs):
pool = ThreadPool(**kwargs)
try:
yield pool
finally:
pool.close()
# wait for all the instances to be processed
pool.join()
# terminate the pool
pool.terminate()
def get_compartments_from_compartment_info(self, compartments_info_items):
"""
gets the compartments from compartments_info which is passed in the option compartments
"""
compartments_result = dict()
fetching_hosts_from_all_compartments = False
for key, value in compartments_info_items:
compartments = self.get_compartments(
compartment_ocid=value.get("compartment_ocid"),
parent_compartment_ocid=value.get("parent_compartment_ocid"),
compartment_name=value.get("compartment_name"),
fetch_hosts_from_subcompartments=value.get(
"fetch_hosts_from_subcompartments"
),
)
for compartment in compartments:
if compartment.id in compartments_result:
self.debug(
"Obtained the the compartment {0} twice, picking up the later entry in the list".format(
compartment.id
)
)
if value.get("fetch_hosts_from_subcompartments") and (
"tenancy" in compartment.id
):
fetching_hosts_from_all_compartments = True
self.debug(
"Config given to fetch hosts from all compartments, skipping reading the "
"compartments list further if there are any present"
)
compartments_result[compartment.id] = compartment
if fetching_hosts_from_all_compartments:
break
return compartments_result
def get_compartments_from_exclude_compartment_info(self):
"""
gets the compartments with compartment_ocids from exclude_compartments
"""
exclude_compartments = dict()
for key, value in self.exclude_compartments_info.items():
if value.get("compartment_ocid", None):
exclude_compartments.update({value.get("compartment_ocid"): value})
elif value.get("compartment_name", None):
compartment = self.get_compartment_from_compartment_name(
parent_compartment_ocid=value.get("parent_compartment_ocid", None),
compartment_name=value.get("compartment_name", None),
fetch_hosts_from_subcompartments=False,
exclude_compartments={},
)
exclude_compartments.update({compartment[0].id: value})
return exclude_compartments
def get_all_compartments(self):
"""
gets all the compartments excluding the compartments configured in exclude_compartments
"""
compartments_result = dict()
if self.exclude_compartments_info:
self.exclude_compartments = (
self.get_compartments_from_exclude_compartment_info()
)
if self.compartments_info:
compartments_result = self.get_compartments_from_compartment_info(
self.compartments_info.items()
)
else:
# fetch all compartments in tenancy
compartments = self.get_compartments()
for compartment in compartments:
compartments_result[compartment.id] = compartment
return compartments_result
def _get_instances_by_region(self, regions):
"""
:param regions: a list of regions in which to describe instances
:return A list of instance dictionaries
"""
self.setup_clients(regions)
self.debug("Building inventory.")
self.compartments = self.get_all_compartments()
if not self.compartments:
self.debug("No compartments matching the criteria.")
return
instance_inventories = []
self.debug(
"Fetch compute hosts:{0}".format(self.get_option("fetch_compute_hosts"))
)
self.debug("Fetch db hosts:{0}".format(self.get_option("fetch_db_hosts")))
if self._fetch_compute_hosts():
all_instances = self.get_instances(self.compartments)
instance_inventories = [
self.build_inventory_for_instance(instance, region)
for region in all_instances
for instance in all_instances[region]
]
if self._fetch_db_hosts():
all_db_hosts = self.get_db_hosts(self.compartments)
instance_inventories += [
self.build_inventory_for_db_host(db_host, region)
for region in all_db_hosts
for db_host in all_db_hosts[region]
]
return instance_inventories
def get_instances(self, compartment_ocids):
"""Get and return instances from all the specified compartments and regions.
:param compartment_ocids: List of compartment ocid's to fetch the instances from
:return: dict with region as key and list of instances of the region as value
"""
instances = defaultdict(list)
if self.get_option("enable_parallel_processing"):
for region in self.regions:
num_threads = min(
len(compartment_ocids), self.params["max_thread_count"]
)
self.debug(
"Parallel processing enabled. Getting instances from {0} in {1} threads.".format(
region, num_threads
)
)
with self.pool(processes=num_threads) as pool:
get_filtered_instances_for_region = partial(
self.get_filtered_instances, region=region
)
lists_of_instances = pool.map(
get_filtered_instances_for_region, compartment_ocids
)
for sublist in lists_of_instances:
instances[region].extend(sublist)
else:
for region in self.regions:
for compartment_ocid in compartment_ocids:
instances[region].extend(
self.get_filtered_instances(compartment_ocid, region)
)
return instances
def get_db_hosts(self, compartment_ocids):
"""Get and return instances from all the specified compartments and regions.
:param compartment_ocids: List of compartment ocid's to fetch the instances from
:return: dict with region as key and list of db nodes of the region as value
"""
db_hosts = defaultdict(list)
if self.get_option("enable_parallel_processing"):
for region in self.regions:
num_threads = min(
len(compartment_ocids), self.params["max_thread_count"]
)
self.debug(
"Parallel processing enabled. Getting db hosts from {0} in {1} threads.".format(
region, num_threads
)
)
with self.pool(processes=num_threads) as pool:
get_filtered_db_hosts_for_region = partial(
self.get_filtered_db_hosts, region=region
)
lists_of_instances = pool.map(
get_filtered_db_hosts_for_region, compartment_ocids
)
for sublist in lists_of_instances:
db_hosts[region].extend(sublist)
else:
for region in self.regions:
for compartment_ocid in compartment_ocids:
db_hosts[region].extend(
self.get_filtered_db_hosts(compartment_ocid, region)
)
return db_hosts
def get_compartment_from_compartment_name(
self,
compartment_name,
parent_compartment_ocid=None,
fetch_hosts_from_subcompartments=True,
exclude_compartments=None,
):
"""
Gets the compartments based on the compartment_name.
the compartment with that name and its hierarchy of compartments are returned
if fetch_hosts_from_subcompartments is true.
The tenancy is returned when compartment_name is the tenancy name.
"""
if not self.params["tenancy"]:
raise Exception(
"Tenancy OCID required to get the compartments in the tenancy."
)
if not compartment_name:
raise Exception("compartment_name is required")
tenancy_compartments = self.get_compartment_including_sub_compartments(
compartment_id=self.params["tenancy"],
exclude_compartments=exclude_compartments,
fetch_child_compartments=False,
)
tenancy_name = (
tenancy_compartments[0].name if len(tenancy_compartments) > 0 else None
)
if compartment_name == tenancy_name:
# return all the compartments when fetch_hosts_from_subcompartments is true
if fetch_hosts_from_subcompartments:
return self.get_compartment_including_sub_compartments(
compartment_id=self.params["tenancy"],
exclude_compartments=exclude_compartments,
fetch_child_compartments=True,
)
else:
return tenancy_compartments
if not parent_compartment_ocid:
parent_compartment_ocid = (
tenancy_compartments[0].id if len(tenancy_compartments) > 0 else None
)
all_compartments = self.get_compartment_including_sub_compartments(
compartment_id=self.params["tenancy"],
exclude_compartments=exclude_compartments,
fetch_child_compartments=True,
)
compartment_with_name = None
for compartment in all_compartments:
if (
compartment.name == compartment_name
and compartment.compartment_id == parent_compartment_ocid
):
compartment_with_name = compartment
break
if not compartment_with_name:
raise Exception(
"Compartment with name {0} not found.".format(compartment_name)
)
if not fetch_hosts_from_subcompartments:
return [compartment_with_name]
return self.get_compartment_including_sub_compartments(
compartment_id=compartment_with_name.id,
exclude_compartments=self.exclude_compartments,
fetch_child_compartments=True,
)
def get_compartments(
self,
compartment_ocid=None,
parent_compartment_ocid=None,
compartment_name=None,
fetch_hosts_from_subcompartments=True,
):
"""
Get the compartments based on the parameters passed. When compartment_name is None, all the compartments
including the root compartment is returned.
When compartment_name is passed, the compartment with that name and its hierarchy of compartments are returned
if fetch_hosts_from_subcompartments is true.
The tenancy is returned when compartment_name is the tenancy name.
When both compartment_ocid and compartment_name are not passed, all the compartments are returned.
:param str compartment_ocid: (optional)
OCID of the compartment. If None, root compartment is assumed to be parent.
:param str parent_compartment_ocid: (optional)
OCID of the parent compartment. If None, root compartment is assumed to be parent.
:param str compartment_name: (optional)
Name of the compartment. If None and :attr:`compartment_ocid` is not set, all the compartments including
the root compartment are returned.
:param str fetch_hosts_from_subcompartments: (optional)
Only applicable when compartment_name or compartment_ocid is specified. When set to true, the entire
hierarchy of compartments of the given compartment is returned.
:raises ServiceError: When the Service returned an Error response
:raises MaximumWaitTimeExceededError: When maximum wait time is exceeded while invoking target_fn
:return: list of :class:`~oci.identity.models.Compartment`
"""
if compartment_ocid:
return self.get_compartment_including_sub_compartments(
compartment_id=compartment_ocid,
exclude_compartments=self.exclude_compartments,
fetch_child_compartments=fetch_hosts_from_subcompartments,