| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright (c) 2019 Oleksandr Stepanov <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
|
| 8 |
from __future__ import absolute_import, division, print_function |
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
|
| 12 |
DOCUMENTATION = r""" |
| 13 |
name: robot |
| 14 |
author: |
| 15 |
- Oleksandr Stepanov (@alexandrst88) |
| 16 |
short_description: Hetzner Robot inventory source |
| 17 |
version_added: 1.1.0 |
| 18 |
description: |
| 19 |
- Reads servers from Hetzner Robot API. |
| 20 |
- Uses a YAML configuration file that ends with C(robot.yml) or C(robot.yaml). |
| 21 |
- The inventory plugin adds all values from U(https://robot.your-server.de/doc/webservice/en.html#get-server) prepended |
| 22 |
with C(hrobot_) to the server's inventory. For example, the variable C(hrobot_dc) contains the data center the server |
| 23 |
is located in. |
| 24 |
extends_documentation_fragment: |
| 25 |
- ansible.builtin.constructed |
| 26 |
- ansible.builtin.inventory_cache |
| 27 |
- community.hrobot.robot |
| 28 |
- community.library_inventory_filtering_v1.inventory_filter |
| 29 |
notes: |
| 30 |
- The O(hetzner_user) and O(hetzner_password) options can be templated. |
| 31 |
options: |
| 32 |
plugin: |
| 33 |
description: Token that ensures this is a source file for the plugin. |
| 34 |
required: true |
| 35 |
choices: ["community.hrobot.robot"] |
| 36 |
hetzner_user: |
| 37 |
env: |
| 38 |
- name: HROBOT_API_USER |
| 39 |
hetzner_password: |
| 40 |
env: |
| 41 |
- name: HROBOT_API_PASSWORD |
| 42 |
simple_filters: |
| 43 |
description: |
| 44 |
- A dictionary of filter value pairs. |
| 45 |
- Available filters are listed here are keys of server like C(status) or C(server_ip). |
| 46 |
- See U(https://robot.your-server.de/doc/webservice/en.html#get-server) for all values that can be used. |
| 47 |
- This option used to be called O(filters) before community.hrobot 2.0.0. It has been renamed from O(filters) to O(simple_filters) |
| 48 |
in community.hrobotdns 1.9.0, and the old name was still available as an alias until community.hrobot 2.0.0. O(filters) |
| 49 |
is now used for something else. |
| 50 |
type: dict |
| 51 |
default: {} |
| 52 |
filters: |
| 53 |
version_added: 2.0.0 |
| 54 |
""" |
| 55 |
|
| 56 |
EXAMPLES = r""" |
| 57 |
--- |
| 58 |
# Fetch all hosts in Hetzner Robot |
| 59 |
plugin: community.hrobot.robot |
| 60 |
# Filters all servers in ready state |
| 61 |
filters: |
| 62 |
status: ready |
| 63 |
|
| 64 |
--- |
| 65 |
# Example showing encrypted credentials and using filters |
| 66 |
# (This assumes that Mozilla sops was used to encrypt keys/hetzner.sops.yaml, which contains two values |
| 67 |
# hetzner_username and hetzner_password. Needs the community.sops collection to decode that file.) |
| 68 |
plugin: community.hrobot.robot |
| 69 |
hetzner_user: '{{ (lookup("community.sops.sops", "keys/hetzner.sops.yaml") | from_yaml).hetzner_username }}' |
| 70 |
hetzner_password: '{{ (lookup("community.sops.sops", "keys/hetzner.sops.yaml") | from_yaml).hetzner_password }}' |
| 71 |
filters: |
| 72 |
# Accept all servers in FSN1-DC1 and FSN1-DC2 |
| 73 |
- include: >- |
| 74 |
hrobot_dc in ["FSN1-DC1", "FSN1-DC2"] |
| 75 |
# Exclude all servers that did not match any of the above filters |
| 76 |
- exclude: true |
| 77 |
|
| 78 |
--- |
| 79 |
# Example using constructed features to create groups |
| 80 |
plugin: community.hrobot.robot |
| 81 |
simple_filters: |
| 82 |
status: ready |
| 83 |
traffic: unlimited |
| 84 |
# keyed_groups may be used to create custom groups |
| 85 |
strict: false |
| 86 |
keyed_groups: |
| 87 |
# Add e.g. groups for every data center |
| 88 |
- key: hrobot_dc |
| 89 |
separator: "" |
| 90 |
# Use the IP address to connect to the host |
| 91 |
compose: |
| 92 |
server_name_ip: hrobot_server_name ~ '-' ~ hrobot_server_ip |
| 93 |
""" |
| 94 |
|
| 95 |
from ansible.errors import AnsibleError |
| 96 |
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable |
| 97 |
from ansible.template import Templar |
| 98 |
from ansible.utils.display import Display |
| 99 |
|
| 100 |
from ansible_collections.community.library_inventory_filtering_v1.plugins.plugin_utils.inventory_filter import parse_filters, filter_host |
| 101 |
|
| 102 |
from ansible_collections.community.hrobot.plugins.module_utils.common import ( |
| 103 |
PluginException, |
| 104 |
) |
| 105 |
from ansible_collections.community.hrobot.plugins.module_utils.robot import ( |
| 106 |
BASE_URL, |
| 107 |
plugin_open_url_json, |
| 108 |
) |
| 109 |
from ansible_collections.community.hrobot.plugins.plugin_utils.unsafe import make_unsafe |
| 110 |
|
| 111 |
display = Display() |
| 112 |
|
| 113 |
|
| 114 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 115 |
|
| 116 |
NAME = 'community.hrobot.robot' |
| 117 |
|
| 118 |
def verify_file(self, path): |
| 119 |
''' return true/false if this is possibly a valid file for this plugin to consume ''' |
| 120 |
valid = False |
| 121 |
if super(InventoryModule, self).verify_file(path): |
| 122 |
# base class verifies that file exists and is readable by current user |
| 123 |
if path.endswith(('robot.yaml', 'robot.yml')): |
| 124 |
valid = True |
| 125 |
else: |
| 126 |
display.debug("robot inventory filename must end with 'robot.yml' or 'robot.yaml'") |
| 127 |
return valid |
| 128 |
|
| 129 |
def parse(self, inventory, loader, path, cache=True): |
| 130 |
super(InventoryModule, self).parse(inventory, loader, path) |
| 131 |
servers = {} |
| 132 |
self._read_config_data(path) |
| 133 |
self.load_cache_plugin() |
| 134 |
cache_key = self.get_cache_key(path) |
| 135 |
|
| 136 |
self.templar = Templar(loader=loader) |
| 137 |
|
| 138 |
# cache may be True or False at this point to indicate if the inventory is being refreshed |
| 139 |
# get the user's cache option too to see if we should save the cache if it is changing |
| 140 |
user_cache_setting = self.get_option('cache') |
| 141 |
|
| 142 |
# read if the user has caching enabled and the cache is not being refreshed |
| 143 |
attempt_to_read_cache = user_cache_setting and cache |
| 144 |
# update if the user has caching enabled and the cache is being refreshed; update this value to True if the cache has expired below |
| 145 |
cache_needs_update = user_cache_setting and not cache |
| 146 |
|
| 147 |
# attempt to read the cache if inventory is not being refreshed and the user has caching enabled |
| 148 |
if attempt_to_read_cache: |
| 149 |
try: |
| 150 |
servers = self._cache[cache_key] |
| 151 |
except KeyError: |
| 152 |
# This occurs if the cache_key is not in the cache or if the cache_key expired, so the cache needs to be updated |
| 153 |
cache_needs_update = True |
| 154 |
elif not cache_needs_update: |
| 155 |
servers = self.get_servers() |
| 156 |
else: |
| 157 |
# This can only happen if the code is modified so that cache=False |
| 158 |
pass # pragma: no cover |
| 159 |
|
| 160 |
if cache_needs_update: |
| 161 |
servers = self.get_servers() |
| 162 |
|
| 163 |
# set the cache |
| 164 |
self._cache[cache_key] = servers |
| 165 |
|
| 166 |
self.populate(servers) |
| 167 |
|
| 168 |
def populate(self, servers): |
| 169 |
simple_filters = self.get_option('simple_filters') |
| 170 |
filters = parse_filters(self.get_option('filters')) |
| 171 |
strict = self.get_option('strict') |
| 172 |
server_lists = [] |
| 173 |
for server in servers: |
| 174 |
s = server['server'] |
| 175 |
server_name = s.get('server_name') or s.get('server_ip') or str(s['server_number']) |
| 176 |
matched = self.filter(s, simple_filters) |
| 177 |
if not matched: |
| 178 |
continue |
| 179 |
|
| 180 |
facts = {} |
| 181 |
if 'server_ip' in s: |
| 182 |
facts['ansible_host'] = make_unsafe(s['server_ip']) |
| 183 |
for hostvar, hostval in s.items(): |
| 184 |
facts["{0}_{1}".format('hrobot', hostvar)] = make_unsafe(hostval) |
| 185 |
|
| 186 |
if not filter_host(self, server_name, facts, filters): |
| 187 |
continue |
| 188 |
|
| 189 |
if server_name in server_lists: |
| 190 |
display.warning('Two of your Hetzner servers use the same server name ({0}). ' |
| 191 |
'Please make sure that your server names are unique. ' |
| 192 |
'Only the first server named {0} will be included in the inventory.'.format(server_name)) |
| 193 |
continue |
| 194 |
|
| 195 |
self.inventory.add_host(server_name) |
| 196 |
server_lists.append(server_name) |
| 197 |
for key, value in facts.items(): |
| 198 |
self.inventory.set_variable(server_name, key, value) |
| 199 |
|
| 200 |
# Composed variables |
| 201 |
server_vars = self.inventory.get_host(server_name).get_vars() |
| 202 |
self._set_composite_vars(self.get_option('compose'), server_vars, server_name, strict=strict) |
| 203 |
|
| 204 |
# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group |
| 205 |
self._add_host_to_composed_groups(self.get_option('groups'), server, server_name, strict=strict) |
| 206 |
|
| 207 |
# Create groups based on variable values and add the corresponding hosts to it |
| 208 |
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), server, server_name, strict=strict) |
| 209 |
|
| 210 |
def filter(self, server, simple_filters): |
| 211 |
matched = True |
| 212 |
for key, value in simple_filters.items(): |
| 213 |
if server.get(key) != value: |
| 214 |
matched = False |
| 215 |
break |
| 216 |
return matched |
| 217 |
|
| 218 |
def get_servers(self): |
| 219 |
try: |
| 220 |
return plugin_open_url_json(self, '{0}/server'.format(BASE_URL), templar=self.templar)[0] |
| 221 |
except PluginException as e: |
| 222 |
raise AnsibleError(e.error_message) |