Debian Codegraph @

lib/ansible/plugins/inventory/generator.py

raw
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: generator
8 version_added: "2.6"
9 short_description: Uses Jinja2 to construct hosts and groups from patterns
10 description:
11 - Uses a YAML configuration file with a valid YAML or C(.config) extension to define var expressions and group conditionals
12 - Create a template pattern that describes each host, and then use independent configuration layers
13 - Every element of every layer is combined to create a host for every layer combination
14 - Parent groups can be defined with reference to hosts and other groups using the same template variables
15 options:
16 plugin:
17 description: token that ensures this is a source file for the 'generator' plugin.
18 required: True
19 choices: ['ansible.builtin.generator', 'generator']
20 hosts:
21 description:
22 - The C(name) key is a template used to generate
23 hostnames based on the C(layers) option. Each variable in the name is expanded to create a
24 cartesian product of all possible layer combinations.
25 - The C(parents) are a list of parent groups that the host belongs to. Each C(parent) item
26 contains a C(name) key, again expanded from the template, and an optional C(parents) key
27 that lists its parents.
28 - Parents can also contain C(vars), which is a dictionary of vars that
29 is then always set for that variable. This can provide easy access to the group name. E.g
30 set an C(application) variable that is set to the value of the C(application) layer name.
31 layers:
32 description:
33 - A dictionary of layers, with the key being the layer name, used as a variable name in the C(host)
34 C(name) and C(parents) keys. Each layer value is a list of possible values for that layer.
35 use_extra_vars:
36 version_added: '2.21'
37 description:
38 - Merge extra vars into the available variables for composition (highest precedence).
39 type: bool
40 default: false
41 ini:
42 - section: inventory_plugins
43 key: use_extra_vars
44 - section: inventory_plugin_generator
45 key: use_extra_vars
46 env:
47 - name: ANSIBLE_INVENTORY_USE_EXTRA_VARS
48 - name: ANSIBLE_GENERATOR_USE_EXTRA_VARS
49 """
50
51 EXAMPLES = """
52 # inventory.config file in YAML format
53 # remember to enable this inventory plugin in the ansible.cfg before using
54 # View the output using `ansible-inventory -i inventory.config --list`
55 plugin: ansible.builtin.generator
56 hosts:
57 name: "{{ operation }}_{{ application }}_{{ environment }}_runner"
58 parents:
59 - name: "{{ operation }}_{{ application }}_{{ environment }}"
60 parents:
61 - name: "{{ operation }}_{{ application }}"
62 parents:
63 - name: "{{ operation }}"
64 - name: "{{ application }}"
65 - name: "{{ application }}_{{ environment }}"
66 parents:
67 - name: "{{ application }}"
68 vars:
69 application: "{{ application }}"
70 - name: "{{ environment }}"
71 vars:
72 environment: "{{ environment }}"
73 - name: runner
74 layers:
75 operation:
76 - build
77 - launch
78 environment:
79 - dev
80 - test
81 - prod
82 application:
83 - web
84 - api
85 """
86
87 import os
88
89 from itertools import product
90
91 from ansible import constants as C
92 from ansible.errors import AnsibleParserError
93 from ansible.plugins.inventory import BaseInventoryPlugin
94 from ansible.utils.vars import load_extra_vars
95
96
97 class InventoryModule(BaseInventoryPlugin):
98 """ constructs groups and vars using Jinja2 template expressions """
99
100 NAME = 'generator'
101
102 # implicit trust behavior is already added by the YAML parser invoked by the loader
103
104 def __init__(self):
105
106 super(InventoryModule, self).__init__()
107
108 def verify_file(self, path):
109
110 valid = False
111 if super(InventoryModule, self).verify_file(path):
112 file_name, ext = os.path.splitext(path)
113
114 if not ext or ext in ['.config'] + C.YAML_FILENAME_EXTENSIONS:
115 valid = True
116
117 return valid
118
119 def template(self, pattern, variables):
120 # Allow pass-through of data structures for templating later (if applicable).
121 # This limitation was part of the original plugin implementation and was updated to maintain feature parity with the new templating API.
122 if not isinstance(pattern, str):
123 return pattern
124
125 return self.templar.copy_with_new_env(available_variables=variables).template(pattern)
126
127 def add_parents(self, inventory, child, parents, template_vars):
128 for parent in parents:
129 groupname = self.template(parent.get('name'), template_vars)
130 if not groupname:
131 raise AnsibleParserError(f"Element {child} has a parent with no name.")
132 if groupname not in inventory.groups:
133 inventory.add_group(groupname)
134 group = inventory.groups[groupname]
135 for (k, v) in parent.get('vars', {}).items():
136 group.set_variable(k, self.template(v, template_vars))
137 inventory.add_child(groupname, child)
138 self.add_parents(inventory, groupname, parent.get('parents', []), template_vars)
139
140 def parse(self, inventory, loader, path, cache=False):
141 """ parses the inventory file """
142
143 super(InventoryModule, self).parse(inventory, loader, path, cache=cache)
144
145 config = self._read_config_data(path)
146 if self.get_option('use_extra_vars'):
147 extra_vars = load_extra_vars(loader)
148 else:
149 extra_vars = {}
150 template_inputs = product(*config['layers'].values())
151 for item in template_inputs:
152 template_vars = dict()
153 template_vars.update(extra_vars)
154 for i, key in enumerate(config['layers'].keys()):
155 template_vars[key] = item[i]
156 host = self.template(config['hosts']['name'], template_vars)
157 inventory.add_host(host)
158 self.add_parents(inventory, host, config['hosts'].get('parents', []), template_vars)