Debian Codegraph @

ansible_collections/community/proxmox/plugins/modules/proxmox_cluster_ha_rules.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2025, Reto Kupferschmid <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-FileCopyrightText: (c) 2025, Reto Kupferschmid <[email protected]>
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8
9 DOCUMENTATION = r"""
10 ---
11 module: proxmox_cluster_ha_rules
12
13 short_description: Management of HA rules
14
15 version_added: 1.4.0
16
17 description:
18 - Configure ha rules C(/cluster/ha/rules).
19
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: full
25
26 options:
27 affinity:
28 description: |
29 Describes whether the HA resource are supposed to be kept on the same node V(positive),
30 or are supposed to be kept on separate nodes V(negative).
31 Required if O(type=resource-affinity).
32 required: false
33 choices: ['positive', 'negative']
34 type: str
35 comment:
36 description: Description
37 required: false
38 type: str
39 disable:
40 description: Whether the HA rule is disabled. If not specified, the Proxmox API default C(false) will be used.
41 required: false
42 type: bool
43 force:
44 description: |
45 Existing rules with a specific O(type) can not be changed to the other type.
46 If V(force=true), the existing rule will be deleted and recreated with the new type.
47 required: false
48 default: false
49 type: bool
50 name:
51 description: HA rule identifier.
52 required: true
53 type: str
54 nodes:
55 description: |
56 List of cluster node members, where a priority can be given to each node. A resource bound to a group will run on the
57 available nodes with the highest priority. If there are more nodes in the highest priority class, the services will
58 get distributed to those nodes. The priorities have a
59 relative meaning only. The higher the number, the higher the priority.
60 It can either be a string C(node_name:priority,node_name:priority) or an actual list of strings.
61 Required if O(type=node-affinity).
62 required: false
63 type: list
64 elements: str
65 resources:
66 description: List of HA resource IDs. It can either be a string C(vm:100,ct:101) or an actual list of strings.
67 required: false
68 type: list
69 elements: str
70 state:
71 description: create or delete rule
72 required: true
73 choices: ['present', 'absent']
74 type: str
75 strict:
76 description: |
77 If false, the HA resource can also be moved to other nodes if there is none of the specified nodes available.
78 If not specified, the Proxmox API default C(false) will be used.
79 required: false
80 type: bool
81 type:
82 description: HA rule type.
83 required: false
84 choices: ['node-affinity', 'resource-affinity']
85 type: str
86
87 extends_documentation_fragment:
88 - community.proxmox.proxmox.actiongroup_proxmox
89 - community.proxmox.proxmox.documentation
90 - community.proxmox.attributes
91
92 author:
93 - Reto Kupferschmid (@rekup)
94 """
95
96 EXAMPLES = r"""
97 - name: Configure ha rule (node-affinity)
98 community.proxmox.proxmox_cluster_ha_rules:
99 name: node-affinity-rule-1
100 state: present
101 type: node-affinity
102 comment: VM 100 is supposed run on proxmox02
103 nodes:
104 - proxmox01:10
105 - proxmox02:20
106 resources:
107 - vm:100
108 disable: false
109 delegate_to: localhost
110
111 - name: Configure ha rule (node-affinity) - nodes and resources can also be provided as str
112 community.proxmox.proxmox_cluster_ha_rules:
113 name: node-affinity-rule-2
114 state: present
115 type: node-affinity
116 comment: VM 100 is supposed to run on proxmox02
117 nodes: proxmox01:10,proxmox02:20
118 resources: vm:100
119 disable: false
120 delegate_to: localhost
121
122 - name: Configure ha rule (resource-affinity) - resource affinity
123 community.proxmox.proxmox_cluster_ha_rules:
124 name: resource-affinity-rule-1
125 state: present
126 type: resource-affinity
127 comment: VM 100 and 101 are supposed to be kept on the same node
128 affinity: positive
129 resources:
130 - vm:100
131 - vm:101
132 disable: false
133 delegate_to: localhost
134
135 - name: Configure ha rule (resource-affinity) - resource anti-affinity
136 community.proxmox.proxmox_cluster_ha_rules:
137 name: resource-affinity-rule-1
138 state: present
139 type: resource-affinity
140 comment: VM 100 and 101 are supposed to be kept on different nodes
141 affinity: negative
142 resources:
143 - vm:100
144 - vm:101
145 disable: false
146 delegate_to: localhost
147 """
148
149 RETURN = r"""
150 rule:
151 description: A representation of the rule.
152 returned: success
153 type: dict
154 sample: {
155 "comment": "My first ha rule",
156 "digest": "f19acd44b43052343763cd9fd45a03b7449b3e2f",
157 "disable": 0,
158 "nodes": "proxmox01:10,proxmox02:10",
159 "order": 2,
160 "resources": "vm:100",
161 "rule": "ha-rule1",
162 "strict": 0,
163 "type": "node-affinity"
164 }
165
166 """
167
168 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
169 ProxmoxAnsible,
170 create_proxmox_module,
171 )
172
173
174 def module_args():
175 return dict(
176 affinity=dict(choices=["positive", "negative"], required=False),
177 comment=dict(type="str", required=False),
178 disable=dict(type="bool", required=False),
179 force=dict(type="bool", default=False, required=False),
180 name=dict(type="str", required=True),
181 nodes=dict(type="list", elements="str", required=False),
182 resources=dict(type="list", elements="str", required=False),
183 state=dict(choices=["present", "absent"], required=True),
184 strict=dict(type="bool", required=False),
185 type=dict(choices=["node-affinity", "resource-affinity"], required=False),
186 )
187
188
189 def module_options():
190 return dict(
191 required_if=[
192 ("state", "present", ["type", "resources"]),
193 ("type", "node-affinity", ["nodes"]),
194 ("type", "resource-affinity", ["affinity"]),
195 ],
196 )
197
198
199 class ProxmoxClusterHARuleAnsible(ProxmoxAnsible):
200 def get(self):
201 rules = self.proxmox_api.cluster.ha.rules.get()
202 return rules
203
204 def _post(self, data):
205 return self.proxmox_api.cluster.ha.rules.post(**data)
206
207 def _put(self, name, data):
208 return self.proxmox_api.cluster.ha.rules(name).put(**data)
209
210 def _delete(self, name):
211 return self.proxmox_api.cluster.ha.rules(name).delete()
212
213 def create_payload(self):
214 payload: dict = {
215 "rule": self.module.params["name"],
216 "type": self.module.params["type"],
217 }
218
219 if self.module.params["comment"] is not None:
220 payload["comment"] = self.module.params["comment"]
221
222 if self.module.params["disable"] is not None:
223 payload["disable"] = int(self.module.params["disable"])
224
225 if self.module.params["resources"] is not None:
226 payload["resources"] = ",".join(sorted(self.module.params["resources"]))
227
228 if self.module.params["type"] == "node-affinity":
229 if self.module.params["strict"] is not None:
230 payload["strict"] = int(self.module.params["strict"])
231 if self.module.params["nodes"] is not None:
232 payload["nodes"] = ",".join(sorted(self.module.params["nodes"]))
233
234 if self.module.params["type"] == "resource-affinity":
235 payload["affinity"] = self.module.params["affinity"]
236
237 return dict(sorted(payload.items()))
238
239 def create(self, existing_rule):
240 changed: bool = False
241 diff: dict = {"before": {}, "after": {}}
242
243 name = self.module.params["name"]
244
245 if existing_rule and existing_rule.get("type") != self.module.params["type"]:
246 if self.module.params["force"]:
247 diff["before"] = existing_rule.copy()
248 if not self.module.check_mode:
249 self._delete(name=name)
250 existing_rule = {}
251 else:
252 self.module.fail_json(
253 changed=False,
254 msg=(
255 f"Rule {name} already exists with type={existing_rule.get('type')}. "
256 "The type of an existing rule can not be changed. "
257 f"Use force=true to delete the existing rule and recreate it with type={self.module.params.get('type')}"
258 ),
259 )
260
261 if existing_rule:
262 # if the rule is enabled the "disabled" key is missing from the api response
263 existing_rule.setdefault("disable", 0)
264
265 # if the rule has no comment, the "comment" key is missing from the api response
266 existing_rule.setdefault("comment", "")
267
268 # sort fields to ensure idempotency
269 for key in ["nodes", "resources"]:
270 if existing_rule.get(key) is not None:
271 value_list = existing_rule.get(key).split(",")
272 existing_rule[key] = ",".join(sorted(value_list))
273
274 payload = self.create_payload()
275 updated_rule = {**existing_rule, **payload}
276
277 diff["before"] = existing_rule
278 diff["after"] = updated_rule
279 changed = existing_rule != updated_rule
280
281 if changed and not self.module.check_mode:
282 self._put(name, payload)
283
284 else:
285 changed = True
286 payload = self.create_payload()
287
288 if not self.module.check_mode:
289 self._post(payload)
290
291 # fetch the new rule and update the diff
292 rules = self.get()
293 diff["after"] = next((item for item in rules if item.get("rule") == name), {})
294 else:
295 diff["after"] = payload
296
297 return {"changed": changed, "rule": diff["after"], "diff": diff}
298
299 def delete(self, existing_rule, name):
300 diff: dict = {"before": {}, "after": {}}
301
302 if existing_rule:
303 diff.update({"before": existing_rule})
304 if not self.module.check_mode:
305 self._delete(name)
306 return {"changed": True, "diff": diff}
307
308 return {"changed": False, "diff": diff}
309
310
311 def run_module():
312 module = create_proxmox_module(module_args(), **module_options())
313 proxmox = ProxmoxClusterHARuleAnsible(module)
314
315 result = dict(
316 changed=False,
317 rule={},
318 diff={},
319 )
320
321 name = module.params["name"]
322 state = module.params["state"]
323
324 try:
325 rules = proxmox.get()
326
327 existing: dict = next((item for item in rules if item.get("rule") == name), {})
328
329 if state == "present":
330 result = proxmox.create(existing)
331 result.update(**result)
332 else:
333 result = proxmox.delete(existing, name=name)
334 result.update(**result)
335
336 except Exception as e:
337 module.fail_json(msg=str(e), **result)
338
339 module.exit_json(**result)
340
341
342 def main():
343 run_module()
344
345
346 if __name__ == "__main__":
347 main()