| 1 |
#!/usr/bin/python |
| 2 |
# coding: utf-8 -*- |
| 3 |
|
| 4 |
# 2022, Sébastien Gendre <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
|
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = """ |
| 12 |
module: podman_generate_systemd |
| 13 |
author: |
| 14 |
- Sébastien Gendre (@CyberFox001) |
| 15 |
short_description: Generate systemd unit from a pod or a container |
| 16 |
description: |
| 17 |
- Generate systemd .service unit file(s) from a pod or a container |
| 18 |
- Support Ansible check mode |
| 19 |
options: |
| 20 |
name: |
| 21 |
description: |
| 22 |
- Name of the pod or container to export |
| 23 |
type: str |
| 24 |
required: true |
| 25 |
dest: |
| 26 |
description: |
| 27 |
- Destination of the generated systemd unit file(s). |
| 28 |
- Use C(/etc/systemd/system) for the system-wide systemd instance. |
| 29 |
- Use C(/etc/systemd/user) or C(~/.config/systemd/user) for use with per-user instances of systemd. |
| 30 |
type: path |
| 31 |
force: |
| 32 |
description: |
| 33 |
- Replace the systemd unit file(s) even if it already exists. |
| 34 |
- This works with dest option. |
| 35 |
type: bool |
| 36 |
default: false |
| 37 |
new: |
| 38 |
description: |
| 39 |
- Generate unit files that create containers and pods, not only start them. |
| 40 |
- Refer to podman-generate-systemd(1) man page for more information. |
| 41 |
type: bool |
| 42 |
default: false |
| 43 |
restart_policy: |
| 44 |
description: |
| 45 |
- Restart policy of the service |
| 46 |
type: str |
| 47 |
choices: |
| 48 |
- no-restart |
| 49 |
- on-success |
| 50 |
- on-failure |
| 51 |
- on-abnormal |
| 52 |
- on-watchdog |
| 53 |
- on-abort |
| 54 |
- always |
| 55 |
restart_sec: |
| 56 |
description: |
| 57 |
- Configures the time to sleep before restarting a service (as configured with restart-policy). |
| 58 |
- Takes a value in seconds. |
| 59 |
- Only with Podman 4.0.0 and above |
| 60 |
type: int |
| 61 |
start_timeout: |
| 62 |
description: |
| 63 |
- Override the default start timeout for the container with the given value in seconds. |
| 64 |
- Only with Podman 4.0.0 and above |
| 65 |
type: int |
| 66 |
stop_timeout: |
| 67 |
description: |
| 68 |
- Override the default stop timeout for the container with the given value in seconds. |
| 69 |
type: int |
| 70 |
env: |
| 71 |
description: |
| 72 |
- Set environment variables to the systemd unit files. |
| 73 |
- Keys are the environment variable names, and values are the environment variable values |
| 74 |
- Only with Podman 4.3.0 and above |
| 75 |
type: dict |
| 76 |
use_names: |
| 77 |
description: |
| 78 |
- Use name of the containers for the start, stop, and description in the unit file. |
| 79 |
type: bool |
| 80 |
default: true |
| 81 |
container_prefix: |
| 82 |
description: |
| 83 |
- Set the systemd unit name prefix for containers. |
| 84 |
- If not set, use the default defined by podman, C(container). |
| 85 |
- Refer to podman-generate-systemd(1) man page for more information. |
| 86 |
type: str |
| 87 |
pod_prefix: |
| 88 |
description: |
| 89 |
- Set the systemd unit name prefix for pods. |
| 90 |
- If not set, use the default defined by podman, C(pod). |
| 91 |
- Refer to podman-generate-systemd(1) man page for more information. |
| 92 |
type: str |
| 93 |
separator: |
| 94 |
description: |
| 95 |
- Systemd unit name separator between the name/id of a container/pod and the prefix. |
| 96 |
- If not set, use the default defined by podman, C(-). |
| 97 |
- Refer to podman-generate-systemd(1) man page for more information. |
| 98 |
type: str |
| 99 |
no_header: |
| 100 |
description: |
| 101 |
- Do not generate the header including meta data such as the Podman version and the timestamp. |
| 102 |
type: bool |
| 103 |
default: false |
| 104 |
after: |
| 105 |
description: |
| 106 |
- Add the systemd unit after (C(After=)) option, that ordering dependencies between the list of dependencies and this service. |
| 107 |
- This option may be specified more than once. |
| 108 |
- User-defined dependencies will be appended to the generated unit file |
| 109 |
- But any existing options such as needed or defined by default (e.g. C(online.target)) will not be removed or overridden. |
| 110 |
- Only with Podman 4.0.0 and above |
| 111 |
type: list |
| 112 |
elements: str |
| 113 |
wants: |
| 114 |
description: |
| 115 |
- Add the systemd unit wants (C(Wants=)) option, that this service is (weak) dependent on. |
| 116 |
- This option may be specified more than once. |
| 117 |
- This option does not influence the order in which services are started or stopped. |
| 118 |
- User-defined dependencies will be appended to the generated unit file |
| 119 |
- But any existing options such as needed or defined by default (e.g. C(online.target)) will not be removed or overridden. |
| 120 |
- Only with Podman 4.0.0 and above |
| 121 |
type: list |
| 122 |
elements: str |
| 123 |
requires: |
| 124 |
description: |
| 125 |
- Set the systemd unit requires (Requires=) option. |
| 126 |
- Similar to wants, but declares a stronger requirement dependency. |
| 127 |
- Only with Podman 4.0.0 and above |
| 128 |
type: list |
| 129 |
elements: str |
| 130 |
executable: |
| 131 |
description: |
| 132 |
- C(Podman) executable name or full path |
| 133 |
type: str |
| 134 |
default: podman |
| 135 |
requirements: |
| 136 |
- Podman installed on target host |
| 137 |
notes: |
| 138 |
- If you indicate a pod, the systemd units for it and all its containers will be generated |
| 139 |
- Create all your pods, containers and their dependencies before generating the systemd files |
| 140 |
- If a container or pod is already started before you do a C(systemctl daemon-reload), |
| 141 |
systemd will not see the container or pod as started |
| 142 |
- Stop your container or pod before you do a C(systemctl daemon-reload), |
| 143 |
then you can start them with C(systemctl start my_container.service) |
| 144 |
""" |
| 145 |
|
| 146 |
EXAMPLES = """ |
| 147 |
# Example of creating a container and systemd unit file. |
| 148 |
# When using podman_generate_systemd with new:true then |
| 149 |
# the container needs rm:true for idempotence. |
| 150 |
- name: Create postgres container |
| 151 |
containers.podman.podman_container: |
| 152 |
name: postgres |
| 153 |
image: docker.io/library/postgres:latest |
| 154 |
rm: true |
| 155 |
state: created |
| 156 |
|
| 157 |
- name: Generate systemd unit file for postgres container |
| 158 |
containers.podman.podman_generate_systemd: |
| 159 |
name: postgres |
| 160 |
new: true |
| 161 |
no_header: true |
| 162 |
dest: /etc/systemd/system |
| 163 |
|
| 164 |
- name: Ensure postgres container is started and enabled |
| 165 |
ansible.builtin.systemd: |
| 166 |
name: container-postgres |
| 167 |
daemon_reload: true |
| 168 |
state: started |
| 169 |
enabled: true |
| 170 |
|
| 171 |
|
| 172 |
# Example of creating a container and integrate it into systemd |
| 173 |
- name: A postgres container must exist, stopped |
| 174 |
containers.podman.podman_container: |
| 175 |
name: postgres_local |
| 176 |
image: docker.io/library/postgres:latest |
| 177 |
state: stopped |
| 178 |
|
| 179 |
- name: Systemd unit files for postgres container must exist |
| 180 |
containers.podman.podman_generate_systemd: |
| 181 |
name: postgres_local |
| 182 |
dest: ~/.config/systemd/user/ |
| 183 |
|
| 184 |
- name: Postgres container must be started and enabled on systemd |
| 185 |
ansible.builtin.systemd: |
| 186 |
name: container-postgres_local |
| 187 |
scope: user |
| 188 |
daemon_reload: true |
| 189 |
state: started |
| 190 |
enabled: true |
| 191 |
|
| 192 |
|
| 193 |
# Generate the unit files, but store them on an Ansible variable |
| 194 |
# instead of writing them on target host |
| 195 |
- name: Systemd unit files for postgres container must be generated |
| 196 |
containers.podman.podman_generate_systemd: |
| 197 |
name: postgres_local |
| 198 |
register: postgres_local_systemd_unit |
| 199 |
|
| 200 |
# Generate the unit files with environment variables sets |
| 201 |
- name: Systemd unit files for postgres container must be generated |
| 202 |
containers.podman.podman_generate_systemd: |
| 203 |
name: postgres_local |
| 204 |
env: |
| 205 |
POSTGRES_USER: my_app |
| 206 |
POSTGRES_PASSWORD: example |
| 207 |
register: postgres_local_systemd_unit |
| 208 |
""" |
| 209 |
|
| 210 |
RETURN = """ |
| 211 |
systemd_units: |
| 212 |
description: A copy of the generated systemd .service unit(s) |
| 213 |
returned: always |
| 214 |
type: dict |
| 215 |
sample: { |
| 216 |
"container-postgres_local": " #Content of the systemd .servec unit for postgres_local container", |
| 217 |
"pod-my_webapp": " #Content of the systemd .servec unit for my_webapp pod", |
| 218 |
} |
| 219 |
podman_command: |
| 220 |
description: A copy of the podman command used to generate the systemd unit(s) |
| 221 |
returned: always |
| 222 |
type: str |
| 223 |
sample: "podman generate systemd my_webapp" |
| 224 |
""" |
| 225 |
|
| 226 |
|
| 227 |
import os |
| 228 |
from ansible.module_utils.basic import AnsibleModule |
| 229 |
import json |
| 230 |
from ansible_collections.containers.podman.plugins.module_utils.podman.common import ( |
| 231 |
compare_systemd_file_content, |
| 232 |
) |
| 233 |
|
| 234 |
RESTART_POLICY_CHOICES = [ |
| 235 |
"no-restart", |
| 236 |
"on-success", |
| 237 |
"on-failure", |
| 238 |
"on-abnormal", |
| 239 |
"on-watchdog", |
| 240 |
"on-abort", |
| 241 |
"always", |
| 242 |
] |
| 243 |
|
| 244 |
|
| 245 |
def generate_systemd(module): |
| 246 |
"""Generate systemd .service unit file from a pod or container. |
| 247 |
|
| 248 |
Parameter: |
| 249 |
- module (AnsibleModule): An AnsibleModule object |
| 250 |
|
| 251 |
Returns (tuple[bool, list[str], str]): |
| 252 |
- A boolean which indicate whether the targeted systemd state is modified |
| 253 |
- A copy of the generated systemd .service units content |
| 254 |
- A copy of the command, as a string |
| 255 |
""" |
| 256 |
# Flag which indicate whether the targeted system state is modified |
| 257 |
changed = False |
| 258 |
|
| 259 |
# Build the podman command, based on the module parameters |
| 260 |
command_options = [] |
| 261 |
|
| 262 |
# New option |
| 263 |
if module.params["new"]: |
| 264 |
command_options.append("--new") |
| 265 |
|
| 266 |
# Restart policy option |
| 267 |
restart_policy = module.params["restart_policy"] |
| 268 |
if restart_policy: |
| 269 |
# add the restart policy to options |
| 270 |
if restart_policy == "no-restart": |
| 271 |
restart_policy = "no" |
| 272 |
command_options.append( |
| 273 |
"--restart-policy={restart_policy}".format( |
| 274 |
restart_policy=restart_policy, |
| 275 |
), |
| 276 |
) |
| 277 |
|
| 278 |
# Restart-sec option (only for Podman 4.0.0 and above) |
| 279 |
restart_sec = module.params["restart_sec"] |
| 280 |
if restart_sec: |
| 281 |
command_options.append( |
| 282 |
"--restart-sec={restart_sec}".format( |
| 283 |
restart_sec=restart_sec, |
| 284 |
), |
| 285 |
) |
| 286 |
|
| 287 |
# Start-timeout option (only for Podman 4.0.0 and above) |
| 288 |
start_timeout = module.params["start_timeout"] |
| 289 |
if start_timeout: |
| 290 |
command_options.append( |
| 291 |
"--start-timeout={start_timeout}".format( |
| 292 |
start_timeout=start_timeout, |
| 293 |
), |
| 294 |
) |
| 295 |
|
| 296 |
# Stop-timeout option |
| 297 |
stop_timeout = module.params["stop_timeout"] |
| 298 |
if stop_timeout: |
| 299 |
command_options.append( |
| 300 |
"--stop-timeout={stop_timeout}".format( |
| 301 |
stop_timeout=stop_timeout, |
| 302 |
), |
| 303 |
) |
| 304 |
|
| 305 |
# Use container name(s) option |
| 306 |
if module.params["use_names"]: |
| 307 |
command_options.append("--name") |
| 308 |
|
| 309 |
# Container-prefix option |
| 310 |
container_prefix = module.params["container_prefix"] |
| 311 |
if container_prefix is not None: |
| 312 |
command_options.append( |
| 313 |
"--container-prefix={container_prefix}".format( |
| 314 |
container_prefix=container_prefix, |
| 315 |
), |
| 316 |
) |
| 317 |
|
| 318 |
# Pod-prefix option |
| 319 |
pod_prefix = module.params["pod_prefix"] |
| 320 |
if pod_prefix is not None: |
| 321 |
command_options.append( |
| 322 |
"--pod-prefix={pod_prefix}".format( |
| 323 |
pod_prefix=pod_prefix, |
| 324 |
), |
| 325 |
) |
| 326 |
|
| 327 |
# Separator option |
| 328 |
separator = module.params["separator"] |
| 329 |
if separator is not None: |
| 330 |
command_options.append( |
| 331 |
"--separator={separator}".format( |
| 332 |
separator=separator, |
| 333 |
), |
| 334 |
) |
| 335 |
|
| 336 |
# No-header option |
| 337 |
if module.params["no_header"]: |
| 338 |
command_options.append("--no-header") |
| 339 |
|
| 340 |
# After option (only for Podman 4.0.0 and above) |
| 341 |
after = module.params["after"] |
| 342 |
if after: |
| 343 |
for item in after: |
| 344 |
command_options.append( |
| 345 |
"--after={item}".format( |
| 346 |
item=item, |
| 347 |
), |
| 348 |
) |
| 349 |
|
| 350 |
# Wants option (only for Podman 4.0.0 and above) |
| 351 |
wants = module.params["wants"] |
| 352 |
if wants: |
| 353 |
for item in wants: |
| 354 |
command_options.append( |
| 355 |
"--wants={item}".format( |
| 356 |
item=item, |
| 357 |
) |
| 358 |
) |
| 359 |
|
| 360 |
# Requires option (only for Podman 4.0.0 and above) |
| 361 |
requires = module.params["requires"] |
| 362 |
if requires: |
| 363 |
for item in requires: |
| 364 |
command_options.append( |
| 365 |
"--requires={item}".format( |
| 366 |
item=item, |
| 367 |
), |
| 368 |
) |
| 369 |
|
| 370 |
# Environment variables (only for Podman 4.3.0 and above) |
| 371 |
environment_variables = module.params["env"] |
| 372 |
if environment_variables: |
| 373 |
for env_var_name, env_var_value in environment_variables.items(): |
| 374 |
command_options.append( |
| 375 |
"-e='{env_var_name}={env_var_value}'".format( |
| 376 |
env_var_name=env_var_name, |
| 377 |
env_var_value=env_var_value, |
| 378 |
), |
| 379 |
) |
| 380 |
|
| 381 |
# Set output format, of podman command, to json |
| 382 |
command_options.extend(["--format", "json"]) |
| 383 |
|
| 384 |
# Full command build, with option included |
| 385 |
# Base of the command |
| 386 |
command = [ |
| 387 |
module.params["executable"], |
| 388 |
"generate", |
| 389 |
"systemd", |
| 390 |
] |
| 391 |
# Add the options to the commande |
| 392 |
command.extend(command_options) |
| 393 |
# Add pod or container name to the command |
| 394 |
command.append(module.params["name"]) |
| 395 |
# Build the string version of the command, only for module return |
| 396 |
command_str = " ".join(command) |
| 397 |
|
| 398 |
# Run the podman command to generated systemd .service unit(s) content |
| 399 |
return_code, stdout, stderr = module.run_command(command) |
| 400 |
|
| 401 |
# In case of error in running the command |
| 402 |
if return_code != 0: |
| 403 |
# Print information about the error and return and empty dictionary |
| 404 |
message = "Error generating systemd .service unit(s)." |
| 405 |
message += " Command executed: {command_str}" |
| 406 |
message += " Command returned with code: {return_code}." |
| 407 |
message += " Error message: {stderr}." |
| 408 |
module.fail_json( |
| 409 |
msg=message.format( |
| 410 |
command_str=command_str, |
| 411 |
return_code=return_code, |
| 412 |
stderr=stderr, |
| 413 |
), |
| 414 |
changed=changed, |
| 415 |
systemd_units={}, |
| 416 |
podman_command=command_str, |
| 417 |
) |
| 418 |
|
| 419 |
# In case of command execution success, its stdout is a json |
| 420 |
# dictionary. This dictionary is all the generated systemd units. |
| 421 |
# Each key value pair is one systemd unit. The key is the unit name |
| 422 |
# and the value is the unit content. |
| 423 |
|
| 424 |
# Load the returned json dictionary as a python dictionary |
| 425 |
systemd_units = json.loads(stdout) |
| 426 |
|
| 427 |
# Write the systemd .service unit(s) content to file(s), if |
| 428 |
# requested |
| 429 |
if module.params["dest"]: |
| 430 |
try: |
| 431 |
systemd_units_dest = module.params["dest"] |
| 432 |
# If destination don't exist |
| 433 |
if not os.path.exists(systemd_units_dest): |
| 434 |
# If not in check mode, make it |
| 435 |
if not module.check_mode: |
| 436 |
os.makedirs(systemd_units_dest) |
| 437 |
changed = True |
| 438 |
# If destination exist but not a directory |
| 439 |
if not os.path.isdir(systemd_units_dest): |
| 440 |
# Stop and tell user that the destination is not a directory |
| 441 |
message = "Destination {systemd_units_dest} is not a directory." |
| 442 |
message += " Can't save systemd unit files in." |
| 443 |
module.fail_json( |
| 444 |
msg=message.format( |
| 445 |
systemd_units_dest=systemd_units_dest, |
| 446 |
), |
| 447 |
changed=changed, |
| 448 |
systemd_units=systemd_units, |
| 449 |
podman_command=command_str, |
| 450 |
) |
| 451 |
|
| 452 |
# Write each systemd unit, if needed |
| 453 |
for unit_name, unit_content in systemd_units.items(): |
| 454 |
# Build full path to unit file |
| 455 |
unit_file_name = unit_name + ".service" |
| 456 |
unit_file_full_path = os.path.join( |
| 457 |
systemd_units_dest, |
| 458 |
unit_file_name, |
| 459 |
) |
| 460 |
|
| 461 |
if module.params["force"]: |
| 462 |
# Force to replace the existing unit file |
| 463 |
need_to_write_file = True |
| 464 |
else: |
| 465 |
# See if we need to write the unit file, default yes |
| 466 |
need_to_write_file = bool(compare_systemd_file_content(unit_file_full_path, unit_content)) |
| 467 |
|
| 468 |
# Write the file, if needed |
| 469 |
if need_to_write_file: |
| 470 |
with open(unit_file_full_path, "w") as unit_file: |
| 471 |
# If not in check mode, write the file |
| 472 |
if not module.check_mode: |
| 473 |
unit_file.write(unit_content) |
| 474 |
changed = True |
| 475 |
|
| 476 |
except Exception as exception: |
| 477 |
# When exception occurs while trying to write units file |
| 478 |
message = "PODMAN-GENERATE-SYSTEMD-DEBUG: " |
| 479 |
message += "Error writing systemd units files: " |
| 480 |
message += "{exception}" |
| 481 |
module.log( |
| 482 |
message.format(exception=exception), |
| 483 |
) |
| 484 |
# Return the systemd .service unit(s) content |
| 485 |
return changed, systemd_units, command_str |
| 486 |
|
| 487 |
|
| 488 |
def run_module(): |
| 489 |
"""Run the module on the target""" |
| 490 |
# Build the list of parameters user can use |
| 491 |
module_parameters = { |
| 492 |
"name": { |
| 493 |
"type": "str", |
| 494 |
"required": True, |
| 495 |
}, |
| 496 |
"dest": { |
| 497 |
"type": "path", |
| 498 |
"required": False, |
| 499 |
}, |
| 500 |
"new": { |
| 501 |
"type": "bool", |
| 502 |
"required": False, |
| 503 |
"default": False, |
| 504 |
}, |
| 505 |
"force": { |
| 506 |
"type": "bool", |
| 507 |
"required": False, |
| 508 |
"default": False, |
| 509 |
}, |
| 510 |
"restart_policy": { |
| 511 |
"type": "str", |
| 512 |
"required": False, |
| 513 |
"choices": RESTART_POLICY_CHOICES, |
| 514 |
}, |
| 515 |
"restart_sec": { |
| 516 |
"type": "int", |
| 517 |
"required": False, |
| 518 |
}, |
| 519 |
"start_timeout": { |
| 520 |
"type": "int", |
| 521 |
"required": False, |
| 522 |
}, |
| 523 |
"stop_timeout": { |
| 524 |
"type": "int", |
| 525 |
"required": False, |
| 526 |
}, |
| 527 |
"env": { |
| 528 |
"type": "dict", |
| 529 |
"required": False, |
| 530 |
}, |
| 531 |
"use_names": { |
| 532 |
"type": "bool", |
| 533 |
"required": False, |
| 534 |
"default": True, |
| 535 |
}, |
| 536 |
"container_prefix": { |
| 537 |
"type": "str", |
| 538 |
"required": False, |
| 539 |
}, |
| 540 |
"pod_prefix": { |
| 541 |
"type": "str", |
| 542 |
"required": False, |
| 543 |
}, |
| 544 |
"separator": { |
| 545 |
"type": "str", |
| 546 |
"required": False, |
| 547 |
}, |
| 548 |
"no_header": { |
| 549 |
"type": "bool", |
| 550 |
"required": False, |
| 551 |
"default": False, |
| 552 |
}, |
| 553 |
"after": { |
| 554 |
"type": "list", |
| 555 |
"elements": "str", |
| 556 |
"required": False, |
| 557 |
}, |
| 558 |
"wants": { |
| 559 |
"type": "list", |
| 560 |
"elements": "str", |
| 561 |
"required": False, |
| 562 |
}, |
| 563 |
"requires": { |
| 564 |
"type": "list", |
| 565 |
"elements": "str", |
| 566 |
"required": False, |
| 567 |
}, |
| 568 |
"executable": { |
| 569 |
"type": "str", |
| 570 |
"required": False, |
| 571 |
"default": "podman", |
| 572 |
}, |
| 573 |
} |
| 574 |
|
| 575 |
# Build result dictionary |
| 576 |
result = { |
| 577 |
"changed": False, |
| 578 |
"systemd_units": {}, |
| 579 |
"podman_command": "", |
| 580 |
} |
| 581 |
|
| 582 |
# Build the Ansible Module |
| 583 |
module = AnsibleModule(argument_spec=module_parameters, supports_check_mode=True) |
| 584 |
|
| 585 |
# Generate the systemd units |
| 586 |
state_changed, systemd_units, podman_command = generate_systemd(module) |
| 587 |
|
| 588 |
result["changed"] = state_changed |
| 589 |
result["systemd_units"] = systemd_units |
| 590 |
result["podman_command"] = podman_command |
| 591 |
|
| 592 |
# Return the result |
| 593 |
module.exit_json(**result) |
| 594 |
|
| 595 |
|
| 596 |
def main(): |
| 597 |
"""Main function of this script.""" |
| 598 |
run_module() |
| 599 |
|
| 600 |
|
| 601 |
if __name__ == "__main__": |
| 602 |
main() |