| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright (c) 2023 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_mq |
| 8 |
version_added: 6.1.0 |
| 9 |
short_description: MQ broker inventory source |
| 10 |
description: |
| 11 |
- Get brokers from Amazon Web Services MQ. |
| 12 |
- Uses a YAML configuration file that ends with aws_mq.(yml|yaml). |
| 13 |
options: |
| 14 |
regions: |
| 15 |
description: |
| 16 |
- A list of regions in which to describe MQ brokers. Available regions are listed here |
| 17 |
U(https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) |
| 18 |
type: list |
| 19 |
elements: str |
| 20 |
default: [] |
| 21 |
strict_permissions: |
| 22 |
description: By default if an AccessDenied exception is encountered this plugin will fail. You can set I(strict_permissions) to |
| 23 |
C(False) in the inventory config file which will allow the restrictions to be gracefully skipped. |
| 24 |
type: bool |
| 25 |
default: True |
| 26 |
statuses: |
| 27 |
description: |
| 28 |
- A list of desired states for brokers to be added to inventory. Set to C(['all']) as a shorthand to find everything. |
| 29 |
Possible value are listed here U(https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/broker-statuses.html) |
| 30 |
type: list |
| 31 |
elements: str |
| 32 |
default: |
| 33 |
- RUNNING |
| 34 |
- CREATION_IN_PROGRESS |
| 35 |
hostvars_prefix: |
| 36 |
description: |
| 37 |
- The prefix for host variables names coming from AWS. |
| 38 |
type: str |
| 39 |
hostvars_suffix: |
| 40 |
description: |
| 41 |
- The suffix for host variables names coming from AWS. |
| 42 |
type: str |
| 43 |
extends_documentation_fragment: |
| 44 |
- inventory_cache |
| 45 |
- constructed |
| 46 |
- amazon.aws.boto3 |
| 47 |
- amazon.aws.common.plugins |
| 48 |
- amazon.aws.region.plugins |
| 49 |
- amazon.aws.assume_role.plugins |
| 50 |
author: |
| 51 |
- Ali AlKhalidi (@doteast) |
| 52 |
""" |
| 53 |
|
| 54 |
EXAMPLES = r""" |
| 55 |
--- |
| 56 |
# Minimal example using AWS credentials from environment vars or instance role credentials |
| 57 |
# Get all brokers in us-east-1 region |
| 58 |
plugin: community.aws.aws_mq |
| 59 |
regions: |
| 60 |
- ca-central-1 |
| 61 |
|
| 62 |
--- |
| 63 |
|
| 64 |
# Example multiple regions, ignoring permission errors, and only brokers with state RUNNING |
| 65 |
plugin: community.aws.aws_mq |
| 66 |
regions: |
| 67 |
- us-east-1 |
| 68 |
- us-east-2 |
| 69 |
strict_permissions: false |
| 70 |
statuses: |
| 71 |
- RUNNING |
| 72 |
|
| 73 |
--- |
| 74 |
|
| 75 |
# Example group by engine, hostvars custom prefix-suffix, and compose variable from tags |
| 76 |
plugin: community.aws.aws_mq |
| 77 |
regions: |
| 78 |
- ca-central-1 |
| 79 |
keyed_groups: |
| 80 |
- key: engine_type |
| 81 |
prefix: mq |
| 82 |
compose: |
| 83 |
app: 'tags.Applications|split(",")' |
| 84 |
hostvars_prefix: aws_ |
| 85 |
hostvars_suffix: _mq |
| 86 |
""" |
| 87 |
|
| 88 |
try: |
| 89 |
import botocore |
| 90 |
except ImportError: |
| 91 |
pass # will be captured by imported HAS_BOTO3 |
| 92 |
|
| 93 |
from ansible.errors import AnsibleError |
| 94 |
from ansible.module_utils._text import to_native |
| 95 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 96 |
|
| 97 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 98 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 99 |
from ansible_collections.amazon.aws.plugins.plugin_utils.inventory import AWSInventoryBase |
| 100 |
|
| 101 |
broker_attr = [ |
| 102 |
"MaintenanceWindowStartTime", |
| 103 |
"AutoMinorVersionUpgrade", |
| 104 |
"AuthenticationStrategy", |
| 105 |
"PubliclyAccessible", |
| 106 |
"EncryptionOptions", |
| 107 |
"HostInstanceType", |
| 108 |
"BrokerInstances", |
| 109 |
"SecurityGroups", |
| 110 |
"DeploymentMode", |
| 111 |
"EngineVersion", |
| 112 |
"StorageType", |
| 113 |
"BrokerState", |
| 114 |
"EngineType", |
| 115 |
"SubnetIds", |
| 116 |
"BrokerArn", |
| 117 |
"BrokerId", |
| 118 |
"Created", |
| 119 |
"Logs", |
| 120 |
] |
| 121 |
|
| 122 |
inventory_group = "aws_mq" |
| 123 |
|
| 124 |
|
| 125 |
def _find_hosts_matching_statuses(hosts, statuses): |
| 126 |
if not statuses: |
| 127 |
statuses = ["RUNNING", "CREATION_IN_PROGRESS"] |
| 128 |
if "all" in statuses: |
| 129 |
return hosts |
| 130 |
valid_hosts = [] |
| 131 |
for host in hosts: |
| 132 |
if host.get("BrokerState") in statuses: |
| 133 |
valid_hosts.append(host) |
| 134 |
return valid_hosts |
| 135 |
|
| 136 |
|
| 137 |
def _get_mq_hostname(host): |
| 138 |
if host.get("BrokerName"): |
| 139 |
return host["BrokerName"] |
| 140 |
|
| 141 |
|
| 142 |
def _get_broker_host_tags(detail): |
| 143 |
tags = [] |
| 144 |
if "Tags" in detail: |
| 145 |
for key, value in detail["Tags"].items(): |
| 146 |
tags.append({"Key": key, "Value": value}) |
| 147 |
return tags |
| 148 |
|
| 149 |
|
| 150 |
def _add_details_to_hosts(connection, hosts, strict): |
| 151 |
for host in hosts: |
| 152 |
detail = None |
| 153 |
resource_id = host["BrokerId"] |
| 154 |
try: |
| 155 |
detail = connection.describe_broker(BrokerId=resource_id) |
| 156 |
except is_boto3_error_code("AccessDenied") as e: |
| 157 |
if not strict: |
| 158 |
pass |
| 159 |
else: |
| 160 |
raise AnsibleError(f"Failed to query MQ: {to_native(e)}") |
| 161 |
except ( |
| 162 |
botocore.exceptions.BotoCoreError, |
| 163 |
botocore.exceptions.ClientError, |
| 164 |
) as e: # pylint: disable=duplicate-except |
| 165 |
raise AnsibleError(f"Failed to query MQ: {to_native(e)}") |
| 166 |
|
| 167 |
if detail: |
| 168 |
# special handling of tags |
| 169 |
host["Tags"] = _get_broker_host_tags(detail) |
| 170 |
|
| 171 |
# collect rest of attributes |
| 172 |
for attr in broker_attr: |
| 173 |
if attr in detail: |
| 174 |
host[attr] = detail[attr] |
| 175 |
|
| 176 |
|
| 177 |
class InventoryModule(AWSInventoryBase): |
| 178 |
NAME = "community.aws.aws_mq" |
| 179 |
INVENTORY_FILE_SUFFIXES = ("aws_mq.yml", "aws_mq.yaml") |
| 180 |
|
| 181 |
def __init__(self): |
| 182 |
super(InventoryModule, self).__init__() |
| 183 |
|
| 184 |
def _get_broker_hosts(self, connection, strict): |
| 185 |
def _boto3_paginate_wrapper(func, *args, **kwargs): |
| 186 |
results = [] |
| 187 |
try: |
| 188 |
results = func(*args, **kwargs) |
| 189 |
results = results["BrokerSummaries"] |
| 190 |
_add_details_to_hosts(connection, results, strict) |
| 191 |
except is_boto3_error_code("AccessDenied") as e: # pylint: disable=duplicate-except |
| 192 |
if not strict: |
| 193 |
results = [] |
| 194 |
else: |
| 195 |
raise AnsibleError(f"Failed to query MQ: {to_native(e)}") |
| 196 |
except ( |
| 197 |
botocore.exceptions.ClientError, |
| 198 |
botocore.exceptions.BotoCoreError, |
| 199 |
) as e: # pylint: disable=duplicate-except |
| 200 |
raise AnsibleError(f"Failed to query MQ: {to_native(e)}") |
| 201 |
return results |
| 202 |
|
| 203 |
return _boto3_paginate_wrapper |
| 204 |
|
| 205 |
def _get_all_hosts(self, regions, strict, statuses): |
| 206 |
""" |
| 207 |
:param regions: a list of regions in which to describe hosts |
| 208 |
:param strict: a boolean determining whether to fail or ignore 403 error codes |
| 209 |
:param statuses: a list of statuses that the returned hosts should match |
| 210 |
:return A list of host dictionaries |
| 211 |
""" |
| 212 |
all_instances = [] |
| 213 |
|
| 214 |
for connection, _region in self.all_clients("mq"): |
| 215 |
paginator = connection.get_paginator("list_brokers") |
| 216 |
all_instances.extend(self._get_broker_hosts(connection, strict)(paginator.paginate().build_full_result)) |
| 217 |
sorted_hosts = list(sorted(all_instances, key=lambda x: x["BrokerName"])) |
| 218 |
return _find_hosts_matching_statuses(sorted_hosts, statuses) |
| 219 |
|
| 220 |
def _populate_from_cache(self, cache_data): |
| 221 |
hostvars = cache_data.pop("_meta", {}).get("hostvars", {}) |
| 222 |
for group in cache_data: |
| 223 |
if group == "all": |
| 224 |
continue |
| 225 |
self.inventory.add_group(group) |
| 226 |
hosts = cache_data[group].get("hosts", []) |
| 227 |
for host in hosts: |
| 228 |
self._populate_host_vars([host], hostvars.get(host, {}), group) |
| 229 |
self.inventory.add_child("all", group) |
| 230 |
|
| 231 |
def _populate(self, hosts): |
| 232 |
group = inventory_group |
| 233 |
self.inventory.add_group(group) |
| 234 |
if hosts: |
| 235 |
self._add_hosts(hosts=hosts, group=group) |
| 236 |
self.inventory.add_child("all", group) |
| 237 |
|
| 238 |
def _format_inventory(self, hosts): |
| 239 |
results = {"_meta": {"hostvars": {}}} |
| 240 |
group = inventory_group |
| 241 |
results[group] = {"hosts": []} |
| 242 |
for host in hosts: |
| 243 |
hostname = _get_mq_hostname(host) |
| 244 |
results[group]["hosts"].append(hostname) |
| 245 |
h = self.inventory.get_host(hostname) |
| 246 |
results["_meta"]["hostvars"][h.name] = h.vars |
| 247 |
return results |
| 248 |
|
| 249 |
def _add_hosts(self, hosts, group): |
| 250 |
""" |
| 251 |
:param hosts: a list of hosts to add to the group |
| 252 |
:param group: name of the group the host list belongs to |
| 253 |
""" |
| 254 |
for host in hosts: |
| 255 |
hostname = _get_mq_hostname(host) |
| 256 |
host = camel_dict_to_snake_dict(host, ignore_list=["Tags", "EngineType"]) |
| 257 |
host["tags"] = boto3_tag_list_to_ansible_dict(host.get("tags", [])) |
| 258 |
if host.get("engine_type"): |
| 259 |
# align value with API spec of all upper |
| 260 |
host["engine_type"] = host.get("engine_type", "").upper() |
| 261 |
|
| 262 |
self.inventory.add_host(hostname, group=group) |
| 263 |
new_vars = dict() |
| 264 |
hostvars_prefix = self.get_option("hostvars_prefix") |
| 265 |
hostvars_suffix = self.get_option("hostvars_suffix") |
| 266 |
for hostvar, hostval in host.items(): |
| 267 |
if hostvars_prefix: |
| 268 |
hostvar = hostvars_prefix + hostvar |
| 269 |
if hostvars_suffix: |
| 270 |
hostvar = hostvar + hostvars_suffix |
| 271 |
new_vars[hostvar] = hostval |
| 272 |
self.inventory.set_variable(hostname, hostvar, hostval) |
| 273 |
host.update(new_vars) |
| 274 |
|
| 275 |
strict = self.get_option("strict") |
| 276 |
self._set_composite_vars(self.get_option("compose"), host, hostname, strict=strict) |
| 277 |
self._add_host_to_composed_groups(self.get_option("groups"), host, hostname, strict=strict) |
| 278 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), host, hostname, strict=strict) |
| 279 |
|
| 280 |
def parse(self, inventory, loader, path, cache=True): |
| 281 |
super().parse(inventory, loader, path, cache=cache) |
| 282 |
|
| 283 |
# get user specifications |
| 284 |
regions = self.get_option("regions") |
| 285 |
strict_permissions = self.get_option("strict_permissions") |
| 286 |
statuses = self.get_option("statuses") |
| 287 |
|
| 288 |
result_was_cached, results = self.get_cached_result(path, cache) |
| 289 |
if result_was_cached: |
| 290 |
self._populate_from_cache(results) |
| 291 |
return |
| 292 |
|
| 293 |
results = self._get_all_hosts(regions, strict_permissions, statuses) |
| 294 |
self._populate(results) |
| 295 |
|
| 296 |
formatted_inventory = self._format_inventory(results) |
| 297 |
self.update_cached_result(path, cache, formatted_inventory) |