Debian Codegraph @

ansible_collections/amazon/aws/plugins/plugin_utils/inventory.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2022, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 try:
7 import boto3
8 import botocore
9 except ImportError:
10 pass # will be captured by imported HAS_BOTO3
11
12 from ansible.plugins.inventory import BaseInventoryPlugin
13 from ansible.plugins.inventory import Cacheable
14 from ansible.plugins.inventory import Constructable
15
16 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
17 from ansible_collections.amazon.aws.plugins.plugin_utils.base import AWSPluginBase
18 from ansible_collections.amazon.aws.plugins.plugin_utils.botocore import AnsibleBotocoreError
19
20
21 def _boto3_session(profile_name=None):
22 if profile_name is None:
23 return boto3.Session()
24 return boto3.session.Session(profile_name=profile_name)
25
26
27 class AWSInventoryBase(BaseInventoryPlugin, Constructable, Cacheable, AWSPluginBase):
28 class TemplatedOptions:
29 # When someone looks up the TEMPLATABLE_OPTIONS using get() any templates
30 # will be templated using the loader passed to parse.
31 TEMPLATABLE_OPTIONS = (
32 "access_key",
33 "secret_key",
34 "session_token",
35 "profile",
36 "endpoint_url",
37 "assume_role_arn",
38 "region",
39 "regions",
40 "filters",
41 )
42
43 def __init__(self, templar, options):
44 self.original_options = options
45 self.templar = templar
46
47 def __getitem__(self, *args):
48 return self.original_options.__getitem__(self, *args)
49
50 def __setitem__(self, *args):
51 return self.original_options.__setitem__(self, *args)
52
53 def get(self, *args):
54 value = self.original_options.get(*args)
55 if not value or not self.templar or args[0] not in self.TEMPLATABLE_OPTIONS:
56 return value
57
58 if isinstance(value, dict):
59 return {k: self.templar.template(variable=v) for k, v in value.items()}
60 if isinstance(value, list):
61 return [self.templar.template(variable=v) for v in value]
62
63 if not self.templar.is_template(value):
64 return value
65
66 return self.templar.template(variable=value)
67
68 def get_options(self, *args):
69 return self.TemplatedOptions(self.templar, super().get_options(*args))
70
71 def get_option(self, option, hostvars=None):
72 return self.TemplatedOptions(self.templar, {option: super().get_option(option, hostvars)}).get(option)
73
74 def __init__(self):
75 super().__init__()
76 self._frozen_credentials = {}
77
78 # pylint: disable=too-many-arguments
79 def parse(self, inventory, loader, path, cache=True, botocore_version=None, boto3_version=None):
80 super().parse(inventory, loader, path)
81 self.require_aws_sdk(botocore_version=botocore_version, boto3_version=boto3_version)
82 self._read_config_data(path)
83 self._set_frozen_credentials()
84
85 def client(self, *args, **kwargs):
86 kw_args = dict(self._frozen_credentials)
87 kw_args.update(kwargs)
88 return super().client(*args, **kw_args)
89
90 def resource(self, *args, **kwargs):
91 kw_args = dict(self._frozen_credentials)
92 kw_args.update(kwargs)
93 return super().resource(*args, **kw_args)
94
95 def _get_role_session_name(self):
96 """
97 Generate the role session name for assume_role operations.
98
99 Returns the session name based on the plugin's ansible_name attribute if present,
100 otherwise returns a default session name.
101 """
102 if hasattr(self, "ansible_name") and self.ansible_name:
103 return f"ansible_aws_{self.ansible_name}_dynamic_inventory"
104 return "ansible_aws_dynamic_inventory"
105
106 def _freeze_iam_role(self, iam_role_arn):
107 role_session_name = self._get_role_session_name()
108 assume_params = {"RoleArn": iam_role_arn, "RoleSessionName": role_session_name}
109
110 try:
111 sts = self.client("sts")
112 assumed_role = sts.assume_role(**assume_params)
113 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError, AnsibleBotocoreError) as e:
114 self.fail_aws(f"Unable to assume role {iam_role_arn}", exception=e)
115
116 credentials = assumed_role.get("Credentials")
117 if not credentials:
118 self.fail_aws(f"Unable to assume role {iam_role_arn}")
119
120 self._frozen_credentials = {
121 "profile_name": None,
122 "aws_access_key_id": credentials.get("AccessKeyId"),
123 "aws_secret_access_key": credentials.get("SecretAccessKey"),
124 "aws_session_token": credentials.get("SessionToken"),
125 }
126
127 def _set_frozen_credentials(self):
128 iam_role_arn = self.get_option("assume_role_arn")
129 if iam_role_arn:
130 self._freeze_iam_role(iam_role_arn)
131
132 def _describe_regions(self, service):
133 # Try pulling a list of regions from the service
134 try:
135 initial_region = self.region or "us-east-1"
136 client = self.client(service, region=initial_region)
137 resp = client.describe_regions()
138 except AttributeError:
139 # Not all clients support describe
140 pass
141 except is_boto3_error_code("UnauthorizedOperation"):
142 self.warn(f"UnauthorizedOperation when trying to list {service} regions")
143 except botocore.exceptions.NoRegionError:
144 self.warn(f"NoRegionError when trying to list {service} regions")
145 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
146 self.warn(f"Unexpected error while trying to list {service} regions: {e}")
147 else:
148 regions = [x["RegionName"] for x in resp.get("Regions", [])]
149 if regions:
150 return regions
151 return None
152
153 def _boto3_regions(self, service):
154 regions = self.get_option("regions")
155 if regions:
156 return regions
157
158 # boto3 has hard coded lists of available regions for resources, however this does bit-rot
159 # As such we try to query the service, and fall back to ec2 for a list of regions
160 services_to_try = [service] if service == "ec2" else [service, "ec2"]
161 for resource_type in services_to_try:
162 regions = self._describe_regions(resource_type)
163 if regions:
164 return regions
165
166 # fallback to local list hardcoded in boto3 if still no regions
167 session = _boto3_session(self.get_option("profile"))
168 regions = session.get_available_regions(service)
169
170 if not regions:
171 # I give up, now you MUST give me regions
172 self.fail_aws(
173 "Unable to get regions list from available methods, you must specify the 'regions' option to continue."
174 )
175
176 return regions
177
178 def all_clients(self, service):
179 """
180 Generator that yields a boto3 client and the region
181
182 :param service: The boto3 service to connect to.
183
184 Note: For services which don't support 'DescribeRegions' this may include bad
185 endpoints, and as such EndpointConnectionError should be cleanly handled as a non-fatal
186 error.
187 """
188 regions = self._boto3_regions(service=service)
189
190 for region in regions:
191 connection = self.client(service, region=region)
192 yield connection, region
193
194 def get_cached_result(self, path, cache):
195 # false when refresh_cache or --flush-cache is used
196 if not cache:
197 return False, None
198 # get the user-specified directive
199 if not self.get_option("cache"):
200 return False, None
201
202 cache_key = self.get_cache_key(path)
203 try:
204 cached_value = self._cache[cache_key]
205 except KeyError:
206 # if cache expires or cache file doesn"t exist
207 return False, None
208
209 return True, cached_value
210
211 def update_cached_result(self, path, cache, result):
212 if not self.get_option("cache"):
213 return
214
215 cache_key = self.get_cache_key(path)
216 # We weren't explicitly told to flush the cache, and there's already a cache entry,
217 # this means that the result we're being passed came from the cache. As such we don't
218 # want to "update" the cache as that could reset a TTL on the cache entry.
219 if cache and cache_key in self._cache:
220 return
221
222 self._cache[cache_key] = result
223
224 def verify_file(self, path):
225 """
226 :param path: the path to the inventory config file
227 :return the contents of the config file
228 """
229 if not super().verify_file(path):
230 return False
231
232 if hasattr(self, "INVENTORY_FILE_SUFFIXES"):
233 if not path.endswith(self.INVENTORY_FILE_SUFFIXES):
234 return False
235
236 return True