mirror of
https://github.com/containers/ansible-podman-collections.git
synced 2026-02-04 07:11:49 +00:00
Run black -l 120 on all Python files to unify the style (#939)
Signed-off-by: Sagi Shnaidman <sshnaidm@redhat.com>
This commit is contained in:
parent
50c5a2549d
commit
4c682e170c
39 changed files with 3828 additions and 3129 deletions
|
|
@ -7,7 +7,7 @@ from __future__ import absolute_import, division, print_function
|
|||
__metaclass__ = type
|
||||
|
||||
|
||||
DOCUMENTATION = r'''
|
||||
DOCUMENTATION = r"""
|
||||
module: podman_play
|
||||
author:
|
||||
- "Sagi Shnaidman (@sshnaidm)"
|
||||
|
|
@ -195,9 +195,9 @@ options:
|
|||
type: list
|
||||
elements: str
|
||||
required: false
|
||||
'''
|
||||
"""
|
||||
|
||||
EXAMPLES = '''
|
||||
EXAMPLES = """
|
||||
- name: Play kube file
|
||||
containers.podman.podman_play:
|
||||
kube_file: ~/kube.yaml
|
||||
|
|
@ -229,17 +229,24 @@ EXAMPLES = '''
|
|||
quadlet_options:
|
||||
- "SetWorkingDirectory=yaml"
|
||||
- "ExitCodePropagation=any"
|
||||
'''
|
||||
"""
|
||||
import re # noqa: F402
|
||||
|
||||
try:
|
||||
import yaml
|
||||
|
||||
HAS_YAML = True
|
||||
except ImportError:
|
||||
HAS_YAML = False
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule # noqa: F402
|
||||
from ansible_collections.containers.podman.plugins.module_utils.podman.common import LooseVersion, get_podman_version
|
||||
from ansible_collections.containers.podman.plugins.module_utils.podman.quadlet import create_quadlet_state # noqa: F402
|
||||
from ansible_collections.containers.podman.plugins.module_utils.podman.common import (
|
||||
LooseVersion,
|
||||
get_podman_version,
|
||||
)
|
||||
from ansible_collections.containers.podman.plugins.module_utils.podman.quadlet import (
|
||||
create_quadlet_state,
|
||||
) # noqa: F402
|
||||
|
||||
|
||||
class PodmanKubeManagement:
|
||||
|
|
@ -248,115 +255,127 @@ class PodmanKubeManagement:
|
|||
self.module = module
|
||||
self.actions = []
|
||||
self.executable = executable
|
||||
self.command = [self.executable, 'play', 'kube']
|
||||
self.command = [self.executable, "play", "kube"]
|
||||
self.version = get_podman_version(module)
|
||||
creds = []
|
||||
# pod_name = extract_pod_name(module.params['kube_file'])
|
||||
if self.module.params['annotation']:
|
||||
for k, v in self.module.params['annotation'].items():
|
||||
self.command.extend(['--annotation', '{k}={v}'.format(k=k, v=v)])
|
||||
if self.module.params['username']:
|
||||
creds += [self.module.params['username']]
|
||||
if self.module.params['password']:
|
||||
creds += [self.module.params['password']]
|
||||
if self.module.params["annotation"]:
|
||||
for k, v in self.module.params["annotation"].items():
|
||||
self.command.extend(["--annotation", "{k}={v}".format(k=k, v=v)])
|
||||
if self.module.params["username"]:
|
||||
creds += [self.module.params["username"]]
|
||||
if self.module.params["password"]:
|
||||
creds += [self.module.params["password"]]
|
||||
creds = ":".join(creds)
|
||||
self.command.extend(['--creds=%s' % creds])
|
||||
if self.module.params['network']:
|
||||
networks = ",".join(self.module.params['network'])
|
||||
self.command.extend(['--network=%s' % networks])
|
||||
if self.module.params['configmap']:
|
||||
configmaps = ",".join(self.module.params['configmap'])
|
||||
self.command.extend(['--configmap=%s' % configmaps])
|
||||
if self.module.params['log_opt']:
|
||||
for k, v in self.module.params['log_opt'].items():
|
||||
self.command.extend(['--log-opt', '{k}={v}'.format(k=k.replace('_', '-'), v=v)])
|
||||
start = self.module.params['state'] == 'started'
|
||||
self.command.extend(['--start=%s' % str(start).lower()])
|
||||
self.command.extend(["--creds=%s" % creds])
|
||||
if self.module.params["network"]:
|
||||
networks = ",".join(self.module.params["network"])
|
||||
self.command.extend(["--network=%s" % networks])
|
||||
if self.module.params["configmap"]:
|
||||
configmaps = ",".join(self.module.params["configmap"])
|
||||
self.command.extend(["--configmap=%s" % configmaps])
|
||||
if self.module.params["log_opt"]:
|
||||
for k, v in self.module.params["log_opt"].items():
|
||||
self.command.extend(
|
||||
["--log-opt", "{k}={v}".format(k=k.replace("_", "-"), v=v)]
|
||||
)
|
||||
start = self.module.params["state"] == "started"
|
||||
self.command.extend(["--start=%s" % str(start).lower()])
|
||||
for arg, param in {
|
||||
'--authfile': 'authfile',
|
||||
'--build': 'build',
|
||||
'--cert-dir': 'cert_dir',
|
||||
'--context-dir': 'context_dir',
|
||||
'--log-driver': 'log_driver',
|
||||
'--seccomp-profile-root': 'seccomp_profile_root',
|
||||
'--tls-verify': 'tls_verify',
|
||||
'--log-level': 'log_level',
|
||||
'--userns': 'userns',
|
||||
'--quiet': 'quiet',
|
||||
"--authfile": "authfile",
|
||||
"--build": "build",
|
||||
"--cert-dir": "cert_dir",
|
||||
"--context-dir": "context_dir",
|
||||
"--log-driver": "log_driver",
|
||||
"--seccomp-profile-root": "seccomp_profile_root",
|
||||
"--tls-verify": "tls_verify",
|
||||
"--log-level": "log_level",
|
||||
"--userns": "userns",
|
||||
"--quiet": "quiet",
|
||||
}.items():
|
||||
if self.module.params[param] is not None:
|
||||
self.command += ["%s=%s" % (arg, self.module.params[param])]
|
||||
if self.module.params['kube_file']:
|
||||
self.command += [self.module.params['kube_file']]
|
||||
elif self.module.params['kube_file_content']:
|
||||
self.command += ['-']
|
||||
if self.module.params["kube_file"]:
|
||||
self.command += [self.module.params["kube_file"]]
|
||||
elif self.module.params["kube_file_content"]:
|
||||
self.command += ["-"]
|
||||
|
||||
def _command_run(self, cmd):
|
||||
if self.module.params['kube_file_content']:
|
||||
rc, out, err = self.module.run_command(cmd, data=self.module.params['kube_file_content'])
|
||||
if self.module.params["kube_file_content"]:
|
||||
rc, out, err = self.module.run_command(
|
||||
cmd, data=self.module.params["kube_file_content"]
|
||||
)
|
||||
else:
|
||||
rc, out, err = self.module.run_command(cmd)
|
||||
self.actions.append(" ".join(cmd))
|
||||
if self.module.params['debug']:
|
||||
self.module.log('PODMAN-PLAY-KUBE command: %s' % " ".join(cmd))
|
||||
self.module.log('PODMAN-PLAY-KUBE stdout: %s' % out)
|
||||
self.module.log('PODMAN-PLAY-KUBE stderr: %s' % err)
|
||||
self.module.log('PODMAN-PLAY-KUBE rc: %s' % rc)
|
||||
if self.module.params["debug"]:
|
||||
self.module.log("PODMAN-PLAY-KUBE command: %s" % " ".join(cmd))
|
||||
self.module.log("PODMAN-PLAY-KUBE stdout: %s" % out)
|
||||
self.module.log("PODMAN-PLAY-KUBE stderr: %s" % err)
|
||||
self.module.log("PODMAN-PLAY-KUBE rc: %s" % rc)
|
||||
return rc, out, err
|
||||
|
||||
def tear_down_pods(self):
|
||||
'''
|
||||
"""
|
||||
Tear down the pod and contaiers by using --down option in kube play
|
||||
which is supported since Podman 3.4.0
|
||||
'''
|
||||
"""
|
||||
changed = False
|
||||
kube_file = self.module.params['kube_file']
|
||||
kube_file_content = self.module.params['kube_file_content']
|
||||
kube_file = self.module.params["kube_file"]
|
||||
kube_file_content = self.module.params["kube_file_content"]
|
||||
if kube_file:
|
||||
rc, out, err = self._command_run([self.executable, "kube", "play", "--down", kube_file])
|
||||
rc, out, err = self._command_run(
|
||||
[self.executable, "kube", "play", "--down", kube_file]
|
||||
)
|
||||
elif kube_file_content:
|
||||
rc, out, err = self._command_run([self.executable, "kube", "play", "--down", "-"])
|
||||
rc, out, err = self._command_run(
|
||||
[self.executable, "kube", "play", "--down", "-"]
|
||||
)
|
||||
if rc != 0 and "no such pod" in err:
|
||||
changed = False
|
||||
return changed, out, err
|
||||
if rc != 0:
|
||||
self.module.fail_json(msg="Failed to delete Pod with %s: %s %s" % (
|
||||
kube_file if kube_file else "YAML content", out, err))
|
||||
self.module.fail_json(
|
||||
msg="Failed to delete Pod with %s: %s %s"
|
||||
% (kube_file if kube_file else "YAML content", out, err)
|
||||
)
|
||||
|
||||
# hack to check if no resources are deleted
|
||||
for line in out.splitlines():
|
||||
if line and not line.endswith(':'):
|
||||
if line and not line.endswith(":"):
|
||||
changed = True
|
||||
break
|
||||
return changed, out, err
|
||||
|
||||
def discover_pods(self):
|
||||
pod_name = ''
|
||||
if self.module.params['kube_file']:
|
||||
pod_name = ""
|
||||
if self.module.params["kube_file"]:
|
||||
if HAS_YAML:
|
||||
with open(self.module.params['kube_file']) as f:
|
||||
with open(self.module.params["kube_file"]) as f:
|
||||
pods = list(yaml.safe_load_all(f))
|
||||
for pod in pods:
|
||||
if 'metadata' in pod and pod['kind'] in ['Deployment', 'Pod']:
|
||||
pod_name = pod['metadata'].get('name')
|
||||
if "metadata" in pod and pod["kind"] in ["Deployment", "Pod"]:
|
||||
pod_name = pod["metadata"].get("name")
|
||||
else:
|
||||
with open(self.module.params['kube_file']) as text:
|
||||
with open(self.module.params["kube_file"]) as text:
|
||||
# the following formats are matched for a kube name:
|
||||
# should match name field within metadata (2 or 4 spaces in front of name)
|
||||
# the name can be written without quotes, in single or double quotes
|
||||
# the name can contain -_
|
||||
re_pod_name = re.compile(r'^\s{2,4}name: ["|\']?(?P<pod_name>[\w|\-|\_]+)["|\']?', re.MULTILINE)
|
||||
re_pod_name = re.compile(
|
||||
r'^\s{2,4}name: ["|\']?(?P<pod_name>[\w|\-|\_]+)["|\']?',
|
||||
re.MULTILINE,
|
||||
)
|
||||
re_pod = re_pod_name.search(text.read())
|
||||
if re_pod:
|
||||
pod_name = re_pod.group(1)
|
||||
if not pod_name:
|
||||
self.module.fail_json("This Kube file doesn't have Pod or Deployment!")
|
||||
# Find all pods
|
||||
all_pods = ''
|
||||
all_pods = ""
|
||||
# In case of one pod or replicasets
|
||||
for name in ("name=%s$", "name=%s-pod-*"):
|
||||
cmd = [self.executable,
|
||||
"pod", "ps", "-q", "--filter", name % pod_name]
|
||||
cmd = [self.executable, "pod", "ps", "-q", "--filter", name % pod_name]
|
||||
rc, out, err = self._command_run(cmd)
|
||||
all_pods += out
|
||||
ids = list(set([i for i in all_pods.splitlines() if i]))
|
||||
|
|
@ -364,11 +383,12 @@ class PodmanKubeManagement:
|
|||
|
||||
def remove_associated_pods(self, pods):
|
||||
changed = False
|
||||
out_all, err_all = '', ''
|
||||
out_all, err_all = "", ""
|
||||
# Delete all pods
|
||||
for pod_id in pods:
|
||||
rc, out, err = self._command_run(
|
||||
[self.executable, "pod", "rm", "-f", pod_id])
|
||||
[self.executable, "pod", "rm", "-f", pod_id]
|
||||
)
|
||||
if rc != 0:
|
||||
self.module.fail_json("Can NOT delete Pod %s" % pod_id)
|
||||
else:
|
||||
|
|
@ -378,7 +398,9 @@ class PodmanKubeManagement:
|
|||
return changed, out_all, err_all
|
||||
|
||||
def pod_recreate(self):
|
||||
if self.version is not None and LooseVersion(self.version) >= LooseVersion('3.4.0'):
|
||||
if self.version is not None and LooseVersion(self.version) >= LooseVersion(
|
||||
"3.4.0"
|
||||
):
|
||||
self.tear_down_pods()
|
||||
else:
|
||||
pods = self.discover_pods()
|
||||
|
|
@ -392,14 +414,15 @@ class PodmanKubeManagement:
|
|||
|
||||
def play(self):
|
||||
rc, out, err = self._command_run(self.command)
|
||||
if rc != 0 and 'pod already exists' in err:
|
||||
if self.module.params['recreate']:
|
||||
if rc != 0 and "pod already exists" in err:
|
||||
if self.module.params["recreate"]:
|
||||
out, err = self.pod_recreate()
|
||||
changed = True
|
||||
else:
|
||||
changed = False
|
||||
err = "\n".join([
|
||||
i for i in err.splitlines() if 'pod already exists' not in i])
|
||||
err = "\n".join(
|
||||
[i for i in err.splitlines() if "pod already exists" not in i]
|
||||
)
|
||||
elif rc != 0:
|
||||
self.module.fail_json(msg="Output: %s\nError=%s" % (out, err))
|
||||
else:
|
||||
|
|
@ -416,63 +439,73 @@ class PodmanKubeManagement:
|
|||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec=dict(
|
||||
annotation=dict(type='dict', aliases=['annotations']),
|
||||
executable=dict(type='str', default='podman'),
|
||||
kube_file=dict(type='path'),
|
||||
kube_file_content=dict(type='str'),
|
||||
authfile=dict(type='path'),
|
||||
build=dict(type='bool'),
|
||||
cert_dir=dict(type='path'),
|
||||
configmap=dict(type='list', elements='path'),
|
||||
context_dir=dict(type='path'),
|
||||
seccomp_profile_root=dict(type='path'),
|
||||
username=dict(type='str'),
|
||||
password=dict(type='str', no_log=True),
|
||||
log_driver=dict(type='str'),
|
||||
log_opt=dict(type='dict', aliases=['log_options'], options=dict(
|
||||
path=dict(type='str'),
|
||||
max_size=dict(type='str'),
|
||||
tag=dict(type='str'))),
|
||||
network=dict(type='list', elements='str'),
|
||||
annotation=dict(type="dict", aliases=["annotations"]),
|
||||
executable=dict(type="str", default="podman"),
|
||||
kube_file=dict(type="path"),
|
||||
kube_file_content=dict(type="str"),
|
||||
authfile=dict(type="path"),
|
||||
build=dict(type="bool"),
|
||||
cert_dir=dict(type="path"),
|
||||
configmap=dict(type="list", elements="path"),
|
||||
context_dir=dict(type="path"),
|
||||
seccomp_profile_root=dict(type="path"),
|
||||
username=dict(type="str"),
|
||||
password=dict(type="str", no_log=True),
|
||||
log_driver=dict(type="str"),
|
||||
log_opt=dict(
|
||||
type="dict",
|
||||
aliases=["log_options"],
|
||||
options=dict(
|
||||
path=dict(type="str"),
|
||||
max_size=dict(type="str"),
|
||||
tag=dict(type="str"),
|
||||
),
|
||||
),
|
||||
network=dict(type="list", elements="str"),
|
||||
state=dict(
|
||||
type='str',
|
||||
choices=['started', 'created', 'absent', 'quadlet'],
|
||||
required=True),
|
||||
tls_verify=dict(type='bool'),
|
||||
debug=dict(type='bool'),
|
||||
quiet=dict(type='bool'),
|
||||
recreate=dict(type='bool'),
|
||||
userns=dict(type='str'),
|
||||
type="str",
|
||||
choices=["started", "created", "absent", "quadlet"],
|
||||
required=True,
|
||||
),
|
||||
tls_verify=dict(type="bool"),
|
||||
debug=dict(type="bool"),
|
||||
quiet=dict(type="bool"),
|
||||
recreate=dict(type="bool"),
|
||||
userns=dict(type="str"),
|
||||
log_level=dict(
|
||||
type='str',
|
||||
choices=["debug", "info", "warn", "error", "fatal", "panic"]),
|
||||
quadlet_dir=dict(type='path', required=False),
|
||||
quadlet_filename=dict(type='str', required=False),
|
||||
quadlet_file_mode=dict(type='raw', required=False),
|
||||
quadlet_options=dict(type='list', elements='str', required=False),
|
||||
type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"]
|
||||
),
|
||||
quadlet_dir=dict(type="path", required=False),
|
||||
quadlet_filename=dict(type="str", required=False),
|
||||
quadlet_file_mode=dict(type="raw", required=False),
|
||||
quadlet_options=dict(type="list", elements="str", required=False),
|
||||
),
|
||||
supports_check_mode=True,
|
||||
required_if=[
|
||||
('state', 'quadlet', ['quadlet_filename']),
|
||||
("state", "quadlet", ["quadlet_filename"]),
|
||||
],
|
||||
required_one_of=[
|
||||
('kube_file', 'kube_file_content'),
|
||||
("kube_file", "kube_file_content"),
|
||||
],
|
||||
)
|
||||
|
||||
executable = module.get_bin_path(
|
||||
module.params['executable'], required=True)
|
||||
executable = module.get_bin_path(module.params["executable"], required=True)
|
||||
manage = PodmanKubeManagement(module, executable)
|
||||
changed = False
|
||||
out = err = ''
|
||||
if module.params['state'] == 'absent':
|
||||
if manage.version is not None and LooseVersion(manage.version) > LooseVersion('3.4.0'):
|
||||
manage.module.log(msg="version: %s, kube file %s" % (manage.version, manage.module.params['kube_file']))
|
||||
out = err = ""
|
||||
if module.params["state"] == "absent":
|
||||
if manage.version is not None and LooseVersion(manage.version) > LooseVersion(
|
||||
"3.4.0"
|
||||
):
|
||||
manage.module.log(
|
||||
msg="version: %s, kube file %s"
|
||||
% (manage.version, manage.module.params["kube_file"])
|
||||
)
|
||||
changed, out, err = manage.tear_down_pods()
|
||||
else:
|
||||
pods = manage.discover_pods()
|
||||
changed, out, err = manage.remove_associated_pods(pods)
|
||||
elif module.params['state'] == 'quadlet':
|
||||
elif module.params["state"] == "quadlet":
|
||||
manage.make_quadlet()
|
||||
else:
|
||||
changed, out, err = manage.play()
|
||||
|
|
@ -480,10 +513,10 @@ def main():
|
|||
"changed": changed,
|
||||
"stdout": out,
|
||||
"stderr": err,
|
||||
"actions": manage.actions
|
||||
"actions": manage.actions,
|
||||
}
|
||||
module.exit_json(**results)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue