1
0
Fork 0
mirror of https://github.com/containers/ansible-podman-collections.git synced 2026-02-04 07:11:49 +00:00

Generate systemd service files for containers (#298)

This commit is contained in:
Sergey 2021-09-13 17:13:15 +03:00 committed by GitHub
parent 53338e7ec0
commit 24329ce5d3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 147 additions and 1 deletions

View file

@ -54,6 +54,7 @@ ARGUMENTS_SPEC_CONTAINER = dict(
'exposed', 'exposed_ports']),
force_restart=dict(type='bool', default=False,
aliases=['restart']),
generate_systemd=dict(type='dict', default={}),
gidmap=dict(type='list', elements='str'),
group_add=dict(type='list', elements='str', aliases=['groups']),
healthcheck=dict(type='str'),
@ -1510,6 +1511,56 @@ class PodmanManager:
self.container = PodmanContainer(
self.module, self.name, self.module_params)
def generate_systemd(self):
"""Generate systemd unit file."""
command = [self.module_params['executable'], 'generate', 'systemd',
self.name, '--format', 'json']
sysconf = self.module_params['generate_systemd']
empty = {'name': '', 'text': ''}
if sysconf.get('restart_policy'):
if sysconf.get('restart_policy') not in [
"no", "on-success", "on-failure", "on-abnormal", "on-watchdog",
"on-abort", "always"]:
self.module.fail_json(
'Restart policy for systemd unit file is "%s" and must be one of: '
'"no", "on-success", "on-failure", "on-abnormal", "on-watchdog", "on-abort", or "always"' %
sysconf.get('restart_policy'))
command.extend([
'--restart-policy',
sysconf['restart_policy']])
if sysconf.get('time'):
command.extend(['--time', str(sysconf['time'])])
if sysconf.get('no_header'):
command.extend(['--no-header'])
if sysconf.get('names', True):
command.extend(['--name'])
if sysconf.get('container_prefix'):
command.extend(['--container-prefix=%s' % sysconf['container_prefix']])
if sysconf.get('pod_prefix'):
command.extend(['--pod-prefix=%s' % sysconf['pod_prefix']])
if sysconf.get('separator'):
command.extend(['--separator=%s' % sysconf['separator']])
if self.module.params['debug'] or self.module_params['debug']:
self.module.log("PODMAN-CONTAINER-DEBUG: systemd command: %s" % " ".join(command))
rc, systemd, err = self.module.run_command(command)
if rc != 0:
self.module.log(
"PODMAN-CONTAINER-DEBUG: Error generating systemd: %s" % err)
return empty
else:
try:
systemd_text = list(json.loads(systemd).values())[0]
systemd_name = list(json.loads(systemd).keys())[0]
if sysconf.get('file'):
with open(sysconf['file'], 'w') as f:
f.write(systemd_text)
return {'name': systemd_name,
'text': systemd_text}
except Exception as e:
self.module.log(
"PODMAN-CONTAINER-DEBUG: Error writing systemd: %s" % e)
return empty
def update_container_result(self, changed=True):
"""Inspect the current container, update results with last info, exit.
@ -1526,6 +1577,8 @@ class PodmanManager:
self.results.update({'diff': self.container.diff})
if self.module.params['debug'] or self.module_params['debug']:
self.results.update({'podman_version': self.container.version})
self.results.update(
{'podman_systemd': self.generate_systemd()})
def make_started(self):
"""Run actions if desired state is 'started'."""

View file

@ -291,6 +291,65 @@ options:
default: False
aliases:
- restart
generate_systemd:
description:
- Generate systemd unit file for container.
type: dict
default: {}
suboptions:
file:
description:
- Specify a path to the service file to be generated.
type: str
required: false
restart_policy:
description:
- Specify a restart policy for the service. The restart-policy must be one of
"no", "on-success", "on-failure", "on-abnormal", "on-watchdog", "on-abort", or "always".
The default policy is "on-failure".
type: str
required: false
choices:
- 'no'
- 'on-success'
- 'on-failure'
- 'on-abnormal'
- 'on-watchdog'
- 'on-abort'
- 'always'
time:
description:
- Override the default stop timeout for the container with the given value.
type: int
required: false
no_header:
description:
- Do not generate the header including meta data such as the Podman version and the timestamp.
From podman version 3.1.0.
type: bool
default: false
names:
description:
- Use names of the containers for the start, stop, and description in the unit file.
Default is true.
type: bool
default: true
container_prefix:
description:
- Set the systemd unit name prefix for containers. The default is "container".
type: str
required: false
pod_prefix:
description:
- Set the systemd unit name prefix for pods. The default is "pod".
type: str
required: false
separator:
description:
- Set the systemd unit name separator between the name/id of a
container/pod and the prefix. The default is "-" (dash).
type: str
required: false
gidmap:
description:
- Run the container in a new user namespace using the supplied mapping.

View file

@ -7,7 +7,9 @@
loop:
- "alpine:3.7"
- "container"
- "container1"
- "container2"
- "testidem-pod"
- name: Test no image with default action
containers.podman.podman_container:
@ -531,13 +533,42 @@
assert:
that:
- idem4 is changed
- idem4.podman_systemd.name != ''
- idem4.podman_systemd.text != ''
- name: Run container with systemd generation parameters
containers.podman.podman_container:
name: container1
image: alpine
state: started
command: sleep 20m
generate_systemd:
file: /tmp/my.service
restart_policy: always
time: 120
no_header: true
names: true
pod_prefix: whocares
separator: zzzz
container_prefix: contain
register: system1
- name: Check that container is recreated when changed
assert:
that:
- system1.podman_systemd.name == 'containzzzzcontainer1'
- system1.podman_systemd.text != ''
- "'stop -t 120 container1' in system1.podman_systemd.text"
- "'Restart=always' in system1.podman_systemd.text"
- "'autogenerated by Podman' not in system1.podman_systemd.text"
always:
- name: Remove container
containers.podman.podman_container:
name: testidem-pod
state: absent
always:
- name: Delete all container leftovers from tests
containers.podman.podman_container:
name: "{{ item }}"
@ -545,7 +576,10 @@
loop:
- "alpine:3.7"
- "container"
- "container1"
- "container2"
- "testidem-pod"
- name: Remove pod
shell: podman pod rm -f testidempod
ignore_errors: true