Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2025, Florian Paul Azim Hoberg (@gyptazy) <[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
8 DOCUMENTATION = r"""
9 module: proxmox_cluster
10 version_added: 1.0.0
11 short_description: Create and join Proxmox VE clusters
12 description:
13 - Create and join Proxmox VE clusters with PVE nodes.
14 author: Florian Paul Azim Hoberg (@gyptazy)
15 attributes:
16 check_mode:
17 support: full
18 diff_mode:
19 support: none
20 options:
21 link0:
22 description:
23 - The first IP address to use for cluster communication.
24 type: str
25 required: false
26 link1:
27 description:
28 - The second IP address to use for cluster communication.
29 type: str
30 required: false
31 master_ip:
32 description:
33 - The IP address of the cluster master when joining the cluster.
34 type: str
35 required: false
36 master_api_password:
37 description:
38 - Specify the password to authenticate with the master node.
39 - Uses the api_password parameter if not specified.
40 type: str
41 required: false
42 fingerprint:
43 description:
44 - The fingerprint of the cluster master when joining the cluster.
45 type: str
46 required: false
47 cluster_name:
48 description:
49 - The cluster name to use for cluster creation.
50 - Not used when joining a cluster.
51 type: str
52 required: false
53 state:
54 description:
55 - Possible module state to perform the required steps within the Proxmox VE API.
56 choices: ["present"]
57 type: str
58 extends_documentation_fragment:
59 - community.proxmox.proxmox.actiongroup_proxmox
60 - community.proxmox.proxmox.documentation
61 - community.proxmox.attributes
62 """
63
64 EXAMPLES = r"""
65 - name: Create a Proxmox VE Cluster
66 community.proxmox.proxmox_cluster:
67 state: present
68 link0: 10.10.1.1
69 link1: 10.10.2.1
70 cluster_name: "devcluster"
71
72 - name: Join a Proxmox VE Cluster
73 community.proxmox.proxmox_cluster:
74 state: present
75 master_ip: "{{ primary_node }}"
76 fingerprint: "{{ cluster_fingerprint }}"
77
78 - name: Join a Proxmox VE Cluster with different API password
79 community.proxmox.proxmox_cluster:
80 state: present
81 master_api_password: "{{ master_node_api_password }}"
82 master_ip: "{{ primary_node }}"
83 fingerprint: "{{ cluster_fingerprint }}"
84 """
85
86 RETURN = r"""
87 cluster:
88 description: The name of the cluster that was created.
89 returned: success
90 type: str
91 sample: "devcluster"
92 """
93
94
95 import re
96
97 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
98 ProxmoxAnsible,
99 create_proxmox_module,
100 )
101
102
103 def module_args():
104 return dict(
105 state=dict(default=None, choices=["present"]),
106 cluster_name=dict(type="str"),
107 link0=dict(type="str"),
108 link1=dict(type="str"),
109 master_ip=dict(type="str"),
110 master_api_password=dict(type="str", no_log=True),
111 fingerprint=dict(type="str"),
112 )
113
114
115 def module_options():
116 return {}
117
118
119 class ProxmoxClusterAnsible(ProxmoxAnsible):
120 def check_is_cluster(self, cluster_status):
121 return "cluster" in [cluster_data["type"] for cluster_data in cluster_status]
122
123 def get_cluster_name(self, cluster_status):
124 for d in cluster_status:
125 if d["type"] == "cluster":
126 return d["name"]
127 return ""
128
129 def check_already_in_right_cluster(self, cluster_status, master_ip):
130 return any(master_ip in (d.get("ip"), d.get("name")) for d in cluster_status)
131
132 def cluster_create(self):
133 cluster_name = self.module.params.get("cluster_name") or self.module.params.get("api_host")
134 payload = {"clustername": cluster_name}
135
136 cluster_status = self.proxmox_api.cluster.status.get()
137
138 if self.check_is_cluster(cluster_status):
139 if self.get_cluster_name(cluster_status) == cluster_name:
140 self.module.exit_json(
141 changed=False, msg=f"Cluster '{cluster_name}' already present.", cluster=cluster_name
142 )
143 else:
144 self.module.fail_json(
145 msg=f'Error creating cluster: Node is already part of a different cluster - "{self.get_cluster_name(cluster_status)}".'
146 )
147
148 if self.module.params.get("link0") is not None:
149 payload["link0"] = self.module.params.get("link0")
150 if self.module.params.get("link1") is not None:
151 payload["link1"] = self.module.params.get("link1")
152
153 if self.module.check_mode:
154 self.module.exit_json(changed=True, msg=f"Cluster '{cluster_name}' would be created.", cluster=cluster_name)
155
156 try:
157 self.proxmox_api.cluster.config.post(**payload)
158 self.module.exit_json(changed=True, msg=f"Cluster '{cluster_name}' created.", cluster=cluster_name)
159 except Exception as e:
160 self.module.fail_json(msg=f"Error while creating cluster: {str(e)}")
161
162 def cluster_join(self):
163 payload = {}
164 master_ip = self.module.params.get("master_ip")
165
166 payload["hostname"] = master_ip
167 payload["fingerprint"] = self.module.params.get("fingerprint")
168 payload["password"] = self.module.params.get("master_api_password") or self.module.params.get("api_password")
169
170 if self.module.params.get("link0") is not None:
171 payload["link0"] = self.module.params.get("link0")
172 if self.module.params.get("link1") is not None:
173 payload["link1"] = self.module.params.get("link1")
174
175 cluster_status = self.proxmox_api.cluster.status.get()
176
177 if self.check_is_cluster(cluster_status):
178 if self.check_already_in_right_cluster(cluster_status, master_ip):
179 self.module.exit_json(changed=False, msg="Node already in the cluster.")
180
181 self.module.fail_json(msg="Error while joining cluster: Node is already part of a cluster.")
182
183 if self.module.check_mode:
184 self.module.exit_json(changed=True, msg="Node would join the cluster.")
185
186 try:
187 self.proxmox_api.cluster.config.join.post(**payload)
188 self.module.exit_json(changed=True, msg="Node joined the cluster.")
189
190 except Exception as e:
191 self.module.fail_json(
192 msg=f"Error while joining the cluster: {str(e)}",
193 )
194
195
196 def validate_cluster_name(module, min_length=1, max_length=15):
197 cluster_name = module.params.get("cluster_name")
198
199 if not (min_length <= len(cluster_name) <= max_length):
200 module.fail_json(msg=f"Cluster name must be between {min_length} and {max_length} characters long.")
201
202 if not re.match(r"^[a-zA-Z0-9\-]+$", cluster_name):
203 module.fail_json(msg="Cluster name must contain only letters, digits, or hyphens.")
204
205
206 def main():
207 module = create_proxmox_module(module_args(), **module_options())
208 proxmox = ProxmoxClusterAnsible(module)
209
210 result = dict(changed=False)
211
212 # The Proxmox VE API currently does not support leaving a cluster
213 # or removing a node from a cluster. Therefore, we only support creating
214 # and joining a cluster.
215 # (https://pve.proxmox.com/pve-docs/api-viewer/#/cluster/config/nodes)
216 if module.params.get("state") == "present":
217 if module.params.get("master_ip") and module.params.get("fingerprint"):
218 cluster_action = proxmox.cluster_join()
219 else:
220 validate_cluster_name(module)
221 cluster_action = proxmox.cluster_create()
222 else:
223 cluster_action = {}
224
225 result["proxmox_cluster"] = cluster_action
226 module.exit_json(**result)
227
228
229 if __name__ == "__main__":
230 main()