| 1 |
#!/usr/bin/python |
| 2 |
# Copyright (c) 2020 Red Hat |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
|
| 5 |
from __future__ import absolute_import, division, print_function |
| 6 |
|
| 7 |
__metaclass__ = type |
| 8 |
|
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
module: podman_play |
| 12 |
author: |
| 13 |
- "Sagi Shnaidman (@sshnaidm)" |
| 14 |
short_description: Play kubernetes YAML file using podman |
| 15 |
notes: [] |
| 16 |
description: |
| 17 |
- The module reads in a structured file of Kubernetes YAML. |
| 18 |
It will then recreate the pod and containers described in the YAML. |
| 19 |
requirements: |
| 20 |
- "Podman installed on host" |
| 21 |
options: |
| 22 |
executable: |
| 23 |
description: |
| 24 |
- Name of executable to run, by default 'podman' |
| 25 |
type: str |
| 26 |
default: podman |
| 27 |
kube_file: |
| 28 |
description: |
| 29 |
- Path to file with YAML configuration for a Pod. |
| 30 |
type: path |
| 31 |
kube_file_content: |
| 32 |
description: |
| 33 |
- Content of the kube file. |
| 34 |
type: str |
| 35 |
annotation: |
| 36 |
description: |
| 37 |
- Add an annotation to the container or pod. |
| 38 |
type: dict |
| 39 |
aliases: |
| 40 |
- annotations |
| 41 |
authfile: |
| 42 |
description: |
| 43 |
- Path of the authentication file. Default is ${XDG_RUNTIME_DIR}/containers/auth.json, |
| 44 |
which is set using podman login. If the authorization state is not found there, |
| 45 |
$HOME/.docker/config.json is checked, which is set using docker login. |
| 46 |
Note - You can also override the default path of the authentication file |
| 47 |
by setting the REGISTRY_AUTH_FILE environment variable. export REGISTRY_AUTH_FILE=path |
| 48 |
type: path |
| 49 |
build: |
| 50 |
description: |
| 51 |
- Build images even if they are found in the local storage. |
| 52 |
- It is required to exist subdirectories matching the image names to be build. |
| 53 |
type: bool |
| 54 |
cert_dir: |
| 55 |
description: |
| 56 |
- Use certificates at path (*.crt, *.cert, *.key) to connect to the registry. |
| 57 |
Default certificates directory is /etc/containers/certs.d. |
| 58 |
(This option is not available with the remote Podman client) |
| 59 |
type: path |
| 60 |
configmap: |
| 61 |
description: |
| 62 |
- Use Kubernetes configmap YAML at path to provide a source for environment |
| 63 |
variable values within the containers of the pod. |
| 64 |
Note - The configmap option can be used multiple times to pass multiple |
| 65 |
Kubernetes configmap YAMLs |
| 66 |
type: list |
| 67 |
elements: path |
| 68 |
context_dir: |
| 69 |
description: |
| 70 |
- Use path as the build context directory for each image. |
| 71 |
Requires build option be true. |
| 72 |
type: path |
| 73 |
seccomp_profile_root: |
| 74 |
description: |
| 75 |
- Directory path for seccomp profiles (default is "/var/lib/kubelet/seccomp"). |
| 76 |
This option is not available with the remote Podman client |
| 77 |
type: path |
| 78 |
username: |
| 79 |
description: |
| 80 |
- The username and password to use to authenticate with the registry if required. |
| 81 |
type: str |
| 82 |
password: |
| 83 |
description: |
| 84 |
- The username and password to use to authenticate with the registry if required. |
| 85 |
type: str |
| 86 |
log_driver: |
| 87 |
description: |
| 88 |
- Set logging driver for all created containers. |
| 89 |
type: str |
| 90 |
log_opt: |
| 91 |
description: |
| 92 |
- Logging driver specific options. Set custom logging configuration. |
| 93 |
type: dict |
| 94 |
aliases: |
| 95 |
- log_options |
| 96 |
suboptions: |
| 97 |
path: |
| 98 |
description: |
| 99 |
- specify a path to the log file (e.g. /var/log/container/mycontainer.json). |
| 100 |
type: str |
| 101 |
required: false |
| 102 |
max_size: |
| 103 |
description: |
| 104 |
- Specify a max size of the log file (e.g 10mb). |
| 105 |
type: str |
| 106 |
required: false |
| 107 |
tag: |
| 108 |
description: |
| 109 |
- Specify a custom log tag for the container. |
| 110 |
This option is currently supported only by the journald log driver in Podman. |
| 111 |
type: str |
| 112 |
required: false |
| 113 |
log_level: |
| 114 |
description: |
| 115 |
- Set logging level for podman calls. Log messages above specified level |
| 116 |
("debug"|"info"|"warn"|"error"|"fatal"|"panic") (default "error") |
| 117 |
type: str |
| 118 |
choices: |
| 119 |
- debug |
| 120 |
- info |
| 121 |
- warn |
| 122 |
- error |
| 123 |
- fatal |
| 124 |
- panic |
| 125 |
network: |
| 126 |
description: |
| 127 |
- List of the names of CNI networks the pod should join. |
| 128 |
type: list |
| 129 |
elements: str |
| 130 |
state: |
| 131 |
description: |
| 132 |
- Start the pod after creating it, or to leave it created only. |
| 133 |
type: str |
| 134 |
choices: |
| 135 |
- created |
| 136 |
- started |
| 137 |
- absent |
| 138 |
- quadlet |
| 139 |
required: True |
| 140 |
tls_verify: |
| 141 |
description: |
| 142 |
- Require HTTPS and verify certificates when contacting registries (default is true). |
| 143 |
If explicitly set to true, then TLS verification will be used. If set to false, |
| 144 |
then TLS verification will not be used. If not specified, TLS verification will be |
| 145 |
used unless the target registry is listed as an insecure registry in registries.conf. |
| 146 |
type: bool |
| 147 |
debug: |
| 148 |
description: |
| 149 |
- Enable debug for the module. |
| 150 |
type: bool |
| 151 |
recreate: |
| 152 |
description: |
| 153 |
- If pod already exists, delete it and run the new one. |
| 154 |
type: bool |
| 155 |
quiet: |
| 156 |
description: |
| 157 |
- Hide image pulls logs from output. |
| 158 |
type: bool |
| 159 |
userns: |
| 160 |
description: |
| 161 |
- Set the user namespace mode for all the containers in a pod. |
| 162 |
It defaults to the PODMAN_USERNS environment variable. |
| 163 |
An empty value ("") means user namespaces are disabled. |
| 164 |
required: false |
| 165 |
type: str |
| 166 |
quadlet_dir: |
| 167 |
description: |
| 168 |
- Path to the directory to write quadlet file in. |
| 169 |
By default, it will be set as C(/etc/containers/systemd/) for root user, |
| 170 |
C(~/.config/containers/systemd/) for non-root users. |
| 171 |
type: path |
| 172 |
required: false |
| 173 |
quadlet_filename: |
| 174 |
description: |
| 175 |
- Name of quadlet file to write. Must be specified if state is quadlet. |
| 176 |
type: str |
| 177 |
quadlet_file_mode: |
| 178 |
description: |
| 179 |
- The permissions of the quadlet file. |
| 180 |
- The O(quadlet_file_mode) can be specified as octal numbers or as a symbolic mode (for example, V(u+rwx) or V(u=rw,g=r,o=r)). |
| 181 |
For octal numbers format, you must either add a leading zero so that Ansible's YAML parser knows it is an |
| 182 |
octal number (like V(0644) or V(01777)) or quote it (like V('644') or V('1777')) so Ansible receives a string |
| 183 |
and can do its own conversion from string into number. Giving Ansible a number without following one of these |
| 184 |
rules will end up with a decimal number which will have unexpected results. |
| 185 |
- If O(quadlet_file_mode) is not specified and the quadlet file B(does not) exist, the default V('0640') mask will be used |
| 186 |
when setting the mode for the newly created file. |
| 187 |
- If O(quadlet_file_mode) is not specified and the quadlet file B(does) exist, the mode of the existing file will be used. |
| 188 |
- Specifying O(quadlet_file_mode) is the best way to ensure files are created with the correct permissions. |
| 189 |
type: raw |
| 190 |
required: false |
| 191 |
quadlet_options: |
| 192 |
description: |
| 193 |
- Options for the quadlet file. Provide missing in usual network args |
| 194 |
options as a list of lines to add. |
| 195 |
type: list |
| 196 |
elements: str |
| 197 |
required: false |
| 198 |
""" |
| 199 |
|
| 200 |
EXAMPLES = """ |
| 201 |
- name: Play kube file |
| 202 |
containers.podman.podman_play: |
| 203 |
kube_file: ~/kube.yaml |
| 204 |
state: started |
| 205 |
|
| 206 |
- name: Recreate pod from a kube file with options |
| 207 |
containers.podman.podman_play: |
| 208 |
kube_file: ~/kube.yaml |
| 209 |
state: started |
| 210 |
recreate: true |
| 211 |
annotations: |
| 212 |
greeting: hello |
| 213 |
greet_to: world |
| 214 |
userns: host |
| 215 |
log_opt: |
| 216 |
path: /tmp/my-container.log |
| 217 |
max_size: 10mb |
| 218 |
|
| 219 |
- name: Create a Quadlet file |
| 220 |
containers.podman.podman_play: |
| 221 |
kube_file: ~/kube.yaml |
| 222 |
state: quadlet |
| 223 |
annotations: |
| 224 |
greeting: hello |
| 225 |
greet_to: world |
| 226 |
userns: host |
| 227 |
quadlet_filename: kube-pod |
| 228 |
quadlet_file_mode: '0640' |
| 229 |
quadlet_options: |
| 230 |
- "SetWorkingDirectory=yaml" |
| 231 |
- "ExitCodePropagation=any" |
| 232 |
""" |
| 233 |
import re # noqa: F402 |
| 234 |
|
| 235 |
try: |
| 236 |
import yaml |
| 237 |
|
| 238 |
HAS_YAML = True |
| 239 |
except ImportError: |
| 240 |
HAS_YAML = False |
| 241 |
|
| 242 |
from ansible.module_utils.basic import AnsibleModule # noqa: F402 |
| 243 |
from ansible_collections.containers.podman.plugins.module_utils.podman.common import ( |
| 244 |
LooseVersion, |
| 245 |
get_podman_version, |
| 246 |
) |
| 247 |
from ansible_collections.containers.podman.plugins.module_utils.podman.quadlet import ( |
| 248 |
create_quadlet_state, |
| 249 |
) # noqa: F402 |
| 250 |
|
| 251 |
|
| 252 |
class PodmanKubeManagement: |
| 253 |
|
| 254 |
def __init__(self, module, executable): |
| 255 |
self.module = module |
| 256 |
self.actions = [] |
| 257 |
self.executable = executable |
| 258 |
self.command = [self.executable, "play", "kube"] |
| 259 |
self.version = get_podman_version(module) |
| 260 |
creds = [] |
| 261 |
# pod_name = extract_pod_name(module.params['kube_file']) |
| 262 |
if self.module.params["annotation"]: |
| 263 |
for k, v in self.module.params["annotation"].items(): |
| 264 |
self.command.extend(["--annotation", "{k}={v}".format(k=k, v=v)]) |
| 265 |
if self.module.params["username"]: |
| 266 |
creds += [self.module.params["username"]] |
| 267 |
if self.module.params["password"]: |
| 268 |
creds += [self.module.params["password"]] |
| 269 |
creds = ":".join(creds) |
| 270 |
self.command.extend(["--creds=%s" % creds]) |
| 271 |
if self.module.params["network"]: |
| 272 |
networks = ",".join(self.module.params["network"]) |
| 273 |
self.command.extend(["--network=%s" % networks]) |
| 274 |
if self.module.params["configmap"]: |
| 275 |
configmaps = ",".join(self.module.params["configmap"]) |
| 276 |
self.command.extend(["--configmap=%s" % configmaps]) |
| 277 |
if self.module.params["log_opt"]: |
| 278 |
for k, v in self.module.params["log_opt"].items(): |
| 279 |
self.command.extend(["--log-opt", "{k}={v}".format(k=k.replace("_", "-"), v=v)]) |
| 280 |
start = self.module.params["state"] == "started" |
| 281 |
self.command.extend(["--start=%s" % str(start).lower()]) |
| 282 |
for arg, param in { |
| 283 |
"--authfile": "authfile", |
| 284 |
"--build": "build", |
| 285 |
"--cert-dir": "cert_dir", |
| 286 |
"--context-dir": "context_dir", |
| 287 |
"--log-driver": "log_driver", |
| 288 |
"--seccomp-profile-root": "seccomp_profile_root", |
| 289 |
"--tls-verify": "tls_verify", |
| 290 |
"--log-level": "log_level", |
| 291 |
"--userns": "userns", |
| 292 |
"--quiet": "quiet", |
| 293 |
}.items(): |
| 294 |
if self.module.params[param] is not None: |
| 295 |
self.command += ["%s=%s" % (arg, self.module.params[param])] |
| 296 |
if self.module.params["kube_file"]: |
| 297 |
self.command += [self.module.params["kube_file"]] |
| 298 |
elif self.module.params["kube_file_content"]: |
| 299 |
self.command += ["-"] |
| 300 |
|
| 301 |
def _command_run(self, cmd): |
| 302 |
if self.module.params["kube_file_content"]: |
| 303 |
rc, out, err = self.module.run_command(cmd, data=self.module.params["kube_file_content"]) |
| 304 |
else: |
| 305 |
rc, out, err = self.module.run_command(cmd) |
| 306 |
self.actions.append(" ".join(cmd)) |
| 307 |
if self.module.params["debug"]: |
| 308 |
self.module.log("PODMAN-PLAY-KUBE command: %s" % " ".join(cmd)) |
| 309 |
self.module.log("PODMAN-PLAY-KUBE stdout: %s" % out) |
| 310 |
self.module.log("PODMAN-PLAY-KUBE stderr: %s" % err) |
| 311 |
self.module.log("PODMAN-PLAY-KUBE rc: %s" % rc) |
| 312 |
return rc, out, err |
| 313 |
|
| 314 |
def tear_down_pods(self): |
| 315 |
""" |
| 316 |
Tear down the pod and contaiers by using --down option in kube play |
| 317 |
which is supported since Podman 3.4.0 |
| 318 |
""" |
| 319 |
changed = False |
| 320 |
kube_file = self.module.params["kube_file"] |
| 321 |
kube_file_content = self.module.params["kube_file_content"] |
| 322 |
if kube_file: |
| 323 |
rc, out, err = self._command_run([self.executable, "kube", "play", "--down", kube_file]) |
| 324 |
elif kube_file_content: |
| 325 |
rc, out, err = self._command_run([self.executable, "kube", "play", "--down", "-"]) |
| 326 |
if rc != 0 and "no such pod" in err: |
| 327 |
changed = False |
| 328 |
return changed, out, err |
| 329 |
if rc != 0: |
| 330 |
self.module.fail_json( |
| 331 |
msg="Failed to delete Pod with %s: %s %s" % (kube_file if kube_file else "YAML content", out, err) |
| 332 |
) |
| 333 |
|
| 334 |
# hack to check if no resources are deleted |
| 335 |
for line in out.splitlines(): |
| 336 |
if line and not line.endswith(":"): |
| 337 |
changed = True |
| 338 |
break |
| 339 |
return changed, out, err |
| 340 |
|
| 341 |
def discover_pods(self): |
| 342 |
pod_name = "" |
| 343 |
if self.module.params["kube_file"]: |
| 344 |
if HAS_YAML: |
| 345 |
with open(self.module.params["kube_file"]) as f: |
| 346 |
pods = list(yaml.safe_load_all(f)) |
| 347 |
for pod in pods: |
| 348 |
if "metadata" in pod and pod["kind"] in ["Deployment", "Pod"]: |
| 349 |
pod_name = pod["metadata"].get("name") |
| 350 |
else: |
| 351 |
with open(self.module.params["kube_file"]) as text: |
| 352 |
# the following formats are matched for a kube name: |
| 353 |
# should match name field within metadata (2 or 4 spaces in front of name) |
| 354 |
# the name can be written without quotes, in single or double quotes |
| 355 |
# the name can contain -_ |
| 356 |
re_pod_name = re.compile( |
| 357 |
r'^\s{2,4}name: ["|\']?(?P<pod_name>[\w|\-|\_]+)["|\']?', |
| 358 |
re.MULTILINE, |
| 359 |
) |
| 360 |
re_pod = re_pod_name.search(text.read()) |
| 361 |
if re_pod: |
| 362 |
pod_name = re_pod.group(1) |
| 363 |
if not pod_name: |
| 364 |
self.module.fail_json("This Kube file doesn't have Pod or Deployment!") |
| 365 |
# Find all pods |
| 366 |
all_pods = "" |
| 367 |
# In case of one pod or replicasets |
| 368 |
for name in ("name=%s$", "name=%s-pod-*"): |
| 369 |
cmd = [self.executable, "pod", "ps", "-q", "--filter", name % pod_name] |
| 370 |
rc, out, err = self._command_run(cmd) |
| 371 |
all_pods += out |
| 372 |
ids = list(set([i for i in all_pods.splitlines() if i])) |
| 373 |
return ids |
| 374 |
|
| 375 |
def remove_associated_pods(self, pods): |
| 376 |
changed = False |
| 377 |
out_all, err_all = "", "" |
| 378 |
# Delete all pods |
| 379 |
for pod_id in pods: |
| 380 |
rc, out, err = self._command_run([self.executable, "pod", "rm", "-f", pod_id]) |
| 381 |
if rc != 0: |
| 382 |
self.module.fail_json("Can NOT delete Pod %s" % pod_id) |
| 383 |
else: |
| 384 |
changed = True |
| 385 |
out_all += out |
| 386 |
err_all += err |
| 387 |
return changed, out_all, err_all |
| 388 |
|
| 389 |
def pod_recreate(self): |
| 390 |
if self.version is not None and LooseVersion(self.version) >= LooseVersion("3.4.0"): |
| 391 |
self.tear_down_pods() |
| 392 |
else: |
| 393 |
pods = self.discover_pods() |
| 394 |
self.remove_associated_pods(pods) |
| 395 |
|
| 396 |
# Create a pod |
| 397 |
rc, out, err = self._command_run(self.command) |
| 398 |
if rc != 0: |
| 399 |
self.module.fail_json("Can NOT create Pod! Error: %s" % err) |
| 400 |
return out, err |
| 401 |
|
| 402 |
def play(self): |
| 403 |
rc, out, err = self._command_run(self.command) |
| 404 |
if rc != 0 and "pod already exists" in err: |
| 405 |
if self.module.params["recreate"]: |
| 406 |
out, err = self.pod_recreate() |
| 407 |
changed = True |
| 408 |
else: |
| 409 |
changed = False |
| 410 |
err = "\n".join([i for i in err.splitlines() if "pod already exists" not in i]) |
| 411 |
elif rc != 0: |
| 412 |
self.module.fail_json(msg="Output: %s\nError=%s" % (out, err)) |
| 413 |
else: |
| 414 |
changed = True |
| 415 |
return changed, out, err |
| 416 |
|
| 417 |
def make_quadlet(self): |
| 418 |
results = {"changed": False} |
| 419 |
results_update = create_quadlet_state(self.module, "kube") |
| 420 |
results.update(results_update) |
| 421 |
self.module.exit_json(**results) |
| 422 |
|
| 423 |
|
| 424 |
def main(): |
| 425 |
module = AnsibleModule( |
| 426 |
argument_spec=dict( |
| 427 |
annotation=dict(type="dict", aliases=["annotations"]), |
| 428 |
executable=dict(type="str", default="podman"), |
| 429 |
kube_file=dict(type="path"), |
| 430 |
kube_file_content=dict(type="str"), |
| 431 |
authfile=dict(type="path"), |
| 432 |
build=dict(type="bool"), |
| 433 |
cert_dir=dict(type="path"), |
| 434 |
configmap=dict(type="list", elements="path"), |
| 435 |
context_dir=dict(type="path"), |
| 436 |
seccomp_profile_root=dict(type="path"), |
| 437 |
username=dict(type="str"), |
| 438 |
password=dict(type="str", no_log=True), |
| 439 |
log_driver=dict(type="str"), |
| 440 |
log_opt=dict( |
| 441 |
type="dict", |
| 442 |
aliases=["log_options"], |
| 443 |
options=dict( |
| 444 |
path=dict(type="str"), |
| 445 |
max_size=dict(type="str"), |
| 446 |
tag=dict(type="str"), |
| 447 |
), |
| 448 |
), |
| 449 |
network=dict(type="list", elements="str"), |
| 450 |
state=dict( |
| 451 |
type="str", |
| 452 |
choices=["started", "created", "absent", "quadlet"], |
| 453 |
required=True, |
| 454 |
), |
| 455 |
tls_verify=dict(type="bool"), |
| 456 |
debug=dict(type="bool"), |
| 457 |
quiet=dict(type="bool"), |
| 458 |
recreate=dict(type="bool"), |
| 459 |
userns=dict(type="str"), |
| 460 |
log_level=dict(type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"]), |
| 461 |
quadlet_dir=dict(type="path", required=False), |
| 462 |
quadlet_filename=dict(type="str", required=False), |
| 463 |
quadlet_file_mode=dict(type="raw", required=False), |
| 464 |
quadlet_options=dict(type="list", elements="str", required=False), |
| 465 |
), |
| 466 |
supports_check_mode=True, |
| 467 |
required_if=[ |
| 468 |
("state", "quadlet", ["quadlet_filename"]), |
| 469 |
], |
| 470 |
required_one_of=[ |
| 471 |
("kube_file", "kube_file_content"), |
| 472 |
], |
| 473 |
) |
| 474 |
|
| 475 |
executable = module.get_bin_path(module.params["executable"], required=True) |
| 476 |
manage = PodmanKubeManagement(module, executable) |
| 477 |
changed = False |
| 478 |
out = err = "" |
| 479 |
if module.params["state"] == "absent": |
| 480 |
if manage.version is not None and LooseVersion(manage.version) > LooseVersion("3.4.0"): |
| 481 |
manage.module.log(msg="version: %s, kube file %s" % (manage.version, manage.module.params["kube_file"])) |
| 482 |
changed, out, err = manage.tear_down_pods() |
| 483 |
else: |
| 484 |
pods = manage.discover_pods() |
| 485 |
changed, out, err = manage.remove_associated_pods(pods) |
| 486 |
elif module.params["state"] == "quadlet": |
| 487 |
manage.make_quadlet() |
| 488 |
else: |
| 489 |
changed, out, err = manage.play() |
| 490 |
results = { |
| 491 |
"changed": changed, |
| 492 |
"stdout": out, |
| 493 |
"stderr": err, |
| 494 |
"actions": manage.actions, |
| 495 |
} |
| 496 |
module.exit_json(**results) |
| 497 |
|
| 498 |
|
| 499 |
if __name__ == "__main__": |
| 500 |
main() |