| 1 |
# Copyright (c) 2017 Ansible Project |
| 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: linode |
| 9 |
author: |
| 10 |
- Luke Murphy (@decentral1se) |
| 11 |
short_description: Ansible dynamic inventory plugin for Linode |
| 12 |
requirements: |
| 13 |
- linode_api4 >= 2.0.0 |
| 14 |
description: |
| 15 |
- Reads inventories from the Linode API v4. |
| 16 |
- Uses a YAML configuration file that ends with linode.(yml|yaml). |
| 17 |
- Linode labels are used by default as the hostnames. |
| 18 |
- The default inventory groups are built from groups (deprecated by Linode) and not tags. |
| 19 |
extends_documentation_fragment: |
| 20 |
- ansible.builtin.constructed |
| 21 |
- ansible.builtin.inventory_cache |
| 22 |
options: |
| 23 |
cache: |
| 24 |
version_added: 4.5.0 |
| 25 |
cache_plugin: |
| 26 |
version_added: 4.5.0 |
| 27 |
cache_timeout: |
| 28 |
version_added: 4.5.0 |
| 29 |
cache_connection: |
| 30 |
version_added: 4.5.0 |
| 31 |
cache_prefix: |
| 32 |
version_added: 4.5.0 |
| 33 |
plugin: |
| 34 |
description: Marks this as an instance of the 'linode' plugin. |
| 35 |
type: string |
| 36 |
required: true |
| 37 |
choices: ['linode', 'community.general.linode'] |
| 38 |
ip_style: |
| 39 |
description: Populate hostvars with all information available from the Linode APIv4. |
| 40 |
type: string |
| 41 |
default: plain |
| 42 |
choices: |
| 43 |
- plain |
| 44 |
- api |
| 45 |
version_added: 3.6.0 |
| 46 |
access_token: |
| 47 |
description: The Linode account personal access token. |
| 48 |
type: string |
| 49 |
required: true |
| 50 |
env: |
| 51 |
- name: LINODE_ACCESS_TOKEN |
| 52 |
regions: |
| 53 |
description: Populate inventory with instances in this region. |
| 54 |
default: [] |
| 55 |
type: list |
| 56 |
elements: string |
| 57 |
tags: |
| 58 |
description: Populate inventory only with instances which have at least one of the tags listed here. |
| 59 |
default: [] |
| 60 |
type: list |
| 61 |
elements: string |
| 62 |
version_added: 2.0.0 |
| 63 |
types: |
| 64 |
description: Populate inventory with instances with this type. |
| 65 |
default: [] |
| 66 |
type: list |
| 67 |
elements: string |
| 68 |
strict: |
| 69 |
version_added: 2.0.0 |
| 70 |
compose: |
| 71 |
version_added: 2.0.0 |
| 72 |
groups: |
| 73 |
version_added: 2.0.0 |
| 74 |
keyed_groups: |
| 75 |
version_added: 2.0.0 |
| 76 |
""" |
| 77 |
|
| 78 |
EXAMPLES = r""" |
| 79 |
--- |
| 80 |
# Minimal example. `LINODE_ACCESS_TOKEN` is exposed in environment. |
| 81 |
plugin: community.general.linode |
| 82 |
|
| 83 |
--- |
| 84 |
# You can use Jinja to template the access token. |
| 85 |
plugin: community.general.linode |
| 86 |
access_token: "{{ lookup('ini', 'token', section='your_username', file='~/.config/linode-cli') }}" |
| 87 |
# For older Ansible versions, you need to write this as: |
| 88 |
# access_token: "{{ lookup('ini', 'token section=your_username file=~/.config/linode-cli') }}" |
| 89 |
|
| 90 |
--- |
| 91 |
# Example with regions, types, groups and access token |
| 92 |
plugin: community.general.linode |
| 93 |
access_token: foobar |
| 94 |
regions: |
| 95 |
- eu-west |
| 96 |
types: |
| 97 |
- g5-standard-2 |
| 98 |
|
| 99 |
--- |
| 100 |
# Example with keyed_groups, groups, and compose |
| 101 |
plugin: community.general.linode |
| 102 |
access_token: foobar |
| 103 |
keyed_groups: |
| 104 |
- key: tags |
| 105 |
separator: '' |
| 106 |
- key: region |
| 107 |
prefix: region |
| 108 |
groups: |
| 109 |
webservers: "'web' in (tags|list)" |
| 110 |
mailservers: "'mail' in (tags|list)" |
| 111 |
compose: |
| 112 |
# By default, Ansible tries to connect to the label of the instance. |
| 113 |
# Since that might not be a valid name to connect to, you can |
| 114 |
# replace it with the first IPv4 address of the linode as follows: |
| 115 |
ansible_ssh_host: ipv4[0] |
| 116 |
ansible_port: 2222 |
| 117 |
|
| 118 |
--- |
| 119 |
# Example where control traffic limited to internal network |
| 120 |
plugin: community.general.linode |
| 121 |
access_token: foobar |
| 122 |
ip_style: api |
| 123 |
compose: |
| 124 |
ansible_host: "ipv4 | community.general.json_query('[?public==`false`].address') | first" |
| 125 |
""" |
| 126 |
|
| 127 |
from ansible.errors import AnsibleError |
| 128 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable |
| 129 |
|
| 130 |
from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe |
| 131 |
|
| 132 |
try: |
| 133 |
from linode_api4 import LinodeClient |
| 134 |
from linode_api4.errors import ApiError as LinodeApiError |
| 135 |
from linode_api4.objects.linode import Instance |
| 136 |
|
| 137 |
HAS_LINODE = True |
| 138 |
except ImportError: |
| 139 |
HAS_LINODE = False |
| 140 |
|
| 141 |
|
| 142 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 143 |
NAME = "community.general.linode" |
| 144 |
|
| 145 |
def _build_client(self, loader): |
| 146 |
"""Build the Linode client.""" |
| 147 |
|
| 148 |
access_token = self.get_option("access_token") |
| 149 |
if self.templar.is_template(access_token): |
| 150 |
access_token = self.templar.template(variable=access_token) |
| 151 |
|
| 152 |
if access_token is None: |
| 153 |
raise AnsibleError("Could not retrieve Linode access token from plugin configuration sources") |
| 154 |
|
| 155 |
self.client = LinodeClient(access_token) |
| 156 |
|
| 157 |
def _get_instances_inventory(self): |
| 158 |
"""Retrieve Linode instance information from cloud inventory.""" |
| 159 |
try: |
| 160 |
self.instances = self.client.linode.instances() |
| 161 |
except LinodeApiError as exception: |
| 162 |
raise AnsibleError(f"Linode client raised: {exception}") from exception |
| 163 |
|
| 164 |
def _add_groups(self): |
| 165 |
"""Add Linode instance groups to the dynamic inventory.""" |
| 166 |
self.linode_groups = {instance.group for instance in self.instances if instance.group} |
| 167 |
|
| 168 |
for linode_group in self.linode_groups: |
| 169 |
self.inventory.add_group(linode_group) |
| 170 |
|
| 171 |
def _filter_by_config(self): |
| 172 |
"""Filter instances by user specified configuration.""" |
| 173 |
regions = self.get_option("regions") |
| 174 |
if regions: |
| 175 |
self.instances = [instance for instance in self.instances if instance.region.id in regions] |
| 176 |
|
| 177 |
types = self.get_option("types") |
| 178 |
if types: |
| 179 |
self.instances = [instance for instance in self.instances if instance.type.id in types] |
| 180 |
|
| 181 |
tags = self.get_option("tags") |
| 182 |
if tags: |
| 183 |
self.instances = [instance for instance in self.instances if any(tag in instance.tags for tag in tags)] |
| 184 |
|
| 185 |
def _add_instances_to_groups(self): |
| 186 |
"""Add instance names to their dynamic inventory groups.""" |
| 187 |
for instance in self.instances: |
| 188 |
self.inventory.add_host(make_unsafe(instance.label), group=instance.group) |
| 189 |
|
| 190 |
def _add_hostvars_for_instances(self): |
| 191 |
"""Add hostvars for instances in the dynamic inventory.""" |
| 192 |
ip_style = self.get_option("ip_style") |
| 193 |
for instance in self.instances: |
| 194 |
hostvars = instance._raw_json |
| 195 |
hostname = make_unsafe(instance.label) |
| 196 |
for hostvar_key in hostvars: |
| 197 |
if ip_style == "api" and hostvar_key in ["ipv4", "ipv6"]: |
| 198 |
continue |
| 199 |
self.inventory.set_variable(hostname, hostvar_key, make_unsafe(hostvars[hostvar_key])) |
| 200 |
if ip_style == "api": |
| 201 |
ips = instance.ips.ipv4.public + instance.ips.ipv4.private |
| 202 |
ips += [instance.ips.ipv6.slaac, instance.ips.ipv6.link_local] |
| 203 |
ips += instance.ips.ipv6.pools |
| 204 |
|
| 205 |
for ip_type in {ip.type for ip in ips}: |
| 206 |
self.inventory.set_variable( |
| 207 |
hostname, ip_type, make_unsafe(self._ip_data([ip for ip in ips if ip.type == ip_type])) |
| 208 |
) |
| 209 |
|
| 210 |
def _ip_data(self, ip_list): |
| 211 |
data = [] |
| 212 |
for ip in list(ip_list): |
| 213 |
data.append( |
| 214 |
{ |
| 215 |
"address": ip.address, |
| 216 |
"subnet_mask": ip.subnet_mask, |
| 217 |
"gateway": ip.gateway, |
| 218 |
"public": ip.public, |
| 219 |
"prefix": ip.prefix, |
| 220 |
"rdns": ip.rdns, |
| 221 |
"type": ip.type, |
| 222 |
} |
| 223 |
) |
| 224 |
return data |
| 225 |
|
| 226 |
def _cacheable_inventory(self): |
| 227 |
return [i._raw_json for i in self.instances] |
| 228 |
|
| 229 |
def populate(self): |
| 230 |
strict = self.get_option("strict") |
| 231 |
|
| 232 |
self._filter_by_config() |
| 233 |
|
| 234 |
self._add_groups() |
| 235 |
self._add_instances_to_groups() |
| 236 |
self._add_hostvars_for_instances() |
| 237 |
for instance in self.instances: |
| 238 |
hostname = make_unsafe(instance.label) |
| 239 |
variables = self.inventory.get_host(hostname).get_vars() |
| 240 |
self._add_host_to_composed_groups(self.get_option("groups"), variables, hostname, strict=strict) |
| 241 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), variables, hostname, strict=strict) |
| 242 |
self._set_composite_vars(self.get_option("compose"), variables, hostname, strict=strict) |
| 243 |
|
| 244 |
def verify_file(self, path): |
| 245 |
"""Verify the Linode configuration file. |
| 246 |
|
| 247 |
Return true/false if the config-file is valid for this plugin |
| 248 |
|
| 249 |
Args: |
| 250 |
str(path): path to the config |
| 251 |
Kwargs: |
| 252 |
None |
| 253 |
Raises: |
| 254 |
None |
| 255 |
Returns: |
| 256 |
bool(valid): is valid config file""" |
| 257 |
valid = False |
| 258 |
if super().verify_file(path): |
| 259 |
if path.endswith(("linode.yaml", "linode.yml")): |
| 260 |
valid = True |
| 261 |
else: |
| 262 |
self.display.vvv('Inventory source not ending in "linode.yaml" or "linode.yml"') |
| 263 |
return valid |
| 264 |
|
| 265 |
def parse(self, inventory, loader, path, cache=True): |
| 266 |
"""Dynamically parse Linode the cloud inventory.""" |
| 267 |
super().parse(inventory, loader, path) |
| 268 |
self.instances = None |
| 269 |
|
| 270 |
if not HAS_LINODE: |
| 271 |
raise AnsibleError("the Linode dynamic inventory plugin requires linode_api4.") |
| 272 |
|
| 273 |
self._read_config_data(path) |
| 274 |
|
| 275 |
cache_key = self.get_cache_key(path) |
| 276 |
|
| 277 |
if cache: |
| 278 |
cache = self.get_option("cache") |
| 279 |
|
| 280 |
update_cache = False |
| 281 |
if cache: |
| 282 |
try: |
| 283 |
self.instances = [Instance(None, i["id"], i) for i in self._cache[cache_key]] |
| 284 |
except KeyError: |
| 285 |
update_cache = True |
| 286 |
|
| 287 |
# Check for None rather than False in order to allow |
| 288 |
# for empty sets of cached instances |
| 289 |
if self.instances is None: |
| 290 |
self._build_client(loader) |
| 291 |
self._get_instances_inventory() |
| 292 |
|
| 293 |
if update_cache: |
| 294 |
self._cache[cache_key] = self._cacheable_inventory() |
| 295 |
|
| 296 |
self.populate() |