| 1 |
# Copyright (c) 2021, Cliff Hults <[email protected]> |
| 2 |
# Copyright (c) 2021 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
name: icinga2 |
| 9 |
short_description: Icinga2 inventory source |
| 10 |
version_added: 3.7.0 |
| 11 |
author: |
| 12 |
- Cliff Hults (@BongoEADGC6) <[email protected]> |
| 13 |
description: |
| 14 |
- Get inventory hosts from the Icinga2 API. |
| 15 |
- Uses a configuration file as an inventory source, it must end in C(.icinga2.yml) or C(.icinga2.yaml). |
| 16 |
extends_documentation_fragment: |
| 17 |
- ansible.builtin.constructed |
| 18 |
options: |
| 19 |
strict: |
| 20 |
version_added: 4.4.0 |
| 21 |
compose: |
| 22 |
version_added: 4.4.0 |
| 23 |
groups: |
| 24 |
version_added: 4.4.0 |
| 25 |
keyed_groups: |
| 26 |
version_added: 4.4.0 |
| 27 |
plugin: |
| 28 |
description: Name of the plugin. |
| 29 |
required: true |
| 30 |
type: string |
| 31 |
choices: ['community.general.icinga2'] |
| 32 |
url: |
| 33 |
description: Root URL of Icinga2 API. |
| 34 |
type: string |
| 35 |
required: true |
| 36 |
user: |
| 37 |
description: Username to query the API. |
| 38 |
type: string |
| 39 |
required: true |
| 40 |
password: |
| 41 |
description: Password to query the API. |
| 42 |
type: string |
| 43 |
required: true |
| 44 |
host_filter: |
| 45 |
description: |
| 46 |
- An Icinga2 API valid host filter. Leave blank for no filtering. |
| 47 |
type: string |
| 48 |
required: false |
| 49 |
validate_certs: |
| 50 |
description: Enables or disables SSL certificate verification. |
| 51 |
type: boolean |
| 52 |
default: true |
| 53 |
inventory_attr: |
| 54 |
description: |
| 55 |
- Allows the override of the inventory name based on different attributes. |
| 56 |
- This allows for changing the way limits are used. |
| 57 |
- The current default, V(address), is sometimes not unique or present. We recommend to use V(name) instead. |
| 58 |
type: string |
| 59 |
default: address |
| 60 |
choices: ['name', 'display_name', 'address'] |
| 61 |
version_added: 4.2.0 |
| 62 |
group_by_hostgroups: |
| 63 |
description: |
| 64 |
- Uses Icinga2 hostgroups as groups. |
| 65 |
type: boolean |
| 66 |
default: true |
| 67 |
version_added: 8.4.0 |
| 68 |
""" |
| 69 |
|
| 70 |
EXAMPLES = r""" |
| 71 |
# my.icinga2.yml |
| 72 |
plugin: community.general.icinga2 |
| 73 |
url: http://localhost:5665 |
| 74 |
user: ansible |
| 75 |
password: secure |
| 76 |
host_filter: \"linux-servers\" in host.groups |
| 77 |
validate_certs: false # only do this when connecting to localhost! |
| 78 |
inventory_attr: name |
| 79 |
groups: |
| 80 |
# simple name matching |
| 81 |
webservers: inventory_hostname.startswith('web') |
| 82 |
|
| 83 |
# using icinga2 template |
| 84 |
databaseservers: "'db-template' in (icinga2_attributes.templates|list)" |
| 85 |
|
| 86 |
compose: |
| 87 |
# set all icinga2 attributes to a host variable 'icinga2_attrs' |
| 88 |
icinga2_attrs: icinga2_attributes |
| 89 |
|
| 90 |
# set 'ansible_user' and 'ansible_port' from icinga2 host vars |
| 91 |
ansible_user: icinga2_attributes.vars.ansible_user |
| 92 |
ansible_port: icinga2_attributes.vars.ansible_port | default(22) |
| 93 |
""" |
| 94 |
|
| 95 |
import json |
| 96 |
from http import HTTPStatus |
| 97 |
from urllib.error import HTTPError |
| 98 |
|
| 99 |
from ansible.errors import AnsibleParserError |
| 100 |
from ansible.module_utils.urls import open_url |
| 101 |
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable |
| 102 |
|
| 103 |
from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe |
| 104 |
|
| 105 |
|
| 106 |
class InventoryModule(BaseInventoryPlugin, Constructable): |
| 107 |
"""Host inventory parser for ansible using Icinga2 as source.""" |
| 108 |
|
| 109 |
NAME = "community.general.icinga2" |
| 110 |
|
| 111 |
def __init__(self): |
| 112 |
super().__init__() |
| 113 |
|
| 114 |
# from config |
| 115 |
self.icinga2_url = None |
| 116 |
self.icinga2_user = None |
| 117 |
self.icinga2_password = None |
| 118 |
self.ssl_verify = None |
| 119 |
self.host_filter = None |
| 120 |
self.inventory_attr = None |
| 121 |
self.group_by_hostgroups = None |
| 122 |
|
| 123 |
self.cache_key = None |
| 124 |
self.use_cache = None |
| 125 |
|
| 126 |
def verify_file(self, path): |
| 127 |
valid = False |
| 128 |
if super().verify_file(path): |
| 129 |
if path.endswith(("icinga2.yaml", "icinga2.yml")): |
| 130 |
valid = True |
| 131 |
else: |
| 132 |
self.display.vvv('Skipping due to inventory source not ending in "icinga2.yaml" nor "icinga2.yml"') |
| 133 |
return valid |
| 134 |
|
| 135 |
def _api_connect(self): |
| 136 |
self.headers = { |
| 137 |
"User-Agent": "ansible-icinga2-inv", |
| 138 |
"Accept": "application/json", |
| 139 |
} |
| 140 |
api_status_url = f"{self.icinga2_url}/status" |
| 141 |
request_args = { |
| 142 |
"headers": self.headers, |
| 143 |
"url_username": self.icinga2_user, |
| 144 |
"url_password": self.icinga2_password, |
| 145 |
"validate_certs": self.ssl_verify, |
| 146 |
} |
| 147 |
open_url(api_status_url, **request_args) |
| 148 |
|
| 149 |
def _post_request(self, request_url, data=None): |
| 150 |
self.display.vvv(f"Requested URL: {request_url}") |
| 151 |
request_args = { |
| 152 |
"headers": self.headers, |
| 153 |
"url_username": self.icinga2_user, |
| 154 |
"url_password": self.icinga2_password, |
| 155 |
"validate_certs": self.ssl_verify, |
| 156 |
} |
| 157 |
if data is not None: |
| 158 |
request_args["data"] = json.dumps(data) |
| 159 |
self.display.vvv(f"Request Args: {request_args}") |
| 160 |
try: |
| 161 |
response = open_url(request_url, **request_args) |
| 162 |
except HTTPError as e: |
| 163 |
try: |
| 164 |
error_body = json.loads(e.read().decode()) |
| 165 |
self.display.vvv(f"Error returned: {error_body}") |
| 166 |
except Exception: |
| 167 |
error_body = {"status": None} |
| 168 |
if e.code == HTTPStatus.NOT_FOUND and error_body.get("status") == "No objects found.": |
| 169 |
raise AnsibleParserError( |
| 170 |
"Host filter returned no data. Please confirm your host_filter value is valid" |
| 171 |
) from e |
| 172 |
raise AnsibleParserError(f"Unexpected data returned: {e} -- {error_body}") from e |
| 173 |
|
| 174 |
response_body = response.read() |
| 175 |
json_data = json.loads(response_body.decode("utf-8")) |
| 176 |
self.display.vvv(f"Returned Data: {json.dumps(json_data, indent=4, sort_keys=True)}") |
| 177 |
if HTTPStatus.OK <= response.status < HTTPStatus.MULTIPLE_CHOICES: # 2xx codes |
| 178 |
return json_data |
| 179 |
if response.status == HTTPStatus.NOT_FOUND and json_data["status"] == "No objects found.": |
| 180 |
raise AnsibleParserError(f"API returned no data -- Response: {response.status} - {json_data['status']}") |
| 181 |
if response.status == HTTPStatus.UNAUTHORIZED: |
| 182 |
raise AnsibleParserError( |
| 183 |
f"API was unable to complete query -- Response: {response.status} - {json_data['status']}" |
| 184 |
) |
| 185 |
if response.status == HTTPStatus.INTERNAL_SERVER_ERROR: |
| 186 |
raise AnsibleParserError(f"API Response - {json_data['status']} - {json_data['errors']}") |
| 187 |
raise AnsibleParserError(f"Unexpected data returned - {json_data['status']} - {json_data['errors']}") |
| 188 |
|
| 189 |
def _query_hosts(self, hosts=None, attrs=None, joins=None, host_filter=None): |
| 190 |
query_hosts_url = f"{self.icinga2_url}/objects/hosts" |
| 191 |
self.headers["X-HTTP-Method-Override"] = "GET" |
| 192 |
data_dict = dict() |
| 193 |
if hosts: |
| 194 |
data_dict["hosts"] = hosts |
| 195 |
if attrs is not None: |
| 196 |
data_dict["attrs"] = attrs |
| 197 |
if joins is not None: |
| 198 |
data_dict["joins"] = joins |
| 199 |
if host_filter is not None: |
| 200 |
data_dict["filter"] = host_filter.replace('\\"', '"') |
| 201 |
self.display.vvv(host_filter) |
| 202 |
host_dict = self._post_request(query_hosts_url, data_dict) |
| 203 |
return host_dict["results"] |
| 204 |
|
| 205 |
def get_inventory_from_icinga(self): |
| 206 |
"""Query for all hosts""" |
| 207 |
self.display.vvv("Querying Icinga2 for inventory") |
| 208 |
query_args = { |
| 209 |
"attrs": [ |
| 210 |
"address", |
| 211 |
"address6", |
| 212 |
"name", |
| 213 |
"display_name", |
| 214 |
"state_type", |
| 215 |
"state", |
| 216 |
"templates", |
| 217 |
"groups", |
| 218 |
"vars", |
| 219 |
"zone", |
| 220 |
], |
| 221 |
} |
| 222 |
if self.host_filter is not None: |
| 223 |
query_args["host_filter"] = self.host_filter |
| 224 |
# Icinga2 API Call |
| 225 |
results_json = self._query_hosts(**query_args) |
| 226 |
# Manipulate returned API data to Ansible inventory spec |
| 227 |
ansible_inv = self._convert_inv(results_json) |
| 228 |
return ansible_inv |
| 229 |
|
| 230 |
def _apply_constructable(self, name, variables): |
| 231 |
strict = self.get_option("strict") |
| 232 |
self._add_host_to_composed_groups(self.get_option("groups"), variables, name, strict=strict) |
| 233 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), variables, name, strict=strict) |
| 234 |
self._set_composite_vars(self.get_option("compose"), variables, name, strict=strict) |
| 235 |
|
| 236 |
def _populate(self): |
| 237 |
groups = self._to_json(self.get_inventory_from_icinga()) |
| 238 |
return groups |
| 239 |
|
| 240 |
def _to_json(self, in_dict): |
| 241 |
"""Convert dictionary to JSON""" |
| 242 |
return json.dumps(in_dict, sort_keys=True, indent=2) |
| 243 |
|
| 244 |
def _convert_inv(self, json_data): |
| 245 |
"""Convert Icinga2 API data to JSON format for Ansible""" |
| 246 |
groups_dict = {"_meta": {"hostvars": {}}} |
| 247 |
for entry in json_data: |
| 248 |
host_attrs = make_unsafe(entry["attrs"]) |
| 249 |
if self.inventory_attr == "name": |
| 250 |
host_name = make_unsafe(entry.get("name")) |
| 251 |
if self.inventory_attr == "address": |
| 252 |
# When looking for address for inventory, if missing fallback to object name |
| 253 |
if host_attrs.get("address", "") != "": |
| 254 |
host_name = make_unsafe(host_attrs.get("address")) |
| 255 |
else: |
| 256 |
host_name = make_unsafe(entry.get("name")) |
| 257 |
if self.inventory_attr == "display_name": |
| 258 |
host_name = host_attrs.get("display_name") |
| 259 |
if host_attrs["state"] == 0: |
| 260 |
host_attrs["state"] = "on" |
| 261 |
else: |
| 262 |
host_attrs["state"] = "off" |
| 263 |
self.inventory.add_host(host_name) |
| 264 |
if self.group_by_hostgroups: |
| 265 |
host_groups = host_attrs.get("groups") |
| 266 |
for group in host_groups: |
| 267 |
if group not in self.inventory.groups.keys(): |
| 268 |
self.inventory.add_group(group) |
| 269 |
self.inventory.add_child(group, host_name) |
| 270 |
# If the address attribute is populated, override ansible_host with the value |
| 271 |
if host_attrs.get("address") != "": |
| 272 |
self.inventory.set_variable(host_name, "ansible_host", host_attrs.get("address")) |
| 273 |
self.inventory.set_variable(host_name, "hostname", make_unsafe(entry.get("name"))) |
| 274 |
self.inventory.set_variable(host_name, "display_name", host_attrs.get("display_name")) |
| 275 |
self.inventory.set_variable(host_name, "state", host_attrs["state"]) |
| 276 |
self.inventory.set_variable(host_name, "state_type", host_attrs["state_type"]) |
| 277 |
# Adds all attributes to a variable 'icinga2_attributes' |
| 278 |
construct_vars = dict(self.inventory.get_host(host_name).get_vars()) |
| 279 |
construct_vars["icinga2_attributes"] = host_attrs |
| 280 |
self._apply_constructable(host_name, construct_vars) |
| 281 |
return groups_dict |
| 282 |
|
| 283 |
def parse(self, inventory, loader, path, cache=True): |
| 284 |
super().parse(inventory, loader, path) |
| 285 |
|
| 286 |
# read config from file, this sets 'options' |
| 287 |
self._read_config_data(path) |
| 288 |
|
| 289 |
# Store the options from the YAML file |
| 290 |
self.icinga2_url = self.get_option("url") |
| 291 |
self.icinga2_user = self.get_option("user") |
| 292 |
self.icinga2_password = self.get_option("password") |
| 293 |
self.ssl_verify = self.get_option("validate_certs") |
| 294 |
self.host_filter = self.get_option("host_filter") |
| 295 |
self.inventory_attr = self.get_option("inventory_attr") |
| 296 |
self.group_by_hostgroups = self.get_option("group_by_hostgroups") |
| 297 |
|
| 298 |
if self.templar.is_template(self.icinga2_url): |
| 299 |
self.icinga2_url = self.templar.template(variable=self.icinga2_url) |
| 300 |
if self.templar.is_template(self.icinga2_user): |
| 301 |
self.icinga2_user = self.templar.template(variable=self.icinga2_user) |
| 302 |
if self.templar.is_template(self.icinga2_password): |
| 303 |
self.icinga2_password = self.templar.template(variable=self.icinga2_password) |
| 304 |
|
| 305 |
self.icinga2_url = f"{self.icinga2_url.rstrip('/')}/v1" |
| 306 |
|
| 307 |
# Not currently enabled |
| 308 |
# self.cache_key = self.get_cache_key(path) |
| 309 |
# self.use_cache = cache and self.get_option('cache') |
| 310 |
|
| 311 |
# Test connection to API |
| 312 |
self._api_connect() |
| 313 |
|
| 314 |
# Call our internal helper to populate the dynamic inventory |
| 315 |
self._populate() |