| 1 |
# Copyright (c) 2020, FELDSAM s.r.o. - FeldHost™ <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
name: opennebula |
| 9 |
author: |
| 10 |
- Kristian Feldsam (@feldsam) |
| 11 |
short_description: OpenNebula inventory source |
| 12 |
version_added: "3.8.0" |
| 13 |
extends_documentation_fragment: |
| 14 |
- ansible.builtin.constructed |
| 15 |
description: |
| 16 |
- Get inventory hosts from OpenNebula cloud. |
| 17 |
- Uses an YAML configuration file ending with either C(opennebula.yml) or C(opennebula.yaml) to set parameter values. |
| 18 |
- Uses O(api_authfile), C(~/.one/one_auth), or E(ONE_AUTH) pointing to a OpenNebula credentials file. |
| 19 |
options: |
| 20 |
plugin: |
| 21 |
description: Token that ensures this is a source file for the 'opennebula' plugin. |
| 22 |
type: string |
| 23 |
required: true |
| 24 |
choices: [community.general.opennebula] |
| 25 |
api_url: |
| 26 |
description: |
| 27 |
- URL of the OpenNebula RPC server. |
| 28 |
- It is recommended to use HTTPS so that the username/password are not transferred over the network unencrypted. |
| 29 |
- If not set then the value of the E(ONE_URL) environment variable is used. |
| 30 |
env: |
| 31 |
- name: ONE_URL |
| 32 |
required: true |
| 33 |
type: string |
| 34 |
api_username: |
| 35 |
description: |
| 36 |
- Name of the user to login into the OpenNebula RPC server. If not set then the value of the E(ONE_USERNAME) environment |
| 37 |
variable is used. |
| 38 |
env: |
| 39 |
- name: ONE_USERNAME |
| 40 |
type: string |
| 41 |
api_password: |
| 42 |
description: |
| 43 |
- Password or a token of the user to login into OpenNebula RPC server. |
| 44 |
- If not set, the value of the E(ONE_PASSWORD) environment variable is used. |
| 45 |
env: |
| 46 |
- name: ONE_PASSWORD |
| 47 |
required: false |
| 48 |
type: string |
| 49 |
api_authfile: |
| 50 |
description: |
| 51 |
- If both O(api_username) or O(api_password) are not set, then it tries to authenticate with ONE auth file. Default |
| 52 |
path is C(~/.one/one_auth). |
| 53 |
- Set environment variable E(ONE_AUTH) to override this path. |
| 54 |
env: |
| 55 |
- name: ONE_AUTH |
| 56 |
required: false |
| 57 |
type: string |
| 58 |
hostname: |
| 59 |
description: Field to match the hostname. Note V(v4_first_ip) corresponds to the first IPv4 found on VM. |
| 60 |
type: string |
| 61 |
default: v4_first_ip |
| 62 |
choices: |
| 63 |
- v4_first_ip |
| 64 |
- v6_first_ip |
| 65 |
- name |
| 66 |
filter_by_label: |
| 67 |
description: Only return servers filtered by this label. |
| 68 |
type: string |
| 69 |
group_by_labels: |
| 70 |
description: Create host groups by VM labels. |
| 71 |
type: bool |
| 72 |
default: true |
| 73 |
""" |
| 74 |
|
| 75 |
EXAMPLES = r""" |
| 76 |
# inventory_opennebula.yml file in YAML format |
| 77 |
# Example command line: ansible-inventory --list -i inventory_opennebula.yml |
| 78 |
|
| 79 |
# Pass a label filter to the API |
| 80 |
plugin: community.general.opennebula |
| 81 |
api_url: https://opennebula:2633/RPC2 |
| 82 |
filter_by_label: Cache |
| 83 |
""" |
| 84 |
|
| 85 |
try: |
| 86 |
import pyone |
| 87 |
|
| 88 |
HAS_PYONE = True |
| 89 |
except ImportError: |
| 90 |
HAS_PYONE = False |
| 91 |
|
| 92 |
import os |
| 93 |
from dataclasses import dataclass |
| 94 |
|
| 95 |
from ansible.errors import AnsibleError |
| 96 |
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable |
| 97 |
|
| 98 |
from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe |
| 99 |
|
| 100 |
|
| 101 |
@dataclass |
| 102 |
class AuthParams: |
| 103 |
url: str |
| 104 |
username: str |
| 105 |
password: str |
| 106 |
|
| 107 |
|
| 108 |
class InventoryModule(BaseInventoryPlugin, Constructable): |
| 109 |
NAME = "community.general.opennebula" |
| 110 |
|
| 111 |
def verify_file(self, path): |
| 112 |
valid = False |
| 113 |
if super().verify_file(path): |
| 114 |
if path.endswith(("opennebula.yaml", "opennebula.yml")): |
| 115 |
valid = True |
| 116 |
return valid |
| 117 |
|
| 118 |
def _get_connection_info(self): |
| 119 |
url = self.get_option("api_url") |
| 120 |
username = self.get_option("api_username") |
| 121 |
password = self.get_option("api_password") |
| 122 |
authfile = self.get_option("api_authfile") |
| 123 |
|
| 124 |
if not username and not password: |
| 125 |
if authfile is None: |
| 126 |
authfile = os.path.join(os.environ.get("HOME"), ".one", "one_auth") |
| 127 |
try: |
| 128 |
with open(authfile) as fp: |
| 129 |
authstring = fp.read().rstrip() |
| 130 |
username, password = authstring.split(":") |
| 131 |
except OSError as e: |
| 132 |
raise AnsibleError(f"Could not find or read ONE_AUTH file at '{authfile}'") from e |
| 133 |
except Exception as e: |
| 134 |
raise AnsibleError(f"Error occurs when reading ONE_AUTH file at '{authfile}'") from e |
| 135 |
|
| 136 |
return AuthParams(url=url, username=username, password=password) |
| 137 |
|
| 138 |
def _get_vm_ipv4(self, vm): |
| 139 |
nic = vm.TEMPLATE.get("NIC") |
| 140 |
|
| 141 |
if isinstance(nic, dict): |
| 142 |
nic = [nic] |
| 143 |
|
| 144 |
for net in nic: |
| 145 |
if net.get("IP"): |
| 146 |
return net["IP"] |
| 147 |
|
| 148 |
return False |
| 149 |
|
| 150 |
def _get_vm_ipv6(self, vm): |
| 151 |
nic = vm.TEMPLATE.get("NIC") |
| 152 |
|
| 153 |
if isinstance(nic, dict): |
| 154 |
nic = [nic] |
| 155 |
|
| 156 |
for net in nic: |
| 157 |
if net.get("IP6_GLOBAL"): |
| 158 |
return net["IP6_GLOBAL"] |
| 159 |
|
| 160 |
return False |
| 161 |
|
| 162 |
def _get_vm_pool(self): |
| 163 |
auth = self._get_connection_info() |
| 164 |
|
| 165 |
if not (auth.username and auth.password): |
| 166 |
raise AnsibleError("API Credentials missing. Check OpenNebula inventory file.") |
| 167 |
else: |
| 168 |
one_client = pyone.OneServer(auth.url, session=f"{auth.username}:{auth.password}") |
| 169 |
|
| 170 |
# get hosts (VMs) |
| 171 |
try: |
| 172 |
vm_pool = one_client.vmpool.infoextended(-2, -1, -1, 3) |
| 173 |
except Exception as e: |
| 174 |
raise AnsibleError(f"Something happened during XML-RPC call: {e}") from e |
| 175 |
|
| 176 |
return vm_pool |
| 177 |
|
| 178 |
def _retrieve_servers(self, label_filter=None): |
| 179 |
vm_pool = self._get_vm_pool() |
| 180 |
|
| 181 |
result = [] |
| 182 |
|
| 183 |
# iterate over hosts |
| 184 |
for vm in vm_pool.VM: |
| 185 |
server = vm.USER_TEMPLATE |
| 186 |
|
| 187 |
labels = [] |
| 188 |
if vm.USER_TEMPLATE.get("LABELS"): |
| 189 |
labels = [ |
| 190 |
s for s in vm.USER_TEMPLATE.get("LABELS") if s == "," or s == "-" or s.isalnum() or s.isspace() |
| 191 |
] |
| 192 |
labels = "".join(labels) |
| 193 |
labels = labels.replace(" ", "_") |
| 194 |
labels = labels.replace("-", "_") |
| 195 |
labels = labels.split(",") |
| 196 |
|
| 197 |
# filter by label |
| 198 |
if label_filter is not None: |
| 199 |
if label_filter not in labels: |
| 200 |
continue |
| 201 |
|
| 202 |
server["name"] = vm.NAME |
| 203 |
server["id"] = vm.ID |
| 204 |
if hasattr(vm.HISTORY_RECORDS, "HISTORY") and vm.HISTORY_RECORDS.HISTORY: |
| 205 |
server["host"] = vm.HISTORY_RECORDS.HISTORY[-1].HOSTNAME |
| 206 |
server["LABELS"] = labels |
| 207 |
server["v4_first_ip"] = self._get_vm_ipv4(vm) |
| 208 |
server["v6_first_ip"] = self._get_vm_ipv6(vm) |
| 209 |
|
| 210 |
result.append(server) |
| 211 |
|
| 212 |
return result |
| 213 |
|
| 214 |
def _populate(self): |
| 215 |
hostname_preference = self.get_option("hostname") |
| 216 |
group_by_labels = self.get_option("group_by_labels") |
| 217 |
strict = self.get_option("strict") |
| 218 |
|
| 219 |
# Add a top group 'one' |
| 220 |
self.inventory.add_group(group="all") |
| 221 |
|
| 222 |
filter_by_label = self.get_option("filter_by_label") |
| 223 |
servers = self._retrieve_servers(filter_by_label) |
| 224 |
for server in servers: |
| 225 |
server = make_unsafe(server) |
| 226 |
hostname = server["name"] |
| 227 |
# check for labels |
| 228 |
if group_by_labels and server["LABELS"]: |
| 229 |
for label in server["LABELS"]: |
| 230 |
self.inventory.add_group(group=label) |
| 231 |
self.inventory.add_host(host=hostname, group=label) |
| 232 |
|
| 233 |
self.inventory.add_host(host=hostname, group="all") |
| 234 |
|
| 235 |
for attribute, value in server.items(): |
| 236 |
self.inventory.set_variable(hostname, attribute, value) |
| 237 |
|
| 238 |
if hostname_preference != "name": |
| 239 |
self.inventory.set_variable(hostname, "ansible_host", server[hostname_preference]) |
| 240 |
|
| 241 |
if server.get("SSH_PORT"): |
| 242 |
self.inventory.set_variable(hostname, "ansible_port", server["SSH_PORT"]) |
| 243 |
|
| 244 |
# handle construcable implementation: get composed variables if any |
| 245 |
self._set_composite_vars(self.get_option("compose"), server, hostname, strict=strict) |
| 246 |
|
| 247 |
# groups based on jinja conditionals get added to specific groups |
| 248 |
self._add_host_to_composed_groups(self.get_option("groups"), server, hostname, strict=strict) |
| 249 |
|
| 250 |
# groups based on variables associated with them in the inventory |
| 251 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), server, hostname, strict=strict) |
| 252 |
|
| 253 |
def parse(self, inventory, loader, path, cache=True): |
| 254 |
if not HAS_PYONE: |
| 255 |
raise AnsibleError("OpenNebula Inventory plugin requires pyone to work!") |
| 256 |
|
| 257 |
super().parse(inventory, loader, path) |
| 258 |
self._read_config_data(path=path) |
| 259 |
|
| 260 |
self._populate() |