Debian Codegraph @

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

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2018 Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 DOCUMENTATION = r"""
7 name: aws_rds
8 short_description: RDS instance inventory source
9 description:
10 - Get instances and clusters from Amazon Web Services RDS.
11 - Uses a YAML configuration file that ends with aws_rds.(yml|yaml).
12 options:
13 regions:
14 description:
15 - A list of regions in which to describe RDS instances and clusters. Available regions are listed here
16 U(https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html).
17 default: []
18 filters:
19 description:
20 - A dictionary of filter value pairs. Available filters are listed here
21 U(https://docs.aws.amazon.com/cli/latest/reference/rds/describe-db-instances.html#options). If you filter by
22 db-cluster-id and I(include_clusters) is True it will apply to clusters as well.
23 default: {}
24 strict_permissions:
25 description:
26 - By default if an AccessDenied exception is encountered this plugin will fail. You can set strict_permissions to
27 False in the inventory config file which will allow the restrictions to be gracefully skipped.
28 type: bool
29 default: true
30 include_clusters:
31 description: Whether or not to query for Aurora clusters as well as instances.
32 type: bool
33 default: false
34 statuses:
35 description: A list of desired states for instances/clusters to be added to inventory. Set to ['all'] as a shorthand to find everything.
36 type: list
37 elements: str
38 default:
39 - creating
40 - available
41 hostvars_prefix:
42 description:
43 - The prefix for host variables names coming from AWS.
44 type: str
45 version_added: 3.1.0
46 hostvars_suffix:
47 description:
48 - The suffix for host variables names coming from AWS.
49 type: str
50 version_added: 3.1.0
51 notes:
52 - Ansible versions prior to 2.10 should use the fully qualified plugin name 'amazon.aws.aws_rds'.
53 - The C(tags) host variable is deprecated and will be removed in a release after 2026-12-01.
54 Use C(rds_tags) instead to avoid conflicts with Ansible reserved variable names.
55 - The C(rds_tags) host variable was added in version 11.2.0.
56 extends_documentation_fragment:
57 - inventory_cache
58 - constructed
59 - amazon.aws.boto3
60 - amazon.aws.common.plugins
61 - amazon.aws.region.plugins
62 - amazon.aws.assume_role.plugins
63 author:
64 - Sloane Hertel (@s-hertel)
65 """
66
67 EXAMPLES = r"""
68 plugin: aws_rds
69 regions:
70 - us-east-1
71 - ca-central-1
72 keyed_groups:
73 - key: 'db_parameter_groups|json_query("[].db_parameter_group_name")'
74 prefix: rds_parameter_group
75 - key: engine
76 prefix: rds
77 - key: rds_tags
78 - key: region
79 hostvars_prefix: aws_
80 hostvars_suffix: _rds
81 """
82
83 try:
84 import botocore
85 except ImportError:
86 pass # will be captured by imported HAS_BOTO3
87
88 from ansible.errors import AnsibleError
89 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
90 from ansible.module_utils.common.text.converters import to_native
91
92 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
93 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
94 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
95 from ansible_collections.amazon.aws.plugins.plugin_utils.inventory import AWSInventoryBase
96
97
98 def _find_hosts_with_valid_statuses(hosts, statuses):
99 if "all" in statuses:
100 return hosts
101 valid_hosts = []
102 for host in hosts:
103 if host.get("DBInstanceStatus") in statuses:
104 valid_hosts.append(host)
105 elif host.get("Status") in statuses:
106 valid_hosts.append(host)
107 return valid_hosts
108
109
110 def _get_rds_hostname(host):
111 if host.get("DBInstanceIdentifier"):
112 return host["DBInstanceIdentifier"]
113 else:
114 return host["DBClusterIdentifier"]
115
116
117 def _add_tags_for_rds_hosts(connection, hosts, strict):
118 for host in hosts:
119 if "DBInstanceArn" in host:
120 resource_arn = host["DBInstanceArn"]
121 else:
122 resource_arn = host["DBClusterArn"]
123
124 try:
125 tags = connection.list_tags_for_resource(ResourceName=resource_arn)["TagList"]
126 except is_boto3_error_code("AccessDenied") as e:
127 if not strict:
128 tags = []
129 else:
130 raise e
131 host["Tags"] = tags
132
133
134 def describe_resource_with_tags(func):
135 def describe_wrapper(connection, filters, strict=False):
136 try:
137 results = func(connection=connection, filters=filters)
138 if "DBInstances" in results:
139 results = results["DBInstances"]
140 else:
141 results = results["DBClusters"]
142 _add_tags_for_rds_hosts(connection, results, strict)
143 except is_boto3_error_code("AccessDenied") as e: # pylint: disable=duplicate-except
144 if not strict:
145 return []
146 raise AnsibleError(f"Failed to query RDS: {to_native(e)}")
147 except (
148 botocore.exceptions.BotoCoreError,
149 botocore.exceptions.ClientError,
150 ) as e: # pylint: disable=duplicate-except
151 raise AnsibleError(f"Failed to query RDS: {to_native(e)}")
152
153 return results
154
155 return describe_wrapper
156
157
158 @describe_resource_with_tags
159 def _describe_db_instances(connection, filters):
160 paginator = connection.get_paginator("describe_db_instances")
161 return paginator.paginate(Filters=filters).build_full_result()
162
163
164 @describe_resource_with_tags
165 def _describe_db_clusters(connection, filters):
166 return connection.describe_db_clusters(Filters=filters)
167
168
169 class InventoryModule(AWSInventoryBase):
170 NAME = "amazon.aws.aws_rds"
171 INVENTORY_FILE_SUFFIXES = ("aws_rds.yml", "aws_rds.yaml")
172
173 def __init__(self):
174 super().__init__()
175 self.credentials = {}
176
177 def _populate(self, hosts):
178 group = "aws_rds"
179 self.inventory.add_group(group)
180 if hosts:
181 self._add_hosts(hosts=hosts, group=group)
182 self.inventory.add_child("all", group)
183
184 def _populate_from_source(self, source_data):
185 hostvars = source_data.pop("_meta", {}).get("hostvars", {})
186 for group in source_data:
187 if group == "all":
188 continue
189 self.inventory.add_group(group)
190 hosts = source_data[group].get("hosts", [])
191 for host in hosts:
192 self._populate_host_vars([host], hostvars.get(host, {}), group)
193 self.inventory.add_child("all", group)
194
195 def _format_inventory(self, hosts):
196 results = {"_meta": {"hostvars": {}}}
197 group = "aws_rds"
198 results[group] = {"hosts": []}
199 for host in hosts:
200 hostname = _get_rds_hostname(host)
201 results[group]["hosts"].append(hostname)
202 h = self.inventory.get_host(hostname)
203 results["_meta"]["hostvars"][h.name] = h.vars
204 return results
205
206 def _add_hosts(self, hosts, group):
207 """
208 :param hosts: a list of hosts to be added to a group
209 :param group: the name of the group to which the hosts belong
210 """
211 for host in hosts:
212 hostname = _get_rds_hostname(host)
213 host = camel_dict_to_snake_dict(host, ignore_list=["Tags"])
214 host["rds_tags"] = boto3_tag_list_to_ansible_dict(host.get("tags", []))
215 # rds_tags is the new key, tags is deprecated but kept for backward compatibility
216 host["tags"] = host["rds_tags"]
217
218 # Allow easier grouping by region
219 if "availability_zone" in host:
220 host["region"] = host["availability_zone"][:-1]
221 elif "availability_zones" in host:
222 host["region"] = host["availability_zones"][0][:-1]
223
224 self.inventory.add_host(hostname, group=group)
225 hostvars_prefix = self.get_option("hostvars_prefix")
226 hostvars_suffix = self.get_option("hostvars_suffix")
227 new_vars = dict()
228 for hostvar, hostval in host.items():
229 if hostvars_prefix:
230 hostvar = hostvars_prefix + hostvar
231 if hostvars_suffix:
232 hostvar = hostvar + hostvars_suffix
233 new_vars[hostvar] = hostval
234 self.inventory.set_variable(hostname, hostvar, hostval)
235 host.update(new_vars)
236
237 # Use constructed if applicable
238 strict = self.get_option("strict")
239 # Composed variables
240 self._set_composite_vars(self.get_option("compose"), host, hostname, strict=strict)
241 # Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group
242 self._add_host_to_composed_groups(self.get_option("groups"), host, hostname, strict=strict)
243 # Create groups based on variable values and add the corresponding hosts to it
244 self._add_host_to_keyed_groups(self.get_option("keyed_groups"), host, hostname, strict=strict)
245
246 def _get_all_db_hosts(self, regions, instance_filters, cluster_filters, strict, statuses, gather_clusters=False):
247 """
248 :param regions: a list of regions in which to describe hosts
249 :param instance_filters: a list of boto3 filter dictionaries
250 :param cluster_filters: a list of boto3 filter dictionaries
251 :param strict: a boolean determining whether to fail or ignore 403 error codes
252 :param statuses: a list of statuses that the returned hosts should match
253 :return A list of host dictionaries
254 """
255 all_instances = []
256 all_clusters = []
257
258 for connection, _region in self.all_clients("rds"):
259 all_instances += _describe_db_instances(connection, instance_filters, strict=strict)
260 if gather_clusters:
261 all_clusters += _describe_db_clusters(connection, cluster_filters, strict=strict)
262 sorted_hosts = list(
263 sorted(all_instances, key=lambda x: x["DBInstanceIdentifier"])
264 + sorted(all_clusters, key=lambda x: x["DBClusterIdentifier"])
265 )
266 return _find_hosts_with_valid_statuses(sorted_hosts, statuses)
267
268 def parse(self, inventory, loader, path, cache=True):
269 super().parse(inventory, loader, path, cache=cache)
270
271 self.display.deprecated(
272 "The 'tags' host variable is deprecated. Use 'rds_tags' instead.",
273 date="2026-12-01",
274 collection_name="amazon.aws",
275 )
276
277 # get user specifications
278 regions = self.get_option("regions")
279 filters = self.get_option("filters")
280 strict_permissions = self.get_option("strict_permissions")
281 statuses = self.get_option("statuses")
282 include_clusters = self.get_option("include_clusters")
283 instance_filters = ansible_dict_to_boto3_filter_list(filters)
284 cluster_filters = []
285 if "db-cluster-id" in filters and include_clusters:
286 cluster_filters = ansible_dict_to_boto3_filter_list({"db-cluster-id": filters["db-cluster-id"]})
287
288 result_was_cached, cached_result = self.get_cached_result(path, cache)
289 if result_was_cached:
290 self._populate_from_source(cached_result)
291 return
292
293 results = self._get_all_db_hosts(
294 regions,
295 instance_filters,
296 cluster_filters,
297 strict_permissions,
298 statuses,
299 include_clusters,
300 )
301 self._populate(results)
302
303 # Update the cache once we're done
304 formatted_inventory = self._format_inventory(results)
305 self.update_cached_result(path, cache, formatted_inventory)