Debian Codegraph @

ansible_collections/community/general/plugins/modules/solaris_zone.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2015, Paul Markham <[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: solaris_zone
11 short_description: Manage Solaris zones
12 description:
13 - Create, start, stop and delete Solaris zones.
14 - This module does not currently allow changing of options for a zone that is already been created.
15 author:
16 - Paul Markham (@pmarkham)
17 requirements:
18 - Solaris 10 or 11
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 state:
28 description:
29 - V(present), configure and install the zone.
30 - V(installed), synonym for V(present).
31 - V(running), if the zone already exists, boot it, otherwise, configure and install the zone first, then boot it.
32 - V(started), synonym for V(running).
33 - V(stopped), shutdown a zone.
34 - V(absent), destroy the zone.
35 - V(configured), configure the ready so that it is to be attached.
36 - V(attached), attach a zone, but do not boot it.
37 - V(detached), shutdown and detach a zone.
38 type: str
39 choices: [absent, attached, configured, detached, installed, present, running, started, stopped]
40 default: present
41 name:
42 description:
43 - Zone name.
44 - A zone name must be unique name.
45 - A zone name must begin with an alphanumeric character.
46 - The name can contain alphanumeric characters, underscores V(_), hyphens V(-), and periods V(.).
47 - The name cannot be longer than 64 characters.
48 type: str
49 required: true
50 path:
51 description:
52 - The path where the zone is created. This is required when the zone is created, but not used otherwise.
53 type: str
54 sparse:
55 description:
56 - Whether to create a sparse (V(true)) or whole root (V(false)) zone.
57 type: bool
58 default: false
59 root_password:
60 description:
61 - The password hash for the root account. If not specified, the zone's root account does not have a password.
62 type: str
63 config:
64 description:
65 - The C(zonecfg) configuration commands for this zone. See zonecfg(1M) for the valid options and syntax. Typically this
66 is a list of options separated by semi-colons or new lines, for example V(set auto-boot=true;add net;set physical=bge0;set
67 address=10.1.1.1;end).
68 type: str
69 default: ''
70 create_options:
71 description:
72 - Extra options to the zonecfg(1M) create command.
73 type: str
74 default: ''
75 install_options:
76 description:
77 - Extra options to the zoneadm(1M) install command. To automate Solaris 11 zone creation, use this to specify the profile
78 XML file, for example O(install_options=-c sc_profile.xml).
79 type: str
80 default: ''
81 attach_options:
82 description:
83 - Extra options to the zoneadm attach command. For example, this can be used to specify whether a minimum or full update
84 of packages is required and if any packages need to be deleted. For valid values, see zoneadm(1M).
85 type: str
86 default: ''
87 timeout:
88 description:
89 - Timeout, in seconds, for zone to boot.
90 type: int
91 default: 600
92 """
93
94 EXAMPLES = r"""
95 - name: Create and install a zone, but don't boot it
96 community.general.solaris_zone:
97 name: zone1
98 state: present
99 path: /zones/zone1
100 sparse: true
101 root_password: Be9oX7OSwWoU.
102 config: 'set autoboot=true; add net; set physical=bge0; set address=10.1.1.1; end'
103
104 - name: Create and install a zone and boot it
105 community.general.solaris_zone:
106 name: zone1
107 state: running
108 path: /zones/zone1
109 root_password: Be9oX7OSwWoU.
110 config: 'set autoboot=true; add net; set physical=bge0; set address=10.1.1.1; end'
111
112 - name: Boot an already installed zone
113 community.general.solaris_zone:
114 name: zone1
115 state: running
116
117 - name: Stop a zone
118 community.general.solaris_zone:
119 name: zone1
120 state: stopped
121
122 - name: Destroy a zone
123 community.general.solaris_zone:
124 name: zone1
125 state: absent
126
127 - name: Detach a zone
128 community.general.solaris_zone:
129 name: zone1
130 state: detached
131
132 - name: Configure a zone, ready to be attached
133 community.general.solaris_zone:
134 name: zone1
135 state: configured
136 path: /zones/zone1
137 root_password: Be9oX7OSwWoU.
138 config: 'set autoboot=true; add net; set physical=bge0; set address=10.1.1.1; end'
139
140 - name: Attach zone1
141 community.general.solaris_zone:
142 name: zone1
143 state: attached
144 attach_options: -u
145 """
146
147 import os
148 import platform
149 import re
150 import tempfile
151 import time
152
153 from ansible.module_utils.basic import AnsibleModule
154
155
156 class Zone:
157 def __init__(self, module):
158 self.changed = False
159 self.msg = []
160
161 self.module = module
162 self.path = self.module.params["path"]
163 self.name = self.module.params["name"]
164 self.sparse = self.module.params["sparse"]
165 self.root_password = self.module.params["root_password"]
166 self.timeout = self.module.params["timeout"]
167 self.config = self.module.params["config"]
168 self.create_options = self.module.params["create_options"]
169 self.install_options = self.module.params["install_options"]
170 self.attach_options = self.module.params["attach_options"]
171
172 self.zoneadm_cmd = self.module.get_bin_path("zoneadm", True)
173 self.zonecfg_cmd = self.module.get_bin_path("zonecfg", True)
174 self.ssh_keygen_cmd = self.module.get_bin_path("ssh-keygen", True)
175
176 if self.module.check_mode:
177 self.msg.append("Running in check mode")
178
179 if platform.system() != "SunOS":
180 self.module.fail_json(msg="This module requires Solaris")
181
182 (self.os_major, self.os_minor) = platform.release().split(".")
183 if int(self.os_minor) < 10:
184 self.module.fail_json(msg="This module requires Solaris 10 or later")
185
186 match = re.match("^[a-zA-Z0-9][-_.a-zA-Z0-9]{0,62}$", self.name)
187 if not match:
188 self.module.fail_json(
189 msg="Provided zone name is not a valid zone name. "
190 "Please refer documentation for correct zone name specifications."
191 )
192
193 def configure(self):
194 if not self.path:
195 self.module.fail_json(msg="Missing required argument: path")
196
197 if not self.module.check_mode:
198 t = tempfile.NamedTemporaryFile(delete=False, mode="wt")
199
200 if self.sparse:
201 t.write(f"create {self.create_options}\n")
202 self.msg.append("creating sparse-root zone")
203 else:
204 t.write(f"create -b {self.create_options}\n")
205 self.msg.append("creating whole-root zone")
206
207 t.write(f"set zonepath={self.path}\n")
208 t.write(f"{self.config}\n")
209 t.close()
210
211 cmd = [self.zonecfg_cmd, "-z", self.name, "-f", t.name]
212 (rc, out, err) = self.module.run_command(cmd)
213 if rc != 0:
214 self.module.fail_json(msg=f"Failed to create zone. {out + err}")
215 os.unlink(t.name)
216
217 self.changed = True
218 self.msg.append("zone configured")
219
220 def install(self):
221 if not self.module.check_mode:
222 cmd = [self.zoneadm_cmd, "-z", self.name, "install", self.install_options]
223 (rc, out, err) = self.module.run_command(cmd)
224 if rc != 0:
225 self.module.fail_json(msg=f"Failed to install zone. {out + err}")
226 if int(self.os_minor) == 10:
227 self.configure_sysid()
228 self.configure_password()
229 self.configure_ssh_keys()
230 self.changed = True
231 self.msg.append("zone installed")
232
233 def uninstall(self):
234 if self.is_installed():
235 if not self.module.check_mode:
236 cmd = [self.zoneadm_cmd, "-z", self.name, "uninstall", "-F"]
237 (rc, out, err) = self.module.run_command(cmd)
238 if rc != 0:
239 self.module.fail_json(msg=f"Failed to uninstall zone. {out + err}")
240 self.changed = True
241 self.msg.append("zone uninstalled")
242
243 def configure_sysid(self):
244 if os.path.isfile(f"{self.path}/root/etc/.UNCONFIGURED"):
245 os.unlink(f"{self.path}/root/etc/.UNCONFIGURED")
246
247 open(f"{self.path}/root/noautoshutdown", "w").close()
248
249 with open(f"{self.path}/root/etc/nodename", "w") as node:
250 node.write(self.name)
251
252 with open(f"{self.path}/root/etc/.sysIDtool.state", "w") as id:
253 id.write("1 # System previously configured?\n")
254 id.write("1 # Bootparams succeeded?\n")
255 id.write("1 # System is on a network?\n")
256 id.write("1 # Extended network information gathered?\n")
257 id.write("0 # Autobinder succeeded?\n")
258 id.write("1 # Network has subnets?\n")
259 id.write("1 # root password prompted for?\n")
260 id.write("1 # locale and term prompted for?\n")
261 id.write("1 # security policy in place\n")
262 id.write("1 # NFSv4 domain configured\n")
263 id.write("0 # Auto Registration Configured\n")
264 id.write("vt100")
265
266 def configure_ssh_keys(self):
267 rsa_key_file = f"{self.path}/root/etc/ssh/ssh_host_rsa_key"
268 dsa_key_file = f"{self.path}/root/etc/ssh/ssh_host_dsa_key"
269
270 if not os.path.isfile(rsa_key_file):
271 cmd = [self.ssh_keygen_cmd, "-f", rsa_key_file, "-t", "rsa", "-N", ""]
272 (rc, out, err) = self.module.run_command(cmd)
273 if rc != 0:
274 self.module.fail_json(msg=f"Failed to create rsa key. {out + err}")
275
276 if not os.path.isfile(dsa_key_file):
277 cmd = [self.ssh_keygen_cmd, "-f", dsa_key_file, "-t", "dsa", "-N", ""]
278 (rc, out, err) = self.module.run_command(cmd)
279 if rc != 0:
280 self.module.fail_json(msg=f"Failed to create dsa key. {out + err}")
281
282 def configure_password(self):
283 shadow = f"{self.path}/root/etc/shadow"
284 if self.root_password:
285 with open(shadow) as f:
286 lines = f.readlines()
287
288 for i in range(0, len(lines)):
289 fields = lines[i].split(":")
290 if fields[0] == "root":
291 fields[1] = self.root_password
292 lines[i] = ":".join(fields)
293
294 with open(shadow, "w") as f:
295 for line in lines:
296 f.write(line)
297
298 def boot(self):
299 if not self.module.check_mode:
300 cmd = [self.zoneadm_cmd, "-z", self.name, "boot"]
301 (rc, out, err) = self.module.run_command(cmd)
302 if rc != 0:
303 self.module.fail_json(msg=f"Failed to boot zone. {out + err}")
304
305 """
306 The boot command can return before the zone has fully booted. This is especially
307 true on the first boot when the zone initializes the SMF services. Unless the zone
308 has fully booted, subsequent tasks in the playbook may fail as services aren't running yet.
309 Wait until the zone's console login is running; once that's running, consider the zone booted.
310 """
311
312 zone_booted_re = re.compile(r"ttymon.*-d /dev/console")
313 cmd_ps = ["ps", "-z", self.name, "-o", "args"]
314
315 elapsed = 0
316 while True:
317 if elapsed > self.timeout:
318 self.module.fail_json(msg="timed out waiting for zone to boot")
319 rc, out, err = self.module.run_command(cmd_ps, check_rc=False)
320 if any(zone_booted_re.match(x) for x in out.splitlines()):
321 break
322 time.sleep(10)
323 elapsed += 10
324 self.changed = True
325 self.msg.append("zone booted")
326
327 def destroy(self):
328 if self.is_running():
329 self.stop()
330 if self.is_installed():
331 self.uninstall()
332 if not self.module.check_mode:
333 cmd = [self.zonecfg_cmd, "-z", self.name, "delete", "-F"]
334 (rc, out, err) = self.module.run_command(cmd)
335 if rc != 0:
336 self.module.fail_json(msg=f"Failed to delete zone. {out + err}")
337 self.changed = True
338 self.msg.append("zone deleted")
339
340 def stop(self):
341 if not self.module.check_mode:
342 cmd = [self.zoneadm_cmd, "-z", self.name, "halt"]
343 (rc, out, err) = self.module.run_command(cmd)
344 if rc != 0:
345 self.module.fail_json(msg=f"Failed to stop zone. {out + err}")
346 self.changed = True
347 self.msg.append("zone stopped")
348
349 def detach(self):
350 if not self.module.check_mode:
351 cmd = [self.zoneadm_cmd, "-z", self.name, "detach"]
352 (rc, out, err) = self.module.run_command(cmd)
353 if rc != 0:
354 self.module.fail_json(msg=f"Failed to detach zone. {out + err}")
355 self.changed = True
356 self.msg.append("zone detached")
357
358 def attach(self):
359 if not self.module.check_mode:
360 cmd = [self.zoneadm_cmd, "-z", self.name, "attach", self.attach_options]
361 (rc, out, err) = self.module.run_command(cmd)
362 if rc != 0:
363 self.module.fail_json(msg=f"Failed to attach zone. {out + err}")
364 self.changed = True
365 self.msg.append("zone attached")
366
367 def exists(self):
368 cmd = [self.zoneadm_cmd, "-z", self.name, "list"]
369 (rc, out, err) = self.module.run_command(cmd)
370 return rc == 0
371
372 def is_running(self):
373 return self.status() == "running"
374
375 def is_installed(self):
376 return self.status() == "installed"
377
378 def is_configured(self):
379 return self.status() == "configured"
380
381 def status(self):
382 cmd = [self.zoneadm_cmd, "-z", self.name, "list", "-p"]
383 (rc, out, err) = self.module.run_command(cmd)
384 if rc == 0:
385 return out.split(":")[2]
386 else:
387 return "undefined"
388
389 def state_present(self):
390 if self.exists():
391 self.msg.append("zone already exists")
392 else:
393 self.configure()
394 self.install()
395
396 def state_running(self):
397 self.state_present()
398 if self.is_running():
399 self.msg.append("zone already running")
400 else:
401 self.boot()
402
403 def state_stopped(self):
404 if self.exists():
405 self.stop()
406 else:
407 self.module.fail_json(msg="zone does not exist")
408
409 def state_absent(self):
410 if self.exists():
411 if self.is_running():
412 self.stop()
413 self.destroy()
414 else:
415 self.msg.append("zone does not exist")
416
417 def state_configured(self):
418 if self.exists():
419 self.msg.append("zone already exists")
420 else:
421 self.configure()
422
423 def state_detached(self):
424 if not self.exists():
425 self.module.fail_json(msg="zone does not exist")
426 if self.is_configured():
427 self.msg.append("zone already detached")
428 else:
429 self.stop()
430 self.detach()
431
432 def state_attached(self):
433 if not self.exists():
434 self.msg.append("zone does not exist")
435 if self.is_configured():
436 self.attach()
437 else:
438 self.msg.append("zone already attached")
439
440
441 def main():
442 module = AnsibleModule(
443 argument_spec=dict(
444 name=dict(type="str", required=True),
445 state=dict(
446 type="str",
447 default="present",
448 choices=[
449 "absent",
450 "attached",
451 "configured",
452 "detached",
453 "installed",
454 "present",
455 "running",
456 "started",
457 "stopped",
458 ],
459 ),
460 path=dict(type="str"),
461 sparse=dict(type="bool", default=False),
462 root_password=dict(type="str", no_log=True),
463 timeout=dict(type="int", default=600),
464 config=dict(type="str", default=""),
465 create_options=dict(type="str", default=""),
466 install_options=dict(type="str", default=""),
467 attach_options=dict(type="str", default=""),
468 ),
469 supports_check_mode=True,
470 )
471
472 zone = Zone(module)
473
474 state = module.params["state"]
475
476 if state == "running" or state == "started":
477 zone.state_running()
478 elif state == "present" or state == "installed":
479 zone.state_present()
480 elif state == "stopped":
481 zone.state_stopped()
482 elif state == "absent":
483 zone.state_absent()
484 elif state == "configured":
485 zone.state_configured()
486 elif state == "detached":
487 zone.state_detached()
488 elif state == "attached":
489 zone.state_attached()
490 else:
491 module.fail_json(msg=f"Invalid state: {state}")
492
493 module.exit_json(changed=zone.changed, msg=", ".join(zone.msg))
494
495
496 if __name__ == "__main__":
497 main()