| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2019 Piotr Wojciechowski <[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 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: docker_node |
| 11 |
short_description: Manage Docker Swarm node |
| 12 |
description: |
| 13 |
- Manages the Docker nodes through a Swarm Manager. |
| 14 |
- This module allows to change the node's role, its availability, and to modify, add or remove node labels. |
| 15 |
extends_documentation_fragment: |
| 16 |
- community.docker._docker |
| 17 |
- community.docker._docker.docker_py_2_documentation |
| 18 |
- community.docker._attributes |
| 19 |
- community.docker._attributes.actiongroup_docker |
| 20 |
|
| 21 |
attributes: |
| 22 |
check_mode: |
| 23 |
support: full |
| 24 |
diff_mode: |
| 25 |
support: none |
| 26 |
idempotent: |
| 27 |
support: full |
| 28 |
|
| 29 |
options: |
| 30 |
hostname: |
| 31 |
description: |
| 32 |
- The hostname or ID of node as registered in Swarm. |
| 33 |
- If more than one node is registered using the same hostname the ID must be used, otherwise module will fail. |
| 34 |
type: str |
| 35 |
required: true |
| 36 |
labels: |
| 37 |
description: |
| 38 |
- User-defined key/value metadata that will be assigned as node attribute. |
| 39 |
- Label operations in this module apply to the docker swarm node specified by O(hostname). Use M(community.docker.docker_swarm) |
| 40 |
module to add/modify/remove swarm cluster labels. |
| 41 |
- The actual state of labels assigned to the node when module completes its work depends on O(labels_state) and O(labels_to_remove) |
| 42 |
parameters values. See description below. |
| 43 |
type: dict |
| 44 |
labels_state: |
| 45 |
description: |
| 46 |
- It defines the operation on the labels assigned to node and labels specified in O(labels) option. |
| 47 |
- Set to V(merge) to combine labels provided in O(labels) with those already assigned to the node. If no labels are |
| 48 |
assigned then it will add listed labels. For labels that are already assigned to the node, it will update their values. |
| 49 |
The labels not specified in O(labels) will remain unchanged. If O(labels) is empty then no changes will be made. |
| 50 |
- Set to V(replace) to replace all assigned labels with provided ones. If O(labels) is empty then all labels assigned |
| 51 |
to the node will be removed. |
| 52 |
type: str |
| 53 |
default: 'merge' |
| 54 |
choices: |
| 55 |
- merge |
| 56 |
- replace |
| 57 |
labels_to_remove: |
| 58 |
description: |
| 59 |
- List of labels that will be removed from the node configuration. The list has to contain only label names, not their |
| 60 |
values. |
| 61 |
- If the label provided on the list is not assigned to the node, the entry is ignored. |
| 62 |
- If the label is both on the O(labels_to_remove) and O(labels), then value provided in O(labels) remains assigned to |
| 63 |
the node. |
| 64 |
- If O(labels_state=replace) and O(labels) is not provided or empty then all labels assigned to node are removed and |
| 65 |
O(labels_to_remove) is ignored. |
| 66 |
type: list |
| 67 |
elements: str |
| 68 |
availability: |
| 69 |
description: Node availability to assign. If not provided then node availability remains unchanged. |
| 70 |
choices: |
| 71 |
- active |
| 72 |
- pause |
| 73 |
- drain |
| 74 |
type: str |
| 75 |
role: |
| 76 |
description: Node role to assign. If not provided then node role remains unchanged. |
| 77 |
choices: |
| 78 |
- manager |
| 79 |
- worker |
| 80 |
type: str |
| 81 |
|
| 82 |
requirements: |
| 83 |
- "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 2.4.0" |
| 84 |
- Docker API >= 1.25 |
| 85 |
author: |
| 86 |
- Piotr Wojciechowski (@WojciechowskiPiotr) |
| 87 |
- Thierry Bouvet (@tbouvet) |
| 88 |
""" |
| 89 |
|
| 90 |
EXAMPLES = r""" |
| 91 |
--- |
| 92 |
- name: Set node role |
| 93 |
community.docker.docker_node: |
| 94 |
hostname: mynode |
| 95 |
role: manager |
| 96 |
|
| 97 |
- name: Set node availability |
| 98 |
community.docker.docker_node: |
| 99 |
hostname: mynode |
| 100 |
availability: drain |
| 101 |
|
| 102 |
- name: Replace node labels with new labels |
| 103 |
community.docker.docker_node: |
| 104 |
hostname: mynode |
| 105 |
labels: |
| 106 |
key: value |
| 107 |
labels_state: replace |
| 108 |
|
| 109 |
- name: Merge node labels and new labels |
| 110 |
community.docker.docker_node: |
| 111 |
hostname: mynode |
| 112 |
labels: |
| 113 |
key: value |
| 114 |
|
| 115 |
- name: Remove all labels assigned to node |
| 116 |
community.docker.docker_node: |
| 117 |
hostname: mynode |
| 118 |
labels_state: replace |
| 119 |
|
| 120 |
- name: Remove selected labels from the node |
| 121 |
community.docker.docker_node: |
| 122 |
hostname: mynode |
| 123 |
labels_to_remove: |
| 124 |
- key1 |
| 125 |
- key2 |
| 126 |
""" |
| 127 |
|
| 128 |
RETURN = r""" |
| 129 |
node: |
| 130 |
description: Information about node after 'update' operation. |
| 131 |
returned: success |
| 132 |
type: dict |
| 133 |
""" |
| 134 |
|
| 135 |
import traceback |
| 136 |
import typing as t |
| 137 |
|
| 138 |
try: |
| 139 |
from docker.errors import APIError, DockerException |
| 140 |
except ImportError: |
| 141 |
# missing Docker SDK for Python handled in ansible.module_utils.docker.common |
| 142 |
pass |
| 143 |
|
| 144 |
from ansible.module_utils.common.text.converters import to_text |
| 145 |
|
| 146 |
from ansible_collections.community.docker.plugins.module_utils._common import ( |
| 147 |
RequestException, |
| 148 |
) |
| 149 |
from ansible_collections.community.docker.plugins.module_utils._swarm import ( |
| 150 |
AnsibleDockerSwarmClient, |
| 151 |
) |
| 152 |
from ansible_collections.community.docker.plugins.module_utils._util import ( |
| 153 |
DockerBaseClass, |
| 154 |
sanitize_labels, |
| 155 |
) |
| 156 |
|
| 157 |
|
| 158 |
class TaskParameters(DockerBaseClass): |
| 159 |
hostname: str |
| 160 |
|
| 161 |
def __init__(self, client: AnsibleDockerSwarmClient) -> None: |
| 162 |
super().__init__() |
| 163 |
|
| 164 |
# Spec |
| 165 |
self.labels: dict[str, t.Any] | None = None |
| 166 |
self.labels_state: t.Literal["merge", "replace"] = "merge" |
| 167 |
self.labels_to_remove: list[str] | None = None |
| 168 |
|
| 169 |
# Node |
| 170 |
self.availability: t.Literal["active", "pause", "drain"] | None = None |
| 171 |
self.role: t.Literal["worker", "manager"] | None = None |
| 172 |
|
| 173 |
for key, value in client.module.params.items(): |
| 174 |
setattr(self, key, value) |
| 175 |
|
| 176 |
sanitize_labels(self.labels, "labels", client) |
| 177 |
|
| 178 |
|
| 179 |
class SwarmNodeManager(DockerBaseClass): |
| 180 |
def __init__( |
| 181 |
self, client: AnsibleDockerSwarmClient, results: dict[str, t.Any] |
| 182 |
) -> None: |
| 183 |
super().__init__() |
| 184 |
|
| 185 |
self.client = client |
| 186 |
self.results = results |
| 187 |
self.check_mode = self.client.check_mode |
| 188 |
|
| 189 |
self.client.fail_task_if_not_swarm_manager() |
| 190 |
|
| 191 |
self.parameters = TaskParameters(client) |
| 192 |
|
| 193 |
self.node_update() |
| 194 |
|
| 195 |
def node_update(self) -> None: |
| 196 |
if not (self.client.check_if_swarm_node(node_id=self.parameters.hostname)): |
| 197 |
self.client.fail("This node is not part of a swarm.") |
| 198 |
|
| 199 |
if self.client.check_if_swarm_node_is_down(): |
| 200 |
self.client.fail("Can not update the node. The node is down.") |
| 201 |
|
| 202 |
try: |
| 203 |
node_info = self.client.inspect_node(node_id=self.parameters.hostname) |
| 204 |
except APIError as exc: |
| 205 |
self.client.fail(f"Failed to get node information for {exc}") |
| 206 |
|
| 207 |
changed = False |
| 208 |
node_spec: dict[str, t.Any] = { |
| 209 |
"Availability": self.parameters.availability, |
| 210 |
"Role": self.parameters.role, |
| 211 |
"Labels": self.parameters.labels, |
| 212 |
} |
| 213 |
|
| 214 |
if self.parameters.role is None: |
| 215 |
node_spec["Role"] = node_info["Spec"]["Role"] |
| 216 |
else: |
| 217 |
if node_info["Spec"]["Role"] != self.parameters.role: |
| 218 |
node_spec["Role"] = self.parameters.role |
| 219 |
changed = True |
| 220 |
|
| 221 |
if self.parameters.availability is None: |
| 222 |
node_spec["Availability"] = node_info["Spec"]["Availability"] |
| 223 |
else: |
| 224 |
if node_info["Spec"]["Availability"] != self.parameters.availability: |
| 225 |
node_info["Spec"]["Availability"] = self.parameters.availability |
| 226 |
changed = True |
| 227 |
|
| 228 |
if self.parameters.labels_state == "replace": |
| 229 |
if self.parameters.labels is None: |
| 230 |
node_spec["Labels"] = {} |
| 231 |
if node_info["Spec"]["Labels"]: |
| 232 |
changed = True |
| 233 |
else: |
| 234 |
if (node_info["Spec"]["Labels"] or {}) != self.parameters.labels: |
| 235 |
node_spec["Labels"] = self.parameters.labels |
| 236 |
changed = True |
| 237 |
elif self.parameters.labels_state == "merge": |
| 238 |
labels: dict[str, str] = dict(node_info["Spec"]["Labels"] or {}) |
| 239 |
node_spec["Labels"] = labels |
| 240 |
if self.parameters.labels is not None: |
| 241 |
for key, value in self.parameters.labels.items(): |
| 242 |
if labels.get(key) != value: |
| 243 |
labels[key] = value |
| 244 |
changed = True |
| 245 |
|
| 246 |
if self.parameters.labels_to_remove is not None: |
| 247 |
for key in self.parameters.labels_to_remove: |
| 248 |
if self.parameters.labels is not None: |
| 249 |
if not self.parameters.labels.get(key): |
| 250 |
if node_spec["Labels"].get(key): |
| 251 |
node_spec["Labels"].pop(key) |
| 252 |
changed = True |
| 253 |
else: |
| 254 |
self.client.module.warn( |
| 255 |
f"Label '{to_text(key)}' listed both in 'labels' and 'labels_to_remove'. " |
| 256 |
"Keeping the assigned label value." |
| 257 |
) |
| 258 |
else: |
| 259 |
if node_spec["Labels"].get(key): |
| 260 |
node_spec["Labels"].pop(key) |
| 261 |
changed = True |
| 262 |
|
| 263 |
if changed is True: |
| 264 |
if not self.check_mode: |
| 265 |
try: |
| 266 |
self.client.update_node( |
| 267 |
node_id=node_info["ID"], |
| 268 |
version=node_info["Version"]["Index"], |
| 269 |
node_spec=node_spec, |
| 270 |
) |
| 271 |
except APIError as exc: |
| 272 |
self.client.fail(f"Failed to update node : {exc}") |
| 273 |
self.results["node"] = self.client.get_node_inspect(node_id=node_info["ID"]) |
| 274 |
self.results["changed"] = changed |
| 275 |
else: |
| 276 |
self.results["node"] = node_info |
| 277 |
self.results["changed"] = changed |
| 278 |
|
| 279 |
|
| 280 |
def main() -> None: |
| 281 |
argument_spec = { |
| 282 |
"hostname": {"type": "str", "required": True}, |
| 283 |
"labels": {"type": "dict"}, |
| 284 |
"labels_state": { |
| 285 |
"type": "str", |
| 286 |
"default": "merge", |
| 287 |
"choices": ["merge", "replace"], |
| 288 |
}, |
| 289 |
"labels_to_remove": {"type": "list", "elements": "str"}, |
| 290 |
"availability": {"type": "str", "choices": ["active", "pause", "drain"]}, |
| 291 |
"role": {"type": "str", "choices": ["worker", "manager"]}, |
| 292 |
} |
| 293 |
|
| 294 |
client = AnsibleDockerSwarmClient( |
| 295 |
argument_spec=argument_spec, |
| 296 |
supports_check_mode=True, |
| 297 |
min_docker_version="2.4.0", |
| 298 |
) |
| 299 |
|
| 300 |
try: |
| 301 |
results = { |
| 302 |
"changed": False, |
| 303 |
} |
| 304 |
|
| 305 |
SwarmNodeManager(client, results) |
| 306 |
client.module.exit_json(**results) |
| 307 |
except DockerException as e: |
| 308 |
client.fail( |
| 309 |
f"An unexpected Docker error occurred: {e}", |
| 310 |
exception=traceback.format_exc(), |
| 311 |
) |
| 312 |
except RequestException as e: |
| 313 |
client.fail( |
| 314 |
f"An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}", |
| 315 |
exception=traceback.format_exc(), |
| 316 |
) |
| 317 |
|
| 318 |
|
| 319 |
if __name__ == "__main__": |
| 320 |
main() |