| 1 |
# Copyright (c) 2017 Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
DOCUMENTATION = """ |
| 7 |
name: constructed |
| 8 |
version_added: "2.4" |
| 9 |
short_description: Uses Jinja2 to construct vars and groups based on existing inventory. |
| 10 |
description: |
| 11 |
- Uses a YAML configuration file with a valid YAML or C(.config) extension to define var expressions and group conditionals |
| 12 |
- The Jinja2 conditionals that qualify a host for membership. |
| 13 |
- The Jinja2 expressions are calculated and assigned to the variables |
| 14 |
- Only variables already available from previous inventories or the fact cache can be used for templating. |
| 15 |
- When O(strict) is False, failed expressions will be ignored (assumes vars were missing). |
| 16 |
options: |
| 17 |
plugin: |
| 18 |
description: token that ensures this is a source file for the 'constructed' plugin. |
| 19 |
required: True |
| 20 |
choices: ['ansible.builtin.constructed', 'constructed'] |
| 21 |
use_vars_plugins: |
| 22 |
description: |
| 23 |
- Normally, for performance reasons, vars plugins get executed after the inventory sources complete the base inventory, |
| 24 |
this option allows for getting vars related to hosts/groups from those plugins. |
| 25 |
- The host_group_vars (enabled by default) 'vars plugin' is the one responsible for reading host_vars/ and group_vars/ directories. |
| 26 |
- This will execute all vars plugins, even those that are not supposed to execute at the 'inventory' stage. |
| 27 |
See vars plugins docs for details on 'stage'. |
| 28 |
- Implicit groups, such as 'all' or 'ungrouped', need to be explicitly defined in any previous inventory to apply the |
| 29 |
corresponding group_vars |
| 30 |
required: false |
| 31 |
default: false |
| 32 |
type: boolean |
| 33 |
version_added: '2.11' |
| 34 |
extends_documentation_fragment: |
| 35 |
- constructed |
| 36 |
""" |
| 37 |
|
| 38 |
EXAMPLES = r""" |
| 39 |
# inventory.config file in YAML format |
| 40 |
plugin: ansible.builtin.constructed |
| 41 |
strict: False |
| 42 |
compose: |
| 43 |
var_sum: var1 + var2 |
| 44 |
|
| 45 |
# this variable will only be set if I have a persistent fact cache enabled (and have non expired facts) |
| 46 |
# `strict: False` will skip this instead of producing an error if it is missing facts. |
| 47 |
server_type: "ansible_hostname | regex_replace ('(.{6})(.{2}).*', '\\2')" |
| 48 |
groups: |
| 49 |
# simple name matching |
| 50 |
webservers: inventory_hostname.startswith('web') |
| 51 |
|
| 52 |
# using ec2 'tags' (assumes aws inventory) |
| 53 |
development: "'devel' in (ec2_tags|list)" |
| 54 |
|
| 55 |
# using other host properties populated in inventory |
| 56 |
private_only: not (public_dns_name is defined or ip_address is defined) |
| 57 |
|
| 58 |
# complex group membership |
| 59 |
multi_group: (group_names | intersect(['alpha', 'beta', 'omega'])) | length >= 2 |
| 60 |
|
| 61 |
keyed_groups: |
| 62 |
# this creates a group per distro (distro_CentOS, distro_Debian) and assigns the hosts that have matching values to it, |
| 63 |
# using the default separator "_" |
| 64 |
- prefix: distro |
| 65 |
key: ansible_distribution |
| 66 |
|
| 67 |
# the following examples assume the first inventory is from the `aws_ec2` plugin |
| 68 |
# this creates a group per ec2 architecture and assign hosts to the matching ones (arch_x86_64, arch_sparc, etc) |
| 69 |
- prefix: arch |
| 70 |
key: architecture |
| 71 |
|
| 72 |
# this creates a group per ec2 region like "us_west_1" |
| 73 |
- prefix: "" |
| 74 |
separator: "" |
| 75 |
key: placement.region |
| 76 |
|
| 77 |
# this creates a common parent group for all ec2 availability zones |
| 78 |
- key: placement.availability_zone |
| 79 |
parent_group: all_ec2_zones |
| 80 |
""" |
| 81 |
|
| 82 |
import os |
| 83 |
|
| 84 |
from ansible import constants as C |
| 85 |
from ansible.errors import AnsibleParserError |
| 86 |
from ansible.inventory.helpers import get_group_vars |
| 87 |
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable |
| 88 |
from ansible.plugins.loader import cache_loader |
| 89 |
from ansible.utils.vars import combine_vars |
| 90 |
from ansible.vars.plugins import get_vars_from_inventory_sources |
| 91 |
|
| 92 |
|
| 93 |
class InventoryModule(BaseInventoryPlugin, Constructable): |
| 94 |
""" constructs groups and vars using Jinja2 template expressions """ |
| 95 |
|
| 96 |
NAME = 'constructed' |
| 97 |
|
| 98 |
# implicit trust behavior is already added by the YAML parser invoked by the loader |
| 99 |
|
| 100 |
def verify_file(self, path): |
| 101 |
|
| 102 |
valid = False |
| 103 |
if super(InventoryModule, self).verify_file(path): |
| 104 |
file_name, ext = os.path.splitext(path) |
| 105 |
|
| 106 |
if not ext or ext in ['.config'] + C.YAML_FILENAME_EXTENSIONS: |
| 107 |
valid = True |
| 108 |
|
| 109 |
return valid |
| 110 |
|
| 111 |
def get_all_host_vars(self, host, loader, sources): |
| 112 |
""" requires host object """ |
| 113 |
return combine_vars(self.host_groupvars(host, loader, sources), self.host_vars(host, loader, sources)) |
| 114 |
|
| 115 |
def host_groupvars(self, host, loader, sources): |
| 116 |
""" requires host object """ |
| 117 |
gvars = get_group_vars(host.get_groups()) |
| 118 |
|
| 119 |
if self.get_option('use_vars_plugins'): |
| 120 |
gvars = combine_vars(gvars, get_vars_from_inventory_sources(loader, sources, host.get_groups(), 'all')) |
| 121 |
|
| 122 |
return gvars |
| 123 |
|
| 124 |
def host_vars(self, host, loader, sources): |
| 125 |
""" requires host object """ |
| 126 |
hvars = host.get_vars() |
| 127 |
|
| 128 |
if self.get_option('use_vars_plugins'): |
| 129 |
hvars = combine_vars(hvars, get_vars_from_inventory_sources(loader, sources, [host], 'all')) |
| 130 |
|
| 131 |
return hvars |
| 132 |
|
| 133 |
def parse(self, inventory, loader, path, cache=False): |
| 134 |
""" parses the inventory file """ |
| 135 |
|
| 136 |
super(InventoryModule, self).parse(inventory, loader, path, cache=cache) |
| 137 |
|
| 138 |
self._read_config_data(path) |
| 139 |
|
| 140 |
sources = [] |
| 141 |
try: |
| 142 |
sources = inventory.processed_sources |
| 143 |
except AttributeError: |
| 144 |
if self.get_option('use_vars_plugins'): |
| 145 |
raise |
| 146 |
|
| 147 |
strict = self.get_option('strict') |
| 148 |
|
| 149 |
cache = cache_loader.get(C.CACHE_PLUGIN) |
| 150 |
|
| 151 |
try: |
| 152 |
# Go over hosts (less var copies) |
| 153 |
for host in inventory.hosts: |
| 154 |
|
| 155 |
# get available variables to templar |
| 156 |
hostvars = self.get_all_host_vars(inventory.hosts[host], loader, sources) |
| 157 |
if cache.contains(host): # adds facts if cache is active |
| 158 |
hostvars = combine_vars(hostvars, cache.get(host)) |
| 159 |
|
| 160 |
# create composite vars |
| 161 |
self._set_composite_vars(self.get_option('compose'), hostvars, host, strict=strict) |
| 162 |
|
| 163 |
# refetch host vars in case new ones have been created above |
| 164 |
hostvars = self.get_all_host_vars(inventory.hosts[host], loader, sources) |
| 165 |
if cache.contains(host): # adds facts if cache is active |
| 166 |
hostvars = combine_vars(hostvars, cache.get(host)) |
| 167 |
|
| 168 |
# constructed groups based on conditionals |
| 169 |
self._add_host_to_composed_groups(self.get_option('groups'), hostvars, host, strict=strict, fetch_hostvars=False) |
| 170 |
|
| 171 |
# constructed groups based variable values |
| 172 |
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), hostvars, host, strict=strict, fetch_hostvars=False) |
| 173 |
|
| 174 |
except Exception as ex: |
| 175 |
raise AnsibleParserError(f"Failed to parse {path!r}.") from ex |