| 1 |
|
| 2 |
> |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
from __future__ import (absolute_import, division, print_function) |
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
DOCUMENTATION = ''' |
| 13 |
name: foreman |
| 14 |
short_description: Foreman inventory source |
| 15 |
requirements: |
| 16 |
- requests >= 1.1 |
| 17 |
description: |
| 18 |
- Get inventory hosts from Foreman. |
| 19 |
- Can use the Reports API (default) or the Hosts API to fetch information about the hosts. |
| 20 |
- The Reports API is faster with many hosts. |
| 21 |
- The Reports API requires the C(foreman_ansible) plugin to be installed on the Foreman server. |
| 22 |
- Some options only work when using the Reports API. |
| 23 |
- Uses a YAML configuration file that ends with ``foreman.(yml|yaml)``. |
| 24 |
extends_documentation_fragment: |
| 25 |
- inventory_cache |
| 26 |
- constructed |
| 27 |
options: |
| 28 |
plugin: |
| 29 |
description: token that ensures this is a source file for the C(foreman) plugin. |
| 30 |
required: true |
| 31 |
choices: ['theforeman.foreman.foreman'] |
| 32 |
url: |
| 33 |
description: |
| 34 |
- URL of the Foreman server. |
| 35 |
required: true |
| 36 |
env: |
| 37 |
- name: FOREMAN_SERVER |
| 38 |
- name: FOREMAN_SERVER_URL |
| 39 |
- name: FOREMAN_URL |
| 40 |
user: |
| 41 |
description: |
| 42 |
- Username accessing the Foreman server. |
| 43 |
required: true |
| 44 |
env: |
| 45 |
- name: FOREMAN_USER |
| 46 |
- name: FOREMAN_USERNAME |
| 47 |
password: |
| 48 |
description: |
| 49 |
- Password of the user accessing the Foreman server. |
| 50 |
required: true |
| 51 |
env: |
| 52 |
- name: FOREMAN_PASSWORD |
| 53 |
validate_certs: |
| 54 |
description: |
| 55 |
- Whether or not to verify the TLS certificates of the Foreman server. |
| 56 |
type: boolean |
| 57 |
default: true |
| 58 |
env: |
| 59 |
- name: FOREMAN_VALIDATE_CERTS |
| 60 |
group_prefix: |
| 61 |
description: prefix to apply to foreman groups |
| 62 |
default: foreman_ |
| 63 |
vars_prefix: |
| 64 |
description: prefix to apply to host variables, does not include facts nor params |
| 65 |
default: foreman_ |
| 66 |
want_facts: |
| 67 |
description: Toggle, if True the plugin will retrieve host facts from the server |
| 68 |
type: boolean |
| 69 |
default: false |
| 70 |
want_params: |
| 71 |
description: Toggle, if true the inventory will retrieve 'all_parameters' information as host vars |
| 72 |
type: boolean |
| 73 |
default: false |
| 74 |
want_hostcollections: |
| 75 |
description: Toggle, if true the plugin will create Ansible groups for host collections |
| 76 |
type: boolean |
| 77 |
default: false |
| 78 |
legacy_hostvars: |
| 79 |
description: |
| 80 |
- Toggle, if true the plugin will build legacy hostvars present in the foreman script |
| 81 |
- Places hostvars in a dictionary with keys `foreman`, `foreman_facts`, and `foreman_params` |
| 82 |
type: boolean |
| 83 |
default: false |
| 84 |
host_filters: |
| 85 |
description: This can be used to restrict the list of returned host |
| 86 |
type: string |
| 87 |
batch_size: |
| 88 |
description: Number of hosts per batch that will be retrieved from the Foreman API per individual call |
| 89 |
type: int |
| 90 |
default: 250 |
| 91 |
use_reports_api: |
| 92 |
description: Use Reports API. |
| 93 |
type: boolean |
| 94 |
default: true |
| 95 |
foreman: |
| 96 |
description: |
| 97 |
- Foreman server related configuration, deprecated. |
| 98 |
- You can pass I(use_reports_api) in this dict to enable the Reports API. |
| 99 |
- Only for backward compatibility. |
| 100 |
report: |
| 101 |
description: |
| 102 |
- Report API specific configuration, deprecated. |
| 103 |
- You can pass the Report API specific params as part of this dict, instead of the main configuration. |
| 104 |
- Only for backward compatibility. |
| 105 |
type: dict |
| 106 |
poll_interval: |
| 107 |
description: The polling interval between 2 calls to the report_data endpoint while polling. |
| 108 |
type: int |
| 109 |
default: 10 |
| 110 |
max_timeout: |
| 111 |
description: Timeout before falling back to old host API when using report_data endpoint while polling. |
| 112 |
type: int |
| 113 |
default: 600 |
| 114 |
want_organization: |
| 115 |
description: |
| 116 |
- Toggle, if true the inventory will fetch organization the host belongs to and create groupings for the same. |
| 117 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 118 |
type: boolean |
| 119 |
default: true |
| 120 |
want_location: |
| 121 |
description: |
| 122 |
- Toggle, if true the inventory will fetch location the host belongs to and create groupings for the same. |
| 123 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 124 |
type: boolean |
| 125 |
default: true |
| 126 |
want_ipv4: |
| 127 |
description: |
| 128 |
- Toggle, if true the inventory will fetch ipv4 address of the host. |
| 129 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 130 |
type: boolean |
| 131 |
default: true |
| 132 |
want_ipv6: |
| 133 |
description: |
| 134 |
- Toggle, if true the inventory will fetch ipv6 address of the host. |
| 135 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 136 |
type: boolean |
| 137 |
default: true |
| 138 |
want_host_group: |
| 139 |
description: |
| 140 |
- Toggle, if true the inventory will fetch host_groups and create groupings for the same. |
| 141 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 142 |
type: boolean |
| 143 |
default: true |
| 144 |
want_subnet: |
| 145 |
description: |
| 146 |
- Toggle, if true the inventory will fetch subnet. |
| 147 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 148 |
type: boolean |
| 149 |
default: true |
| 150 |
want_subnet_v6: |
| 151 |
description: |
| 152 |
- Toggle, if true the inventory will fetch ipv6 subnet. |
| 153 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 154 |
type: boolean |
| 155 |
default: true |
| 156 |
want_smart_proxies: |
| 157 |
description: |
| 158 |
- Toggle, if true the inventory will fetch smart proxy that the host is registered to. |
| 159 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 160 |
type: boolean |
| 161 |
default: true |
| 162 |
want_content_facet_attributes: |
| 163 |
description: |
| 164 |
- Toggle, if true the inventory will fetch content view details that the host is tied to. |
| 165 |
- Only applies to inventories using the Reports API - attribute is ignored otherwise. |
| 166 |
type: boolean |
| 167 |
default: true |
| 168 |
hostnames: |
| 169 |
description: |
| 170 |
- A list of templates in order of precedence to compose inventory_hostname. |
| 171 |
- If the template results in an empty string or None value it is ignored. |
| 172 |
type: list |
| 173 |
elements: str |
| 174 |
default: ['name'] |
| 175 |
''' |
| 176 |
|
| 177 |
EXAMPLES = ''' |
| 178 |
# my.foreman.yml |
| 179 |
plugin: theforeman.foreman.foreman |
| 180 |
url: https://foreman.example.com |
| 181 |
user: ansibleinventory |
| 182 |
password: changeme |
| 183 |
# Only fetch hosts in the Web Engineering organization |
| 184 |
host_filters: 'organization="Web Engineering"' |
| 185 |
# Use short names (not FQDN) for the hosts in the intentory |
| 186 |
hostnames: |
| 187 |
- name.split('.')[0] |
| 188 |
''' |
| 189 |
import copy |
| 190 |
import json |
| 191 |
from ansible_collections.theforeman.foreman.plugins.module_utils._version import LooseVersion |
| 192 |
from collections.abc import MutableMapping |
| 193 |
from time import sleep |
| 194 |
from ansible.errors import AnsibleError |
| 195 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 196 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, to_safe_group_name, Constructable |
| 197 |
|
| 198 |
|
| 199 |
try: |
| 200 |
import requests |
| 201 |
if LooseVersion(requests.__version__) < LooseVersion('1.1.0'): |
| 202 |
raise ImportError |
| 203 |
from requests.auth import HTTPBasicAuth |
| 204 |
HAS_REQUESTS = True |
| 205 |
except ImportError: |
| 206 |
HAS_REQUESTS = False |
| 207 |
|
| 208 |
|
| 209 |
class InventoryModule(BaseInventoryPlugin, Cacheable, Constructable): |
| 210 |
''' Host inventory parser for ansible using foreman as source. ''' |
| 211 |
|
| 212 |
NAME = 'theforeman.foreman.foreman' |
| 213 |
|
| 214 |
def __init__(self): |
| 215 |
|
| 216 |
super(InventoryModule, self).__init__() |
| 217 |
self.MINIMUM_FOREMAN_VERSION_FOR_REPORTS_API = '1.24.0' |
| 218 |
|
| 219 |
self.foreman_url = None |
| 220 |
|
| 221 |
self.session = None |
| 222 |
self.cache_key = None |
| 223 |
self.use_cache = None |
| 224 |
|
| 225 |
if not HAS_REQUESTS: |
| 226 |
raise AnsibleError('This script requires python-requests 1.1 as a minimum version') |
| 227 |
|
| 228 |
def verify_file(self, path): |
| 229 |
|
| 230 |
valid = False |
| 231 |
if super(InventoryModule, self).verify_file(path): |
| 232 |
if path.endswith(('foreman.yaml', 'foreman.yml')): |
| 233 |
valid = True |
| 234 |
else: |
| 235 |
self.display.vvv('Skipping due to inventory source not ending in "foreman.yaml" nor "foreman.yml"') |
| 236 |
return valid |
| 237 |
|
| 238 |
def _get_session(self): |
| 239 |
if not self.session: |
| 240 |
self.session = requests.session() |
| 241 |
self.session.auth = HTTPBasicAuth(self.get_option('user'), to_bytes(self.get_option('password'))) |
| 242 |
self.session.verify = self.get_option('validate_certs') |
| 243 |
return self.session |
| 244 |
|
| 245 |
def _get_json(self, url, ignore_errors=None, params=None): |
| 246 |
|
| 247 |
if not self.use_cache or url not in self._cache.get(self.cache_key, {}): |
| 248 |
|
| 249 |
if self.cache_key not in self._cache: |
| 250 |
self._cache[self.cache_key] = {url: ''} |
| 251 |
|
| 252 |
results = [] |
| 253 |
s = self._get_session() |
| 254 |
if params is None: |
| 255 |
params = {} |
| 256 |
params['page'] = 1 |
| 257 |
params['per_page'] = self.get_option('batch_size') |
| 258 |
while True: |
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
ret = s.get(url, params=params, verify=self.get_option('validate_certs')) |
| 263 |
|
| 264 |
if ignore_errors and ret.status_code in ignore_errors: |
| 265 |
break |
| 266 |
ret.raise_for_status() |
| 267 |
json = ret.json() |
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
if 'results' not in json: |
| 273 |
|
| 274 |
results = json |
| 275 |
break |
| 276 |
elif isinstance(json['results'], MutableMapping): |
| 277 |
|
| 278 |
if not isinstance(results, MutableMapping): |
| 279 |
results = {} |
| 280 |
|
| 281 |
|
| 282 |
if len(json['results']) == 0: |
| 283 |
break |
| 284 |
|
| 285 |
for host, facts in json['results'].items(): |
| 286 |
if host not in results: |
| 287 |
results[host] = {} |
| 288 |
results[host].update(facts) |
| 289 |
|
| 290 |
|
| 291 |
params['page'] += 1 |
| 292 |
else: |
| 293 |
|
| 294 |
results = results + json['results'] |
| 295 |
|
| 296 |
|
| 297 |
if len(results) >= json['subtotal']: |
| 298 |
break |
| 299 |
if len(json['results']) == 0: |
| 300 |
self.display.warning("Did not make any progress during loop. expected %d got %d" % (json['subtotal'], len(results))) |
| 301 |
break |
| 302 |
|
| 303 |
|
| 304 |
params['page'] += 1 |
| 305 |
|
| 306 |
self._cache[self.cache_key][url] = results |
| 307 |
|
| 308 |
return self._cache[self.cache_key][url] |
| 309 |
|
| 310 |
def _get_hosts(self): |
| 311 |
url = "%s/api/v2/hosts" % self.foreman_url |
| 312 |
params = {} |
| 313 |
if self.get_option('host_filters'): |
| 314 |
params['search'] = self.get_option('host_filters') |
| 315 |
return self._get_json(url, params=params) |
| 316 |
|
| 317 |
def _get_all_params_by_id(self, hid): |
| 318 |
url = "%s/api/v2/hosts/%s" % (self.foreman_url, hid) |
| 319 |
ret = self._get_json(url, [404]) |
| 320 |
if not ret or not isinstance(ret, MutableMapping) or not ret.get('all_parameters', False): |
| 321 |
return {} |
| 322 |
return ret.get('all_parameters') |
| 323 |
|
| 324 |
def _get_facts_by_id(self, hid): |
| 325 |
url = "%s/api/v2/hosts/%s/facts" % (self.foreman_url, hid) |
| 326 |
return self._get_json(url) |
| 327 |
|
| 328 |
def _get_host_data_by_id(self, hid): |
| 329 |
url = "%s/api/v2/hosts/%s" % (self.foreman_url, hid) |
| 330 |
return self._get_json(url) |
| 331 |
|
| 332 |
def _get_facts(self, host): |
| 333 |
"""Fetch all host facts of the host""" |
| 334 |
|
| 335 |
ret = self._get_facts_by_id(host['id']) |
| 336 |
if len(ret.values()) == 0: |
| 337 |
facts = {} |
| 338 |
elif len(ret.values()) == 1: |
| 339 |
facts = list(ret.values())[0] |
| 340 |
else: |
| 341 |
raise ValueError("More than one set of facts returned for '%s'" % host) |
| 342 |
return facts |
| 343 |
|
| 344 |
def _get_hostvars(self, host, vars_prefix='', omitted_vars=()): |
| 345 |
hostvars = {} |
| 346 |
for k, v in host.items(): |
| 347 |
if k not in omitted_vars: |
| 348 |
hostvars[vars_prefix + k] = v |
| 349 |
return hostvars |
| 350 |
|
| 351 |
def _fetch_params(self): |
| 352 |
options = ("no", "yes") |
| 353 |
params = dict() |
| 354 |
|
| 355 |
report_options = self.get_option('report') or {} |
| 356 |
|
| 357 |
self.want_location = report_options.get('want_location', self.get_option('want_location')) |
| 358 |
self.want_organization = report_options.get('want_organization', self.get_option('want_organization')) |
| 359 |
self.want_IPv4 = report_options.get('want_ipv4', self.get_option('want_ipv4')) |
| 360 |
self.want_IPv6 = report_options.get('want_ipv6', self.get_option('want_ipv6')) |
| 361 |
self.want_host_group = report_options.get('want_host_group', self.get_option('want_host_group')) |
| 362 |
self.want_hostcollections = report_options.get('want_hostcollections', self.get_option('want_hostcollections')) |
| 363 |
self.want_subnet = report_options.get('want_subnet', self.get_option('want_subnet')) |
| 364 |
self.want_subnet_v6 = report_options.get('want_subnet_v6', self.get_option('want_subnet_v6')) |
| 365 |
self.want_smart_proxies = report_options.get('want_smart_proxies', self.get_option('want_smart_proxies')) |
| 366 |
self.want_content_facet_attributes = report_options.get('want_content_facet_attributes', self.get_option('want_content_facet_attributes')) |
| 367 |
self.want_params = self.get_option('want_params') |
| 368 |
self.want_facts = self.get_option('want_facts') |
| 369 |
self.host_filters = self.get_option('host_filters') |
| 370 |
|
| 371 |
params["Organization"] = options[self.want_organization] |
| 372 |
params["Location"] = options[self.want_location] |
| 373 |
params["IPv4"] = options[self.want_IPv4] |
| 374 |
params["IPv6"] = options[self.want_IPv6] |
| 375 |
params["Facts"] = options[self.want_facts] |
| 376 |
params["Host Group"] = options[self.want_host_group] |
| 377 |
params["Host Collections"] = options[self.want_hostcollections] |
| 378 |
params["Subnet"] = options[self.want_subnet] |
| 379 |
params["Subnet v6"] = options[self.want_subnet_v6] |
| 380 |
params["Smart Proxies"] = options[self.want_smart_proxies] |
| 381 |
params["Content Attributes"] = options[self.want_content_facet_attributes] |
| 382 |
params["Host Parameters"] = options[self.want_params] |
| 383 |
if self.host_filters: |
| 384 |
params["Hosts"] = self.host_filters |
| 385 |
return params |
| 386 |
|
| 387 |
def _use_inventory_report(self): |
| 388 |
use_inventory_report = self.get_option('use_reports_api') |
| 389 |
|
| 390 |
try: |
| 391 |
use_inventory_report = self.get_option('foreman').get('use_reports_api') |
| 392 |
except Exception: |
| 393 |
pass |
| 394 |
if not use_inventory_report: |
| 395 |
return False |
| 396 |
status_url = "%s/api/v2/status" % self.foreman_url |
| 397 |
result = self._get_json(status_url) |
| 398 |
foreman_version = (LooseVersion(result.get('version')) >= LooseVersion(self.MINIMUM_FOREMAN_VERSION_FOR_REPORTS_API)) |
| 399 |
return foreman_version |
| 400 |
|
| 401 |
def _post_request(self): |
| 402 |
url = "%s/ansible/api/v2/ansible_inventories/schedule" % self.foreman_url |
| 403 |
params = {'input_values': self._fetch_params()} |
| 404 |
|
| 405 |
if self.use_cache and url in self._cache.get(self.cache_key, {}): |
| 406 |
return self._cache[self.cache_key][url] |
| 407 |
|
| 408 |
if self.cache_key not in self._cache: |
| 409 |
self._cache[self.cache_key] = {} |
| 410 |
|
| 411 |
session = self._get_session() |
| 412 |
self.poll_interval = self.get_option('poll_interval') |
| 413 |
self.max_timeout = self.get_option('max_timeout') |
| 414 |
|
| 415 |
try: |
| 416 |
self.poll_interval = int(self.get_option('report').get('poll_interval')) |
| 417 |
self.max_timeout = int(self.get_option('report').get('max_timeout')) |
| 418 |
except Exception: |
| 419 |
pass |
| 420 |
max_polls = self.max_timeout / self.poll_interval |
| 421 |
ret = session.post(url, json=params) |
| 422 |
if not ret: |
| 423 |
raise Exception("Error scheduling inventory report on foreman. Please check foreman logs!") |
| 424 |
data_url = "{0}/{1}".format(self.foreman_url, ret.json().get('data_url')) |
| 425 |
polls = 0 |
| 426 |
response = session.get(data_url) |
| 427 |
while response: |
| 428 |
if response.status_code != 204 or polls > max_polls: |
| 429 |
break |
| 430 |
sleep(self.poll_interval) |
| 431 |
polls += 1 |
| 432 |
response = session.get(data_url) |
| 433 |
if not response: |
| 434 |
raise Exception("Error receiving inventory report from foreman. Please check foreman logs!") |
| 435 |
elif (response.status_code == 204 and polls > max_polls): |
| 436 |
raise Exception("Timeout receiving inventory report from foreman. Check foreman server and max_timeout in foreman.yml") |
| 437 |
else: |
| 438 |
self._cache[self.cache_key][url] = json.loads(response.json()) |
| 439 |
return self._cache[self.cache_key][url] |
| 440 |
|
| 441 |
def _populate(self): |
| 442 |
if self._use_inventory_report(): |
| 443 |
self._populate_report_api() |
| 444 |
else: |
| 445 |
self._populate_host_api() |
| 446 |
|
| 447 |
def _get_hostname(self, properties, hostnames, strict=False): |
| 448 |
hostname = None |
| 449 |
errors = [] |
| 450 |
|
| 451 |
for preference in hostnames: |
| 452 |
try: |
| 453 |
hostname = self._compose(preference, properties) |
| 454 |
except Exception as e: |
| 455 |
if strict: |
| 456 |
raise AnsibleError("Could not compose %s as hostnames - %s" % (preference, to_native(e))) |
| 457 |
else: |
| 458 |
errors.append( |
| 459 |
(preference, str(e)) |
| 460 |
) |
| 461 |
if hostname: |
| 462 |
return to_text(hostname) |
| 463 |
|
| 464 |
raise AnsibleError( |
| 465 |
'Could not template any hostname for host, errors for each preference: %s' % ( |
| 466 |
', '.join(['%s: %s' % (pref, err) for pref, err in errors]) |
| 467 |
) |
| 468 |
) |
| 469 |
|
| 470 |
def _populate_report_api(self): |
| 471 |
self.groups = dict() |
| 472 |
self.hosts = dict() |
| 473 |
|
| 474 |
|
| 475 |
host_data = copy.deepcopy(self._post_request()) |
| 476 |
|
| 477 |
self.group_prefix = self.get_option('group_prefix') |
| 478 |
|
| 479 |
hostnames = self.get_option('hostnames') |
| 480 |
strict = self.get_option('strict') |
| 481 |
|
| 482 |
for host in host_data: |
| 483 |
if not host: |
| 484 |
continue |
| 485 |
|
| 486 |
composed_host_name = self._get_hostname(host, hostnames, strict=strict) |
| 487 |
|
| 488 |
if (composed_host_name in self._cache.keys()): |
| 489 |
continue |
| 490 |
|
| 491 |
host_name = self.inventory.add_host(composed_host_name) |
| 492 |
|
| 493 |
group_name = host.get('hostgroup_title', host.get('hostgroup_name')) |
| 494 |
if group_name: |
| 495 |
group_name = to_safe_group_name('%s%s' % (self.get_option('group_prefix'), group_name.lower().replace(" ", ""))) |
| 496 |
group_name = self.inventory.add_group(group_name) |
| 497 |
self.inventory.add_child(group_name, host_name) |
| 498 |
|
| 499 |
host_params = host.pop('host_parameters', {}) |
| 500 |
fact_list = host.pop('facts', {}) |
| 501 |
|
| 502 |
if self.get_option('legacy_hostvars'): |
| 503 |
hostvars = self._get_hostvars(host) |
| 504 |
self.inventory.set_variable(host_name, 'foreman', hostvars) |
| 505 |
else: |
| 506 |
omitted_vars = ('name', 'hostgroup_title', 'hostgroup_name') |
| 507 |
hostvars = self._get_hostvars(host, self.get_option('vars_prefix'), omitted_vars) |
| 508 |
|
| 509 |
for k, v in hostvars.items(): |
| 510 |
try: |
| 511 |
self.inventory.set_variable(host_name, k, v) |
| 512 |
except ValueError as e: |
| 513 |
self.display.warning("Could not set host info hostvar for %s, skipping %s: %s" % (host, k, to_text(e))) |
| 514 |
|
| 515 |
content_facet_attributes = host.get('content_attributes', {}) or {} |
| 516 |
if self.get_option('want_facts'): |
| 517 |
self.inventory.set_variable(host_name, 'foreman_facts', fact_list) |
| 518 |
|
| 519 |
|
| 520 |
group = 'host_group' |
| 521 |
group_name = host.get(group) |
| 522 |
if group_name: |
| 523 |
parent_name = None |
| 524 |
group_label_parts = [] |
| 525 |
for part in group_name.split('/'): |
| 526 |
group_label_parts.append(part.lower().replace(" ", "")) |
| 527 |
gname = to_safe_group_name('%s%s' % (self.get_option('group_prefix'), '/'.join(group_label_parts))) |
| 528 |
result_gname = self.inventory.add_group(gname) |
| 529 |
if parent_name: |
| 530 |
self.inventory.add_child(parent_name, result_gname) |
| 531 |
parent_name = result_gname |
| 532 |
self.inventory.add_child(result_gname, host_name) |
| 533 |
|
| 534 |
|
| 535 |
for group in ['environment', 'location', 'organization']: |
| 536 |
val = host.get('%s' % group) |
| 537 |
if val: |
| 538 |
safe_key = to_safe_group_name('%s%s_%s' % ( |
| 539 |
to_text(self.group_prefix), |
| 540 |
group, |
| 541 |
to_text(val).lower() |
| 542 |
)) |
| 543 |
env_lo_org = self.inventory.add_group(safe_key) |
| 544 |
self.inventory.add_child(env_lo_org, host_name) |
| 545 |
|
| 546 |
for group in ['lifecycle_environment', 'content_view']: |
| 547 |
val = content_facet_attributes.get('%s_name' % group) |
| 548 |
if val: |
| 549 |
safe_key = to_safe_group_name('%s%s_%s' % ( |
| 550 |
to_text(self.group_prefix), |
| 551 |
group, |
| 552 |
to_text(val).lower() |
| 553 |
)) |
| 554 |
le_cv_group = self.inventory.add_group(safe_key) |
| 555 |
self.inventory.add_child(le_cv_group, host_name) |
| 556 |
params = host_params |
| 557 |
|
| 558 |
if self.want_hostcollections: |
| 559 |
hostcollections = host.get('host_collections') |
| 560 |
|
| 561 |
if hostcollections: |
| 562 |
|
| 563 |
for hostcollection in hostcollections: |
| 564 |
try: |
| 565 |
host_collection_group_name = to_safe_group_name('%shostcollection_%s' % ( |
| 566 |
to_text(self.group_prefix), |
| 567 |
to_text(hostcollection).lower() |
| 568 |
)) |
| 569 |
hostcollection_group = self.inventory.add_group(host_collection_group_name) |
| 570 |
self.inventory.add_child(hostcollection_group, host_name) |
| 571 |
except ValueError as e: |
| 572 |
self.display.warning("Could not create groups for host collections for %s, skipping: %s" % (host_name, to_text(e))) |
| 573 |
|
| 574 |
|
| 575 |
if self.get_option('want_params'): |
| 576 |
if self.get_option('legacy_hostvars'): |
| 577 |
self.inventory.set_variable(host_name, 'foreman_params', params) |
| 578 |
else: |
| 579 |
for k, v in params.items(): |
| 580 |
try: |
| 581 |
self.inventory.set_variable(host_name, k, v) |
| 582 |
except ValueError as e: |
| 583 |
self.display.warning("Could not set hostvar %s to '%s' for the '%s' host, skipping: %s" % |
| 584 |
(k, to_native(v), host, to_native(e))) |
| 585 |
hostvars = self.inventory.get_host(host_name).get_vars() |
| 586 |
self._set_composite_vars(self.get_option('compose'), hostvars, host_name, strict) |
| 587 |
self._add_host_to_composed_groups(self.get_option('groups'), hostvars, host_name, strict) |
| 588 |
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), hostvars, host_name, strict) |
| 589 |
|
| 590 |
def _populate_host_api(self): |
| 591 |
hostnames = self.get_option('hostnames') |
| 592 |
strict = self.get_option('strict') |
| 593 |
for host in self._get_hosts(): |
| 594 |
if not host: |
| 595 |
continue |
| 596 |
|
| 597 |
composed_host_name = self._get_hostname(host, hostnames, strict=strict) |
| 598 |
|
| 599 |
if (composed_host_name in self._cache.keys()): |
| 600 |
continue |
| 601 |
|
| 602 |
host_name = self.inventory.add_host(composed_host_name) |
| 603 |
|
| 604 |
|
| 605 |
group_name = host.get('hostgroup_title', host.get('hostgroup_name')) |
| 606 |
if group_name: |
| 607 |
parent_name = None |
| 608 |
group_label_parts = [] |
| 609 |
for part in group_name.split('/'): |
| 610 |
group_label_parts.append(part.lower().replace(" ", "")) |
| 611 |
gname = to_safe_group_name('%s%s' % (self.get_option('group_prefix'), '/'.join(group_label_parts))) |
| 612 |
result_gname = self.inventory.add_group(gname) |
| 613 |
if parent_name: |
| 614 |
self.inventory.add_child(parent_name, result_gname) |
| 615 |
parent_name = result_gname |
| 616 |
self.inventory.add_child(result_gname, host_name) |
| 617 |
|
| 618 |
if self.get_option('legacy_hostvars'): |
| 619 |
hostvars = self._get_hostvars(host) |
| 620 |
self.inventory.set_variable(host_name, 'foreman', hostvars) |
| 621 |
else: |
| 622 |
omitted_vars = ('name', 'hostgroup_title', 'hostgroup_name') |
| 623 |
hostvars = self._get_hostvars(host, self.get_option('vars_prefix'), omitted_vars) |
| 624 |
|
| 625 |
for k, v in hostvars.items(): |
| 626 |
try: |
| 627 |
self.inventory.set_variable(host_name, k, v) |
| 628 |
except ValueError as e: |
| 629 |
self.display.warning("Could not set host info hostvar for %s, skipping %s: %s" % (host, k, to_text(e))) |
| 630 |
|
| 631 |
|
| 632 |
if self.get_option('want_params'): |
| 633 |
params = self._get_all_params_by_id(host['id']) |
| 634 |
filtered_params = {} |
| 635 |
for p in params: |
| 636 |
if 'name' in p and 'value' in p: |
| 637 |
filtered_params[p['name']] = p['value'] |
| 638 |
|
| 639 |
if self.get_option('legacy_hostvars'): |
| 640 |
self.inventory.set_variable(host_name, 'foreman_params', filtered_params) |
| 641 |
else: |
| 642 |
for k, v in filtered_params.items(): |
| 643 |
try: |
| 644 |
self.inventory.set_variable(host_name, k, v) |
| 645 |
except ValueError as e: |
| 646 |
self.display.warning("Could not set hostvar %s to '%s' for the '%s' host, skipping: %s" % |
| 647 |
(k, to_native(v), host, to_native(e))) |
| 648 |
|
| 649 |
|
| 650 |
if self.get_option('want_facts'): |
| 651 |
self.inventory.set_variable(host_name, 'foreman_facts', self._get_facts(host)) |
| 652 |
|
| 653 |
|
| 654 |
if self.get_option('want_hostcollections'): |
| 655 |
host_data = self._get_host_data_by_id(host['id']) |
| 656 |
hostcollections = host_data.get('host_collections') |
| 657 |
if hostcollections: |
| 658 |
|
| 659 |
for hostcollection in hostcollections: |
| 660 |
try: |
| 661 |
hostcollection_group = to_safe_group_name('%shostcollection_%s' % (self.get_option('group_prefix'), |
| 662 |
hostcollection['name'].lower().replace(" ", ""))) |
| 663 |
hostcollection_group = self.inventory.add_group(hostcollection_group) |
| 664 |
self.inventory.add_child(hostcollection_group, host_name) |
| 665 |
except ValueError as e: |
| 666 |
self.display.warning("Could not create groups for host collections for %s, skipping: %s" % (host_name, to_text(e))) |
| 667 |
|
| 668 |
hostvars = self.inventory.get_host(host_name).get_vars() |
| 669 |
self._set_composite_vars(self.get_option('compose'), hostvars, host_name, strict) |
| 670 |
self._add_host_to_composed_groups(self.get_option('groups'), hostvars, host_name, strict) |
| 671 |
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), hostvars, host_name, strict) |
| 672 |
|
| 673 |
def parse(self, inventory, loader, path, cache=True): |
| 674 |
|
| 675 |
super(InventoryModule, self).parse(inventory, loader, path) |
| 676 |
|
| 677 |
self.load_cache_plugin() |
| 678 |
|
| 679 |
|
| 680 |
self._read_config_data(path) |
| 681 |
|
| 682 |
|
| 683 |
self.foreman_url = self.get_option('url') |
| 684 |
self.cache_key = self.get_cache_key(path) |
| 685 |
self.use_cache = cache and self.get_option('cache') |
| 686 |
|
| 687 |
|
| 688 |
self._populate() |