| 1 |
# Copyright (c) 2019 Hetzner Cloud GmbH <[email protected]> |
| 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: hcloud |
| 8 |
short_description: Ansible dynamic inventory plugin for the Hetzner Cloud. |
| 9 |
|
| 10 |
description: |
| 11 |
- Reads inventories from the Hetzner Cloud API. |
| 12 |
- Uses a YAML configuration file that ends with C(hcloud.yml) or C(hcloud.yaml). |
| 13 |
|
| 14 |
author: |
| 15 |
- Lukas Kaemmerling (@lkaemmerling) |
| 16 |
|
| 17 |
requirements: |
| 18 |
- python-dateutil >= 2.7.5 |
| 19 |
- requests >=2.20 |
| 20 |
|
| 21 |
extends_documentation_fragment: |
| 22 |
- constructed |
| 23 |
- inventory_cache |
| 24 |
|
| 25 |
options: |
| 26 |
plugin: |
| 27 |
description: Mark this as an P(hetzner.hcloud.hcloud#inventory) inventory instance. |
| 28 |
required: true |
| 29 |
choices: [hcloud, hetzner.hcloud.hcloud] |
| 30 |
|
| 31 |
api_token: |
| 32 |
description: |
| 33 |
- The API Token for the Hetzner Cloud. |
| 34 |
type: str |
| 35 |
required: true |
| 36 |
aliases: [token] |
| 37 |
env: |
| 38 |
- name: HCLOUD_TOKEN |
| 39 |
api_endpoint: |
| 40 |
description: |
| 41 |
- The API Endpoint for the Hetzner Cloud. |
| 42 |
type: str |
| 43 |
default: https://api.hetzner.cloud/v1 |
| 44 |
env: |
| 45 |
- name: HCLOUD_ENDPOINT |
| 46 |
|
| 47 |
group: |
| 48 |
description: The group all servers are automatically added to. |
| 49 |
default: hcloud |
| 50 |
type: str |
| 51 |
required: false |
| 52 |
connect_with: |
| 53 |
description: | |
| 54 |
Connect to the server using the value from this field. This sets the C(ansible_host) |
| 55 |
variable to the value indicated, if that value is available. If you need further |
| 56 |
customization, like falling back to private ipv4 if the server has no public ipv4, |
| 57 |
you can use O(compose) top-level key. |
| 58 |
default: public_ipv4 |
| 59 |
type: str |
| 60 |
choices: |
| 61 |
- public_ipv4 |
| 62 |
- public_ipv6 |
| 63 |
- hostname |
| 64 |
- ipv4_dns_ptr |
| 65 |
- private_ipv4 |
| 66 |
|
| 67 |
locations: |
| 68 |
description: Populate inventory with instances in this location. |
| 69 |
default: [] |
| 70 |
type: list |
| 71 |
elements: str |
| 72 |
required: false |
| 73 |
types: |
| 74 |
description: Populate inventory with instances with this type. |
| 75 |
default: [] |
| 76 |
type: list |
| 77 |
elements: str |
| 78 |
required: false |
| 79 |
images: |
| 80 |
description: Populate inventory with instances with this image name, only available for system images. |
| 81 |
default: [] |
| 82 |
type: list |
| 83 |
elements: str |
| 84 |
required: false |
| 85 |
label_selector: |
| 86 |
description: Populate inventory with instances with this label. |
| 87 |
default: "" |
| 88 |
type: str |
| 89 |
required: false |
| 90 |
network: |
| 91 |
description: Populate inventory with instances which are attached to this network name or ID. |
| 92 |
default: "" |
| 93 |
type: str |
| 94 |
required: false |
| 95 |
status: |
| 96 |
description: Populate inventory with instances with this status. |
| 97 |
default: [] |
| 98 |
type: list |
| 99 |
elements: str |
| 100 |
required: false |
| 101 |
|
| 102 |
hostvars_prefix: |
| 103 |
description: |
| 104 |
- The prefix for host variables names coming from Hetzner Cloud. |
| 105 |
default: hcloud_ |
| 106 |
type: str |
| 107 |
version_added: 2.5.0 |
| 108 |
hostvars_suffix: |
| 109 |
description: |
| 110 |
- The suffix for host variables names coming from Hetzner Cloud. |
| 111 |
type: str |
| 112 |
version_added: 2.5.0 |
| 113 |
|
| 114 |
hostname: |
| 115 |
description: |
| 116 |
- A template for the instances hostname, if not provided the Hetzner Cloud server name will be used. |
| 117 |
- Available variables are the Hetzner Cloud host variables. |
| 118 |
- The available variables names are provide with the O(hostvars_prefix) or O(hostvars_suffix) modifications. |
| 119 |
type: str |
| 120 |
version_added: 3.0.0 |
| 121 |
""" |
| 122 |
|
| 123 |
EXAMPLES = """ |
| 124 |
# Minimal example. 'HCLOUD_TOKEN' is exposed in environment. |
| 125 |
plugin: hetzner.hcloud.hcloud |
| 126 |
|
| 127 |
--- |
| 128 |
# Example with templated token, e.g. provided through extra vars. |
| 129 |
plugin: hetzner.hcloud.hcloud |
| 130 |
api_token: "{{ _vault_hetzner_cloud_token }}" |
| 131 |
|
| 132 |
--- |
| 133 |
# Example with locations, types, status |
| 134 |
plugin: hetzner.hcloud.hcloud |
| 135 |
locations: |
| 136 |
- nbg1 |
| 137 |
types: |
| 138 |
- cpx22 |
| 139 |
status: |
| 140 |
- running |
| 141 |
|
| 142 |
--- |
| 143 |
# Group by a location with prefix e.g. "hcloud_location_nbg1" |
| 144 |
# and image_os_flavor without prefix and separator e.g. "ubuntu" |
| 145 |
# and status with prefix e.g. "server_status_running" |
| 146 |
plugin: hetzner.hcloud.hcloud |
| 147 |
keyed_groups: |
| 148 |
- key: hcloud_location |
| 149 |
prefix: hcloud_location |
| 150 |
- key: image_os_flavor |
| 151 |
separator: "" |
| 152 |
- key: hcloud_status |
| 153 |
prefix: server_status |
| 154 |
|
| 155 |
--- |
| 156 |
# Use a custom hostname template. |
| 157 |
plugin: hetzner.hcloud.hcloud |
| 158 |
|
| 159 |
# Available variables are for example: |
| 160 |
## Server |
| 161 |
# hcloud_id: 42984895 |
| 162 |
# hcloud_name: "my-server" |
| 163 |
# hcloud_labels: |
| 164 |
# foo: "bar" |
| 165 |
# hcloud_status: "running" |
| 166 |
## Server Type |
| 167 |
# hcloud_type: "cpx22" |
| 168 |
# hcloud_server_type: "cpx22" |
| 169 |
# hcloud_architecture: "x86" |
| 170 |
## Image |
| 171 |
# hcloud_image_id: 114690387 |
| 172 |
# hcloud_image_name: "debian-12" |
| 173 |
# hcloud_image_os_flavor: "debian" |
| 174 |
## Location |
| 175 |
# hcloud_location: "hel1" |
| 176 |
# # The hcloud_datacenter variable is deprecated and will be removed after 1 July 2026. |
| 177 |
# # Please use the hcloud_location variable instead. |
| 178 |
# # See https://docs.hetzner.cloud/changelog#2025-12-16-phasing-out-datacenters. |
| 179 |
# hcloud_datacenter: "hel1-dc2" |
| 180 |
## Network |
| 181 |
# hcloud_ipv4: "65.109.140.95" # Value is optional! |
| 182 |
# hcloud_ipv6: "2a01:4f9:c011:b83f::1" # Value is optional! |
| 183 |
# hcloud_ipv6_network: 2a01:4f9:c011:b83f::" # Value is optional! |
| 184 |
# hcloud_ipv6_network_mask: "64" # Value is optional! |
| 185 |
# hcloud_private_ipv4: "10.0.0.3" # Value is optional! |
| 186 |
# hcloud_private_networks: |
| 187 |
# - id: 114690387 |
| 188 |
# name: "my-private-network" |
| 189 |
# ip: "10.0.0.3" |
| 190 |
# |
| 191 |
hostname: "my-prefix-{{ hcloud_location }}-{{ hcloud_name }}-{{ hcloud_server_type }}" |
| 192 |
""" |
| 193 |
|
| 194 |
import sys |
| 195 |
import warnings |
| 196 |
from ipaddress import IPv6Network |
| 197 |
|
| 198 |
from ansible.errors import AnsibleError |
| 199 |
from ansible.inventory.manager import InventoryData |
| 200 |
from ansible.module_utils.common.text.converters import to_native |
| 201 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable |
| 202 |
from ansible.utils.display import Display |
| 203 |
from ansible.utils.vars import combine_vars |
| 204 |
|
| 205 |
from ..module_utils._client import ( |
| 206 |
Client, |
| 207 |
ClientException, |
| 208 |
client_check_required_lib, |
| 209 |
client_get_by_name_or_id, |
| 210 |
) |
| 211 |
from ..module_utils._vendor.hcloud import APIException |
| 212 |
from ..module_utils._vendor.hcloud.networks import Network |
| 213 |
from ..module_utils._vendor.hcloud.servers import Server |
| 214 |
from ..module_utils._version import version |
| 215 |
|
| 216 |
if sys.version_info >= (3, 11): |
| 217 |
# The typed dicts are only used to help development and we prefer not requiring |
| 218 |
# the additional typing-extensions dependency |
| 219 |
from typing import NotRequired, TypedDict |
| 220 |
|
| 221 |
class InventoryPrivateNetwork(TypedDict): |
| 222 |
id: int |
| 223 |
name: str |
| 224 |
ip: str |
| 225 |
|
| 226 |
class InventoryServer(TypedDict): |
| 227 |
id: int |
| 228 |
name: str |
| 229 |
status: str |
| 230 |
|
| 231 |
# Server Type |
| 232 |
type: str |
| 233 |
server_type: str |
| 234 |
architecture: str |
| 235 |
|
| 236 |
# Datacenter |
| 237 |
datacenter: str # Deprecated! |
| 238 |
location: str |
| 239 |
|
| 240 |
# Labels |
| 241 |
labels: dict[str, str] |
| 242 |
|
| 243 |
# Network |
| 244 |
ipv4: NotRequired[str] |
| 245 |
ipv6: NotRequired[str] |
| 246 |
ipv6_network: NotRequired[str] |
| 247 |
ipv6_network_mask: NotRequired[str] |
| 248 |
private_ipv4: NotRequired[str] |
| 249 |
private_networks: list[InventoryPrivateNetwork] |
| 250 |
|
| 251 |
# Image |
| 252 |
image_id: int |
| 253 |
image_name: str |
| 254 |
image_os_flavor: str |
| 255 |
|
| 256 |
# Ansible |
| 257 |
ansible_host: str |
| 258 |
|
| 259 |
else: |
| 260 |
InventoryServer = dict |
| 261 |
|
| 262 |
|
| 263 |
def first_ipv6_address(network: str) -> str: |
| 264 |
""" |
| 265 |
Return the first address for a ipv6 network. |
| 266 |
|
| 267 |
:param network: IPv6 Network. |
| 268 |
""" |
| 269 |
return str(next(IPv6Network(network).hosts())) |
| 270 |
|
| 271 |
|
| 272 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 273 |
NAME = "hetzner.hcloud.hcloud" |
| 274 |
|
| 275 |
inventory: InventoryData |
| 276 |
display: Display |
| 277 |
|
| 278 |
client: Client |
| 279 |
|
| 280 |
network: Network | None |
| 281 |
|
| 282 |
def _configure_hcloud_client(self): |
| 283 |
api_token = self.get_option("api_token") |
| 284 |
api_endpoint = self.get_option("api_endpoint") |
| 285 |
|
| 286 |
# Resolve template string |
| 287 |
api_token = self.templar.template(api_token) |
| 288 |
|
| 289 |
self.client = Client( |
| 290 |
token=api_token, |
| 291 |
api_endpoint=api_endpoint, |
| 292 |
application_name="ansible-inventory", |
| 293 |
application_version=version, |
| 294 |
) |
| 295 |
|
| 296 |
try: |
| 297 |
# Ensure the api token is valid |
| 298 |
self.client.locations.get_list() |
| 299 |
except APIException as exception: |
| 300 |
raise AnsibleError("Invalid Hetzner Cloud API Token.") from exception |
| 301 |
|
| 302 |
def _validate_options(self) -> None: |
| 303 |
if self.get_option("network"): |
| 304 |
network_param: str = self.get_option("network") |
| 305 |
network_param = self.templar.template(network_param) |
| 306 |
|
| 307 |
try: |
| 308 |
self.network = client_get_by_name_or_id(self.client, "networks", network_param) |
| 309 |
except (ClientException, APIException) as exception: |
| 310 |
raise AnsibleError(to_native(exception)) from exception |
| 311 |
|
| 312 |
def _fetch_servers(self) -> list[Server]: |
| 313 |
self._validate_options() |
| 314 |
|
| 315 |
get_servers_params = {} |
| 316 |
if self.get_option("label_selector"): |
| 317 |
get_servers_params["label_selector"] = self.get_option("label_selector") |
| 318 |
|
| 319 |
if self.get_option("status"): |
| 320 |
get_servers_params["status"] = self.get_option("status") |
| 321 |
|
| 322 |
servers = self.client.servers.get_all(**get_servers_params) |
| 323 |
|
| 324 |
if self.get_option("network"): |
| 325 |
servers = [s for s in servers if self.network.id in [p.network.id for p in s.private_net]] |
| 326 |
|
| 327 |
if self.get_option("locations"): |
| 328 |
locations: list[str] = self.get_option("locations") |
| 329 |
servers = [s for s in servers if s.location.name in locations] |
| 330 |
|
| 331 |
if self.get_option("types"): |
| 332 |
server_types: list[str] = self.get_option("types") |
| 333 |
servers = [s for s in servers if s.server_type.name in server_types] |
| 334 |
|
| 335 |
if self.get_option("images"): |
| 336 |
images: list[str] = self.get_option("images") |
| 337 |
servers = [s for s in servers if s.image is not None and s.image.os_flavor in images] |
| 338 |
|
| 339 |
return servers |
| 340 |
|
| 341 |
def _build_inventory_server(self, server: Server) -> InventoryServer: |
| 342 |
server_dict: InventoryServer = {} |
| 343 |
server_dict["id"] = server.id |
| 344 |
server_dict["name"] = server.name |
| 345 |
server_dict["status"] = server.status |
| 346 |
|
| 347 |
# Server Type |
| 348 |
server_dict["type"] = server.server_type.name |
| 349 |
server_dict["server_type"] = server.server_type.name |
| 350 |
server_dict["architecture"] = server.server_type.architecture |
| 351 |
|
| 352 |
# Network |
| 353 |
if server.public_net.ipv4: |
| 354 |
server_dict["ipv4"] = server.public_net.ipv4.ip |
| 355 |
|
| 356 |
if server.public_net.ipv6: |
| 357 |
server_dict["ipv6"] = first_ipv6_address(server.public_net.ipv6.ip) |
| 358 |
server_dict["ipv6_network"] = server.public_net.ipv6.network |
| 359 |
server_dict["ipv6_network_mask"] = server.public_net.ipv6.network_mask |
| 360 |
|
| 361 |
server_dict["private_networks"] = [ |
| 362 |
{"id": v.network.id, "name": v.network.name, "ip": v.ip} for v in server.private_net |
| 363 |
] |
| 364 |
|
| 365 |
if self.get_option("network"): |
| 366 |
for private_net in server.private_net: |
| 367 |
# Set private_ipv4 if user filtered for one network |
| 368 |
if private_net.network.id == self.network.id: |
| 369 |
server_dict["private_ipv4"] = private_net.ip |
| 370 |
break |
| 371 |
|
| 372 |
# Location |
| 373 |
server_dict["location"] = server.location.name |
| 374 |
with warnings.catch_warnings(): |
| 375 |
warnings.simplefilter("ignore", category=DeprecationWarning) |
| 376 |
self.display.warning( |
| 377 |
"The `hcloud_datacenter` variable is deprecated and will be removed " |
| 378 |
"after 1 July 2026. Please use the `hcloud_location` variable instead. " |
| 379 |
"See https://docs.hetzner.cloud/changelog#2025-12-16-phasing-out-datacenters." |
| 380 |
) |
| 381 |
server_dict["datacenter"] = server.datacenter and server.datacenter.name |
| 382 |
|
| 383 |
# Image |
| 384 |
if server.image is not None: |
| 385 |
server_dict["image_id"] = server.image.id |
| 386 |
server_dict["image_os_flavor"] = server.image.os_flavor |
| 387 |
server_dict["image_name"] = server.image.name or server.image.description |
| 388 |
|
| 389 |
# Labels |
| 390 |
server_dict["labels"] = dict(server.labels) |
| 391 |
|
| 392 |
try: |
| 393 |
server_dict["ansible_host"] = self._get_server_ansible_host(server) |
| 394 |
except AnsibleError as exception: |
| 395 |
# Log warning that for this host can not be connected to, using the |
| 396 |
# method specified in 'connect_with'. Users might use 'compose' to |
| 397 |
# override the connection method, or implement custom logic, so we |
| 398 |
# do not need to abort if nothing matched. |
| 399 |
self.display.v(f"[hcloud] {exception}", server.name) |
| 400 |
|
| 401 |
return server_dict |
| 402 |
|
| 403 |
def _get_server_ansible_host(self, server: Server): |
| 404 |
if self.get_option("connect_with") == "public_ipv4": |
| 405 |
if server.public_net.ipv4: |
| 406 |
return server.public_net.ipv4.ip |
| 407 |
raise AnsibleError("Server has no public ipv4, but connect_with=public_ipv4 was specified") |
| 408 |
|
| 409 |
if self.get_option("connect_with") == "public_ipv6": |
| 410 |
if server.public_net.ipv6: |
| 411 |
return first_ipv6_address(server.public_net.ipv6.ip) |
| 412 |
raise AnsibleError("Server has no public ipv6, but connect_with=public_ipv6 was specified") |
| 413 |
|
| 414 |
if self.get_option("connect_with") == "hostname": |
| 415 |
# every server has a name, no need to guard this |
| 416 |
return server.name |
| 417 |
|
| 418 |
if self.get_option("connect_with") == "ipv4_dns_ptr": |
| 419 |
if server.public_net.ipv4: |
| 420 |
return server.public_net.ipv4.dns_ptr |
| 421 |
raise AnsibleError("Server has no public ipv4, but connect_with=ipv4_dns_ptr was specified") |
| 422 |
|
| 423 |
if self.get_option("connect_with") == "private_ipv4": |
| 424 |
if self.get_option("network"): |
| 425 |
for private_net in server.private_net: |
| 426 |
if private_net.network.id == self.network.id: |
| 427 |
return private_net.ip |
| 428 |
|
| 429 |
else: |
| 430 |
raise AnsibleError("You can only connect via private IPv4 if you specify a network") |
| 431 |
|
| 432 |
def verify_file(self, path): |
| 433 |
"""Return the possibly of a file being consumable by this plugin.""" |
| 434 |
return super().verify_file(path) and path.endswith(("hcloud.yaml", "hcloud.yml")) |
| 435 |
|
| 436 |
def _get_cached_result(self, path, cache) -> tuple[list[InventoryServer], bool]: |
| 437 |
# false when refresh_cache or --flush-cache is used |
| 438 |
if not cache: |
| 439 |
return [], False |
| 440 |
|
| 441 |
# get the user-specified directive |
| 442 |
if not self.get_option("cache"): |
| 443 |
return [], False |
| 444 |
|
| 445 |
cache_key = self.get_cache_key(path) |
| 446 |
try: |
| 447 |
cached_result = self._cache[cache_key] |
| 448 |
except KeyError: |
| 449 |
# if cache expires or cache file doesn"t exist |
| 450 |
return [], False |
| 451 |
|
| 452 |
return cached_result, True |
| 453 |
|
| 454 |
def _update_cached_result(self, path, cache, result: list[InventoryServer]): |
| 455 |
if not self.get_option("cache"): |
| 456 |
return |
| 457 |
|
| 458 |
cache_key = self.get_cache_key(path) |
| 459 |
# We weren't explicitly told to flush the cache, and there's already a cache entry, |
| 460 |
# this means that the result we're being passed came from the cache. As such we don't |
| 461 |
# want to "update" the cache as that could reset a TTL on the cache entry. |
| 462 |
if cache and cache_key in self._cache: |
| 463 |
return |
| 464 |
|
| 465 |
self._cache[cache_key] = result |
| 466 |
|
| 467 |
def parse(self, inventory, loader, path, cache=True): |
| 468 |
super().parse(inventory, loader, path, cache) |
| 469 |
|
| 470 |
try: |
| 471 |
client_check_required_lib() |
| 472 |
except ClientException as exception: |
| 473 |
raise AnsibleError(to_native(exception)) from exception |
| 474 |
|
| 475 |
# Allow using extra variables arguments as template variables (e.g. |
| 476 |
# '--extra-vars my_var=my_value') |
| 477 |
self.templar.available_variables = self._vars |
| 478 |
|
| 479 |
self._read_config_data(path) |
| 480 |
self._configure_hcloud_client() |
| 481 |
|
| 482 |
servers, cached = self._get_cached_result(path, cache) |
| 483 |
if not cached: |
| 484 |
with self.client.cached_session(): |
| 485 |
servers = [self._build_inventory_server(s) for s in self._fetch_servers()] |
| 486 |
|
| 487 |
# Add a top group |
| 488 |
self.inventory.add_group(group=self.get_option("group")) |
| 489 |
|
| 490 |
hostvars_prefix = self.get_option("hostvars_prefix") |
| 491 |
hostvars_suffix = self.get_option("hostvars_suffix") |
| 492 |
hostname_template = self.get_option("hostname") |
| 493 |
|
| 494 |
for server in servers: |
| 495 |
hostvars = {} |
| 496 |
for key, value in server.items(): |
| 497 |
# Add hostvars prefix and suffix for variables coming from the Hetzner Cloud. |
| 498 |
if hostvars_prefix or hostvars_suffix: |
| 499 |
if key not in ("ansible_host",): |
| 500 |
if hostvars_prefix: |
| 501 |
key = hostvars_prefix + key |
| 502 |
if hostvars_suffix: |
| 503 |
key = key + hostvars_suffix |
| 504 |
|
| 505 |
hostvars[key] = value |
| 506 |
|
| 507 |
if hostname_template: |
| 508 |
templar = self.templar |
| 509 |
templar.available_variables = combine_vars(hostvars, self._vars) |
| 510 |
hostname = templar.template(hostname_template) |
| 511 |
else: |
| 512 |
hostname = server["name"] |
| 513 |
|
| 514 |
self.inventory.add_host(hostname, group=self.get_option("group")) |
| 515 |
for key, value in hostvars.items(): |
| 516 |
self.inventory.set_variable(hostname, key, value) |
| 517 |
|
| 518 |
# Use constructed if applicable |
| 519 |
strict = self.get_option("strict") |
| 520 |
|
| 521 |
# Composed variables |
| 522 |
self._set_composite_vars( |
| 523 |
self.get_option("compose"), |
| 524 |
self.inventory.get_host(hostname).get_vars(), |
| 525 |
hostname, |
| 526 |
strict=strict, |
| 527 |
) |
| 528 |
|
| 529 |
# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group |
| 530 |
self._add_host_to_composed_groups( |
| 531 |
self.get_option("groups"), |
| 532 |
{}, |
| 533 |
hostname, |
| 534 |
strict=strict, |
| 535 |
) |
| 536 |
|
| 537 |
# Create groups based on variable values and add the corresponding hosts to it |
| 538 |
self._add_host_to_keyed_groups( |
| 539 |
self.get_option("keyed_groups"), |
| 540 |
{}, |
| 541 |
hostname, |
| 542 |
strict=strict, |
| 543 |
) |
| 544 |
|
| 545 |
self._update_cached_result(path, cache, servers) |