| 1 |
# Copyright: (c) 2023, Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
DOCUMENTATION = r""" |
| 5 |
name: ldap |
| 6 |
author: Jordan Borean (@jborean93) |
| 7 |
short_description: Inventory plugin for Active Directory |
| 8 |
version_added: 1.1.0 |
| 9 |
description: |
| 10 |
- Inventory plugin for Active Directory or other LDAP sources. |
| 11 |
- Uses a YAML configuration file that ends with C(microsoft.ad.ldap.{yml|yaml}). |
| 12 |
- Each host that is added will set the C(inventory_hostname) to the C(name) of |
| 13 |
the LDAP computer object and C(ansible_host) to the value of the |
| 14 |
C(dNSHostName) LDAP attribute if set. If the C(dNSHostName) attribute is not |
| 15 |
set on the computer object then C(ansible_host) is not set. See |
| 16 |
R(LDAP inventory hostname,ansible_collections.microsoft.ad.docsite.guide_ldap_inventory.inventory_hostname) |
| 17 |
for more information on how these values are set and how to adjust them. |
| 18 |
- The host fact C(microsoft_ad_distinguished_name) will also be set to the |
| 19 |
distinguished name of the host that was used to derive the host entry. |
| 20 |
- Any other fact that is needed, needs to be defined in the I(attributes) |
| 21 |
option. |
| 22 |
options: |
| 23 |
attributes: |
| 24 |
description: |
| 25 |
- The LDAP attributes to retrieve. |
| 26 |
- The keys specified are the LDAP attributes requested and the values for |
| 27 |
each attribute is a dictionary that reflects what host var to set it to |
| 28 |
and how. |
| 29 |
- Each key of the inner dictionary value is the host variable name to set |
| 30 |
and the value is the template to use to derive the value. If no value is |
| 31 |
explicitly set then it will use the coerced value as returned from the |
| 32 |
LDAP attribute. |
| 33 |
- Attributes that are denoted as single value in the LDAP schema are |
| 34 |
returned as that single value, multi valued attributes are returned as a |
| 35 |
list of values. |
| 36 |
- See R(LDAP inventory attributes,ansible_collections.microsoft.ad.docsite.guide_ldap_inventory.attributes) |
| 37 |
for more information. |
| 38 |
default: {} |
| 39 |
type: dict |
| 40 |
filter: |
| 41 |
description: |
| 42 |
- The LDAP filter string used to query the computer objects. |
| 43 |
- By default, this will be combined with the filter |
| 44 |
"(objectCategory=computer)". Use I(filter_without_computer) to override |
| 45 |
this behavior and have I(filter) be the only filter used. |
| 46 |
type: str |
| 47 |
filter_without_computer: |
| 48 |
description: |
| 49 |
- Will not combine the I(filter) value with the default filter |
| 50 |
"(objectCategory=computer)". |
| 51 |
- In most cases this should be C(false) but can be set to C(true) to have |
| 52 |
the I(filter) value specified be the only filter used. |
| 53 |
type: bool |
| 54 |
default: false |
| 55 |
version_added: '1.3.0' |
| 56 |
search_base: |
| 57 |
description: |
| 58 |
- The LDAP search base to find the computer objects in. |
| 59 |
- Defaults to the C(defaultNamingContext) of the Active Directory server |
| 60 |
if not specified. |
| 61 |
- If searching a larger Active Directory database, it is recommended to |
| 62 |
narrow the search base to speed up the queries. |
| 63 |
type: str |
| 64 |
search_scope: |
| 65 |
description: |
| 66 |
- The scope of the LDAP search to perform. |
| 67 |
- C(base) will search only the current path or object specified by |
| 68 |
I(search_base). This is typically not useful for inventory plugins. |
| 69 |
- C(one_level) will search only the immediate child objects in |
| 70 |
I(search_base). |
| 71 |
- C(subtree) will search the immediate child objects and any nested |
| 72 |
objects in I(search_base). |
| 73 |
choices: |
| 74 |
- base |
| 75 |
- one_level |
| 76 |
- subtree |
| 77 |
default: subtree |
| 78 |
type: str |
| 79 |
notes: |
| 80 |
- See R(LDAP inventory,ansible_collections.microsoft.ad.docsite.guide_ldap_inventory) |
| 81 |
for more details on how to use this inventory plugin. |
| 82 |
- See R(LAPS,ansible_collections.microsoft.ad.docsite.guide_ldap_inventory.laps) |
| 83 |
for more details on how this plugin can retrieve the LAPS password |
| 84 |
information. |
| 85 |
- This plugin is a tech preview and the module options are subject to change |
| 86 |
based on feedback received. |
| 87 |
- Unless specified otherwise in the option description, the value specified in |
| 88 |
the config file is used as is. Only the LDAP connection options allow using |
| 89 |
a Jinja2 template. |
| 90 |
extends_documentation_fragment: |
| 91 |
- constructed |
| 92 |
- microsoft.ad.ldap_connection |
| 93 |
""" |
| 94 |
|
| 95 |
EXAMPLES = r""" |
| 96 |
# Set in the file ending with microsoft.ad.ldap.yml or microsoft.ad.ldap.yaml |
| 97 |
plugin: microsoft.ad.ldap |
| 98 |
|
| 99 |
|
| 100 |
#################################################################### |
| 101 |
# Connection Options # |
| 102 |
# # |
| 103 |
# These options control how the plugin connects to the LDAP server # |
| 104 |
#################################################################### |
| 105 |
|
| 106 |
# Connects to ldap://dc01.domain.com:389 |
| 107 |
server: dc01.domain.com |
| 108 |
port: 389 |
| 109 |
|
| 110 |
# Connects to ldaps://dc01.domain.com:636 |
| 111 |
server: dc01.domain.com |
| 112 |
tls_mode: ldaps |
| 113 |
|
| 114 |
# Connects to the global catalog |
| 115 |
# ldap://dc01.domain.com:3268 |
| 116 |
server: dc01.domain.com |
| 117 |
port: 3268 |
| 118 |
|
| 119 |
# Provides explicit user, will use the current Kerberos ticket if no credential |
| 120 |
# is provided. |
| 121 |
username: [email protected] |
| 122 |
password: Password123! |
| 123 |
|
| 124 |
# Only allow Kerberos authentication. |
| 125 |
auth_protocol: kerberos |
| 126 |
|
| 127 |
# Verify LDAPS CA chain with custom CA chain. |
| 128 |
tls_mode: ldaps |
| 129 |
ca_cert: /home/user/certs/ldap.pem |
| 130 |
|
| 131 |
# The username and password can be retrieved using a template with a lookup. |
| 132 |
# Other connection options can also be set this way, the option description |
| 133 |
# tells you whether it can be set to a template. |
| 134 |
username: '{{ lookup("ansible.builtin.env", "LDAP_USERNAME") }}' |
| 135 |
password: '{{ lookup("ansible.builtin.env", "LDAP_PASSWORD") }}' |
| 136 |
|
| 137 |
|
| 138 |
############################################## |
| 139 |
# Search Options # |
| 140 |
# # |
| 141 |
# These options control the searching rules # |
| 142 |
############################################## |
| 143 |
|
| 144 |
# Search for computer accounts in the Workshop OU. |
| 145 |
search_base: OU=Workshop A,DC=domain,DC=com |
| 146 |
|
| 147 |
# Filter the computer accounts returned for only ones with the dNSDomainName |
| 148 |
# attribute set. |
| 149 |
filter: (dNSDomainName=*) |
| 150 |
|
| 151 |
# Filter computer accounts returned for ones starting with PROD and with the |
| 152 |
# LAPS password set. |
| 153 |
filter: (&(sAMAccountName=PROD*)(ms-Mcs-AdmPwd=*)) |
| 154 |
|
| 155 |
# See documentation for more details |
| 156 |
attributes: |
| 157 |
sAMAccountName: |
| 158 |
sam_account_name: |
| 159 |
objectSid: |
| 160 |
computer_sid: |
| 161 |
pwdLastSet: |
| 162 |
password_last_set: this | microsoft.ad.as_datetime |
| 163 |
comment: |
| 164 |
host_comment |
| 165 |
memberOf: |
| 166 |
# Gets the value (1) of the first RDN (0) of each memberOf instance (this). |
| 167 |
# For example 'CN=Domain Admins,CN=Users,DC=domain,DC=test' |
| 168 |
# will be returned as just 'Domain Admins' |
| 169 |
computer_membership: this | microsoft.ad.parse_dn | map(attribute="0.1") |
| 170 |
location: |
| 171 |
|
| 172 |
|
| 173 |
############################################################################ |
| 174 |
# LAPS Integration # |
| 175 |
# # |
| 176 |
# Examples on how to use the new Windows LAPS values as connection options # |
| 177 |
############################################################################ |
| 178 |
|
| 179 |
attributes: |
| 180 |
# msLAPS-Password is used if no encryption has been configured. |
| 181 |
# Currently an encrypted LAPS password is not supported. |
| 182 |
msLAPS-Password: |
| 183 |
ansible_user: (this | from_json).n |
| 184 |
ansible_password: (this | from_json).p |
| 185 |
|
| 186 |
# msLAPS-EncryptedPassword is used if encryption has been configured. |
| 187 |
# If the Python dpapi-ng library is installed the `this`` value will |
| 188 |
# contain the entry `value` which is the decrypted value. The ``info`` |
| 189 |
# entry will contain the reason why the value could not be decrypted. |
| 190 |
msLAPS-EncryptedPassword: |
| 191 |
ansible_user: (this.value | from_json).n |
| 192 |
ansible_password: (this.value | from_json).p |
| 193 |
|
| 194 |
# ms-Mcs-AdmPwd is used for Legacy LAPS and stores just the password. |
| 195 |
# The username needs to be hardcoded as a string value for this template. |
| 196 |
ms-Mcs-AdmPwd: |
| 197 |
ansible_user: '"Administrator"' |
| 198 |
ansible_password: this |
| 199 |
|
| 200 |
|
| 201 |
##################################################################### |
| 202 |
# Constructed Options # |
| 203 |
# # |
| 204 |
# These options control the constructed values like vars and groups # |
| 205 |
##################################################################### |
| 206 |
|
| 207 |
# Build composed host variables. Requires attributes to be set in the |
| 208 |
# attributes option to be referenced here. |
| 209 |
compose: |
| 210 |
host_var: computer_sid |
| 211 |
|
| 212 |
# Conditionals that adds found hosts to the groups specified. |
| 213 |
groups: |
| 214 |
# Adds all hosts to the windows group |
| 215 |
windows: true |
| 216 |
|
| 217 |
# Uses the memberOf fact documented above to place the host in the production |
| 218 |
# group if it's a member of that group |
| 219 |
production: '"Production Group" in computer_membership' |
| 220 |
|
| 221 |
# Adds the host to a group site_{{ location }} with the default group of |
| 222 |
# site_unknown if the location isn't defined |
| 223 |
keyed_groups: |
| 224 |
- key: location | default(omit) |
| 225 |
prefix: site |
| 226 |
default_value: unknown |
| 227 |
""" |
| 228 |
|
| 229 |
import base64 |
| 230 |
import typing as t |
| 231 |
|
| 232 |
from ansible.errors import AnsibleError |
| 233 |
from ansible.inventory.data import InventoryData |
| 234 |
from ansible.module_utils.basic import missing_required_lib |
| 235 |
from ansible.parsing.dataloader import DataLoader |
| 236 |
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable |
| 237 |
from ansible.utils.unsafe_proxy import wrap_var |
| 238 |
|
| 239 |
USE_DATA_TAGGING = False |
| 240 |
try: |
| 241 |
from ansible.template import trust_as_template |
| 242 |
|
| 243 |
USE_DATA_TAGGING = True |
| 244 |
except ImportError: |
| 245 |
pass |
| 246 |
|
| 247 |
|
| 248 |
try: |
| 249 |
import sansldap |
| 250 |
|
| 251 |
from ..plugin_utils._ldap import create_ldap_connection |
| 252 |
from ..plugin_utils._ldap.schema import LDAPSchema |
| 253 |
from ..plugin_utils._ldap.laps import LAPSDecryptor |
| 254 |
|
| 255 |
HAS_LDAP = True |
| 256 |
LDAP_IMP_ERR = None |
| 257 |
except Exception as e: |
| 258 |
HAS_LDAP = False |
| 259 |
LDAP_IMP_ERR = e |
| 260 |
|
| 261 |
|
| 262 |
class InventoryModule(BaseInventoryPlugin, Constructable): |
| 263 |
NAME = "microsoft.ad.ldap" |
| 264 |
|
| 265 |
def verify_file(self, path: str) -> bool: |
| 266 |
if super().verify_file(path): |
| 267 |
return path.endswith(("microsoft.ad.ldap.yml", "microsoft.ad.ldap.yaml")) |
| 268 |
|
| 269 |
return False |
| 270 |
|
| 271 |
def parse( |
| 272 |
self, |
| 273 |
inventory: InventoryData, |
| 274 |
loader: DataLoader, |
| 275 |
path: str, |
| 276 |
cache: bool, |
| 277 |
) -> None: |
| 278 |
super().parse(inventory, loader, path, cache) |
| 279 |
self.set_options() |
| 280 |
self._read_config_data(path) |
| 281 |
|
| 282 |
if not HAS_LDAP: |
| 283 |
msg = missing_required_lib( |
| 284 |
"sansldap and pyspnego", |
| 285 |
url="https://pypi.org/project/sansldap/ and https://pypi.org/project/pyspnego/", |
| 286 |
reason="for ldap lookups", |
| 287 |
) |
| 288 |
raise AnsibleError(f"{msg}: {LDAP_IMP_ERR}") from LDAP_IMP_ERR |
| 289 |
|
| 290 |
compose = self.get_option("compose") |
| 291 |
groups = self.get_option("groups") |
| 292 |
keyed_groups = self.get_option("keyed_groups") |
| 293 |
ldap_filter = self.get_option("filter") |
| 294 |
ldap_filter_without_computer = self.get_option("filter_without_computer") |
| 295 |
search_base = self.get_option("search_base") |
| 296 |
search_scope = self.get_option("search_scope") |
| 297 |
strict = self.get_option("strict") |
| 298 |
|
| 299 |
ldap_search_scope = { |
| 300 |
"base": sansldap.SearchScope.BASE, |
| 301 |
"one_level": sansldap.SearchScope.ONE_LEVEL, |
| 302 |
"subtree": sansldap.SearchScope.SUBTREE, |
| 303 |
}[search_scope] |
| 304 |
|
| 305 |
computer_filter = sansldap.FilterEquality("objectCategory", b"computer") |
| 306 |
final_filter: sansldap.LDAPFilter |
| 307 |
if ldap_filter: |
| 308 |
ldap_filter_obj = sansldap.LDAPFilter.from_string(ldap_filter) |
| 309 |
|
| 310 |
if ldap_filter_without_computer: |
| 311 |
final_filter = ldap_filter_obj |
| 312 |
else: |
| 313 |
final_filter = sansldap.FilterAnd( |
| 314 |
filters=[computer_filter, ldap_filter_obj] |
| 315 |
) |
| 316 |
else: |
| 317 |
final_filter = computer_filter |
| 318 |
|
| 319 |
custom_attributes = self._get_custom_attributes() |
| 320 |
attributes = {"name", "dnshostname"}.union( |
| 321 |
[a.lower() for a in custom_attributes.keys()] |
| 322 |
) |
| 323 |
|
| 324 |
# If inventory_hostname was defined in compose, set it in the custom |
| 325 |
# attributes so we can set the hostname before processing the rest of |
| 326 |
# compose entries. |
| 327 |
inventory_hostname = compose.pop("inventory_hostname", None) |
| 328 |
if inventory_hostname: |
| 329 |
custom_attributes["inventory_hostname"] = { |
| 330 |
"inventory_hostname": inventory_hostname |
| 331 |
} |
| 332 |
connection_options = self.get_options() |
| 333 |
|
| 334 |
# These options are in ../doc_fragments/ldap_connection.py |
| 335 |
template_fields = { |
| 336 |
"auth_protocol", |
| 337 |
"ca_cert", |
| 338 |
"cert_validation", |
| 339 |
"certificate", |
| 340 |
"certificate_key", |
| 341 |
"certificate_password", |
| 342 |
"connection_timeout", |
| 343 |
"encrypt", |
| 344 |
"password", |
| 345 |
"port", |
| 346 |
"server", |
| 347 |
"tls_mode", |
| 348 |
"username", |
| 349 |
} |
| 350 |
templated_option_kwargs = {} |
| 351 |
if not USE_DATA_TAGGING: |
| 352 |
templated_option_kwargs['disable_lookups'] = False |
| 353 |
|
| 354 |
for option_name, option_value in connection_options.items(): |
| 355 |
if option_name in template_fields and self.templar.is_template( |
| 356 |
option_value |
| 357 |
): |
| 358 |
self.display.vvv(f"Templating option {option_name}") |
| 359 |
connection_options[option_name] = self.templar.template( |
| 360 |
variable=option_value, |
| 361 |
**templated_option_kwargs, |
| 362 |
) |
| 363 |
|
| 364 |
laps_decryptor = LAPSDecryptor(**connection_options) |
| 365 |
with create_ldap_connection(**connection_options) as client: |
| 366 |
schema = LDAPSchema.load_schema(client) |
| 367 |
|
| 368 |
for dn, info in client.search( |
| 369 |
filter=final_filter, |
| 370 |
attributes=list(attributes), |
| 371 |
search_base=search_base, |
| 372 |
search_scope=ldap_search_scope, |
| 373 |
).items(): |
| 374 |
insensitive_info = {k.lower(): v for k, v in info.items()} |
| 375 |
|
| 376 |
host_name = insensitive_info["name"][0].decode("utf-8") |
| 377 |
host_vars: t.Dict[str, t.Any] = { |
| 378 |
"microsoft_ad_distinguished_name": dn, |
| 379 |
} |
| 380 |
|
| 381 |
dns_host_name = insensitive_info.get("dnshostname", None) |
| 382 |
if dns_host_name: |
| 383 |
host_vars["ansible_host"] = dns_host_name[0].decode("utf-8") |
| 384 |
|
| 385 |
for name, var_info in custom_attributes.items(): |
| 386 |
raw_values = insensitive_info.get(name.lower(), []) |
| 387 |
values = schema.cast_object(name, raw_values) |
| 388 |
|
| 389 |
host_vars["raw"] = wrap_var( |
| 390 |
[base64.b64encode(r).decode() for r in raw_values] |
| 391 |
) |
| 392 |
|
| 393 |
if name.lower() == "mslaps-encryptedpassword" and raw_values: |
| 394 |
host_vars["this"] = wrap_var(laps_decryptor.decrypt(raw_values[0])) |
| 395 |
else: |
| 396 |
host_vars["this"] = wrap_var(values) |
| 397 |
|
| 398 |
for n, v in var_info.items(): |
| 399 |
if USE_DATA_TAGGING: |
| 400 |
v = trust_as_template(v) |
| 401 |
|
| 402 |
try: |
| 403 |
composite = self._compose(v, host_vars) |
| 404 |
except Exception as e: |
| 405 |
if strict: |
| 406 |
raise AnsibleError( |
| 407 |
f"Could not set {n} for host {host_name}: {e}" |
| 408 |
) from e |
| 409 |
continue |
| 410 |
|
| 411 |
host_vars[n] = composite |
| 412 |
|
| 413 |
host_vars.pop("raw") |
| 414 |
host_vars.pop("this") |
| 415 |
|
| 416 |
actual_host_name = host_vars.get("inventory_hostname", host_name) |
| 417 |
inventory.add_host(actual_host_name) |
| 418 |
for n, v in host_vars.items(): |
| 419 |
if n == "inventory_hostname": |
| 420 |
continue |
| 421 |
inventory.set_variable(actual_host_name, n, v) |
| 422 |
|
| 423 |
self._set_composite_vars( |
| 424 |
compose, host_vars, actual_host_name, strict=strict |
| 425 |
) |
| 426 |
self._add_host_to_composed_groups( |
| 427 |
groups, host_vars, actual_host_name, strict=strict |
| 428 |
) |
| 429 |
self._add_host_to_keyed_groups( |
| 430 |
keyed_groups, host_vars, actual_host_name, strict=strict |
| 431 |
) |
| 432 |
|
| 433 |
def _get_custom_attributes(self) -> t.Dict[str, t.Dict[str, str]]: |
| 434 |
custom_attributes = self.get_option("attributes") |
| 435 |
|
| 436 |
processed_attributes: t.Dict[str, t.Dict[str, str]] = {} |
| 437 |
for name, info in custom_attributes.items(): |
| 438 |
if not info: |
| 439 |
info = {name.replace("-", "_"): "this"} |
| 440 |
elif isinstance(info, str): |
| 441 |
info = {name.replace("-", "_"): info} |
| 442 |
elif not isinstance(info, dict): |
| 443 |
raise AnsibleError( |
| 444 |
f"Attribute {name} value was {type(info).__name__} but was expecting a dictionary" |
| 445 |
) |
| 446 |
|
| 447 |
for var_name in list(info.keys()): |
| 448 |
var_template = info[var_name] |
| 449 |
if not var_template: |
| 450 |
info[var_name] = "this" |
| 451 |
|
| 452 |
elif not isinstance(var_template, str): |
| 453 |
raise AnsibleError( |
| 454 |
f"Attribute {name}.{var_name} template value was {type(var_template).__name__} but was expecting a string" |
| 455 |
) |
| 456 |
|
| 457 |
processed_attributes[name] = info |
| 458 |
|
| 459 |
return processed_attributes |