2016-05-25 21:20:08 +00:00
|
|
|
#!/usr/bin/python
|
|
|
|
# -*- coding: utf-8 -*-
|
2017-10-30 00:04:57 +00:00
|
|
|
|
|
|
|
# Copyright: (c) 2016, Brian Coca <bcoca@ansible.com>
|
Remove wildcard imports
Made the following changes:
* Removed wildcard imports
* Replaced long form of GPL header with short form
* Removed get_exception usage
* Added from __future__ boilerplate
* Adjust division operator to // where necessary
For the following files:
* web_infrastructure modules
* system modules
* linode, lxc, lxd, atomic, cloudscale, dimensiondata, ovh, packet,
profitbricks, pubnub, smartos, softlayer, univention modules
* compat dirs (disabled as its used intentionally)
2017-07-28 05:55:24 +00:00
|
|
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
|
|
|
|
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
__metaclass__ = type
|
|
|
|
|
2017-08-16 03:16:38 +00:00
|
|
|
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
2017-03-14 16:07:22 +00:00
|
|
|
'status': ['stableinterface'],
|
|
|
|
'supported_by': 'core'}
|
|
|
|
|
2016-05-25 21:20:08 +00:00
|
|
|
DOCUMENTATION = '''
|
|
|
|
module: systemd
|
|
|
|
author:
|
2017-10-30 00:04:57 +00:00
|
|
|
- Ansible Core Team
|
2016-05-25 21:20:08 +00:00
|
|
|
version_added: "2.2"
|
2017-10-30 00:04:57 +00:00
|
|
|
short_description: Manage services
|
2016-05-25 21:20:08 +00:00
|
|
|
description:
|
|
|
|
- Controls systemd services on remote hosts.
|
|
|
|
options:
|
|
|
|
name:
|
|
|
|
description:
|
2017-02-08 20:05:11 +00:00
|
|
|
- Name of the service. When using in a chroot environment you always need to specify the full name i.e. (crond.service).
|
2017-10-30 00:04:57 +00:00
|
|
|
aliases: [ service, unit ]
|
2016-05-25 21:20:08 +00:00
|
|
|
state:
|
|
|
|
description:
|
|
|
|
- C(started)/C(stopped) are idempotent actions that will not run commands unless necessary.
|
|
|
|
C(restarted) will always bounce the service. C(reloaded) will always reload.
|
2017-10-30 00:04:57 +00:00
|
|
|
choices: [ reloaded, restarted, started, stopped ]
|
2016-05-25 21:20:08 +00:00
|
|
|
enabled:
|
|
|
|
description:
|
|
|
|
- Whether the service should start on boot. B(At least one of state and enabled are required.)
|
2017-10-30 00:04:57 +00:00
|
|
|
type: bool
|
2018-02-21 01:47:29 +00:00
|
|
|
force:
|
|
|
|
description:
|
|
|
|
- Whether to override existing symlinks.
|
|
|
|
type: bool
|
|
|
|
version_added: 2.6
|
2016-05-25 21:20:08 +00:00
|
|
|
masked:
|
|
|
|
description:
|
|
|
|
- Whether the unit should be masked or not, a masked unit is impossible to start.
|
2017-10-30 00:04:57 +00:00
|
|
|
type: bool
|
2016-05-25 21:20:08 +00:00
|
|
|
daemon_reload:
|
|
|
|
description:
|
2018-12-18 18:22:57 +00:00
|
|
|
- Run daemon-reload before doing any other operations, to make sure systemd has read any changes.
|
|
|
|
- When set to C(yes), runs daemon-reload even if the module does not start or stop anything.
|
2017-10-30 00:04:57 +00:00
|
|
|
type: bool
|
2019-02-15 11:57:20 +00:00
|
|
|
default: no
|
2017-10-30 00:04:57 +00:00
|
|
|
aliases: [ daemon-reload ]
|
2018-09-22 06:13:33 +00:00
|
|
|
daemon_reexec:
|
|
|
|
description:
|
2018-12-18 18:22:57 +00:00
|
|
|
- Run daemon_reexec command before doing any other operations, the systemd manager will serialize the manager state.
|
2018-09-22 06:13:33 +00:00
|
|
|
type: bool
|
2019-02-15 11:57:20 +00:00
|
|
|
default: no
|
2018-09-22 06:13:33 +00:00
|
|
|
aliases: [ daemon-reexec ]
|
|
|
|
version_added: "2.8"
|
2016-09-12 15:08:27 +00:00
|
|
|
user:
|
|
|
|
description:
|
2018-09-06 17:24:44 +00:00
|
|
|
- (deprecated) run ``systemctl`` talking to the service manager of the calling user, rather than the service manager
|
|
|
|
of the system.
|
|
|
|
- This option is deprecated and will eventually be removed in 2.11. The ``scope`` option should be used instead.
|
2017-10-30 00:04:57 +00:00
|
|
|
type: bool
|
2019-02-15 11:57:20 +00:00
|
|
|
default: no
|
2018-08-02 23:05:20 +00:00
|
|
|
scope:
|
|
|
|
description:
|
|
|
|
- run systemctl within a given service manager scope, either as the default system scope (system),
|
|
|
|
the current user's scope (user), or the scope of all users (global).
|
2019-01-16 17:36:41 +00:00
|
|
|
- "For systemd to work with 'user', the executing user must have its own instance of dbus started (systemd requirement).
|
|
|
|
The user dbus process is normally started during normal login, but not during the run of Ansible tasks.
|
|
|
|
Otherwise you will probably get a 'Failed to connect to bus: no such file or directory' error."
|
2018-08-02 23:05:20 +00:00
|
|
|
choices: [ system, user, global ]
|
|
|
|
version_added: "2.7"
|
2016-11-06 18:47:39 +00:00
|
|
|
no_block:
|
|
|
|
description:
|
|
|
|
- Do not synchronously wait for the requested operation to finish.
|
|
|
|
Enqueued job will continue without Ansible blocking on its completion.
|
2017-10-30 00:04:57 +00:00
|
|
|
type: bool
|
2019-02-15 11:57:20 +00:00
|
|
|
default: no
|
2016-11-06 18:47:39 +00:00
|
|
|
version_added: "2.3"
|
2016-05-25 21:20:08 +00:00
|
|
|
notes:
|
2017-03-21 17:24:14 +00:00
|
|
|
- Since 2.4, one of the following options is required 'state', 'enabled', 'masked', 'daemon_reload', and all except 'daemon_reload' also require 'name'.
|
|
|
|
- Before 2.4 you always required 'name'.
|
2016-05-25 21:20:08 +00:00
|
|
|
requirements:
|
2017-10-30 00:04:57 +00:00
|
|
|
- A system managed by systemd.
|
2016-05-25 21:20:08 +00:00
|
|
|
'''
|
|
|
|
|
|
|
|
EXAMPLES = '''
|
2017-03-21 17:24:14 +00:00
|
|
|
- name: Make sure a service is running
|
2018-02-21 01:47:29 +00:00
|
|
|
systemd:
|
|
|
|
state: started
|
|
|
|
name: httpd
|
2016-11-15 20:21:47 +00:00
|
|
|
|
2017-03-21 17:24:14 +00:00
|
|
|
- name: stop service cron on debian, if running
|
2018-02-21 01:47:29 +00:00
|
|
|
systemd:
|
|
|
|
name: cron
|
|
|
|
state: stopped
|
2016-11-15 20:21:47 +00:00
|
|
|
|
2017-03-21 17:24:14 +00:00
|
|
|
- name: restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes
|
|
|
|
systemd:
|
2016-11-15 20:21:47 +00:00
|
|
|
state: restarted
|
|
|
|
daemon_reload: yes
|
|
|
|
name: crond
|
|
|
|
|
2017-03-21 17:24:14 +00:00
|
|
|
- name: reload service httpd, in all cases
|
|
|
|
systemd:
|
2016-11-15 20:21:47 +00:00
|
|
|
name: httpd
|
|
|
|
state: reloaded
|
|
|
|
|
2017-03-21 17:24:14 +00:00
|
|
|
- name: enable service httpd and ensure it is not masked
|
|
|
|
systemd:
|
2016-05-25 21:20:08 +00:00
|
|
|
name: httpd
|
|
|
|
enabled: yes
|
2016-06-06 17:50:47 +00:00
|
|
|
masked: no
|
2016-11-15 20:21:47 +00:00
|
|
|
|
2017-03-21 17:24:14 +00:00
|
|
|
- name: enable a timer for dnf-automatic
|
|
|
|
systemd:
|
2016-08-08 12:48:33 +00:00
|
|
|
name: dnf-automatic.timer
|
|
|
|
state: started
|
2018-04-20 10:44:48 +00:00
|
|
|
enabled: yes
|
2017-03-21 17:24:14 +00:00
|
|
|
|
|
|
|
- name: just force systemd to reread configs (2.4 and above)
|
2018-02-21 01:47:29 +00:00
|
|
|
systemd:
|
|
|
|
daemon_reload: yes
|
2016-05-25 21:20:08 +00:00
|
|
|
'''
|
|
|
|
|
|
|
|
RETURN = '''
|
|
|
|
status:
|
|
|
|
description: A dictionary with the key=value pairs returned from `systemctl show`
|
|
|
|
returned: success
|
|
|
|
type: complex
|
2017-04-26 14:56:13 +00:00
|
|
|
contains: {
|
2016-05-25 21:20:08 +00:00
|
|
|
"ActiveEnterTimestamp": "Sun 2016-05-15 18:28:49 EDT",
|
|
|
|
"ActiveEnterTimestampMonotonic": "8135942",
|
|
|
|
"ActiveExitTimestampMonotonic": "0",
|
|
|
|
"ActiveState": "active",
|
|
|
|
"After": "auditd.service systemd-user-sessions.service time-sync.target systemd-journald.socket basic.target system.slice",
|
|
|
|
"AllowIsolate": "no",
|
|
|
|
"Before": "shutdown.target multi-user.target",
|
|
|
|
"BlockIOAccounting": "no",
|
|
|
|
"BlockIOWeight": "1000",
|
|
|
|
"CPUAccounting": "no",
|
|
|
|
"CPUSchedulingPolicy": "0",
|
|
|
|
"CPUSchedulingPriority": "0",
|
|
|
|
"CPUSchedulingResetOnFork": "no",
|
|
|
|
"CPUShares": "1024",
|
|
|
|
"CanIsolate": "no",
|
|
|
|
"CanReload": "yes",
|
|
|
|
"CanStart": "yes",
|
|
|
|
"CanStop": "yes",
|
|
|
|
"CapabilityBoundingSet": "18446744073709551615",
|
|
|
|
"ConditionResult": "yes",
|
|
|
|
"ConditionTimestamp": "Sun 2016-05-15 18:28:49 EDT",
|
|
|
|
"ConditionTimestampMonotonic": "7902742",
|
|
|
|
"Conflicts": "shutdown.target",
|
|
|
|
"ControlGroup": "/system.slice/crond.service",
|
|
|
|
"ControlPID": "0",
|
|
|
|
"DefaultDependencies": "yes",
|
|
|
|
"Delegate": "no",
|
|
|
|
"Description": "Command Scheduler",
|
|
|
|
"DevicePolicy": "auto",
|
|
|
|
"EnvironmentFile": "/etc/sysconfig/crond (ignore_errors=no)",
|
|
|
|
"ExecMainCode": "0",
|
|
|
|
"ExecMainExitTimestampMonotonic": "0",
|
|
|
|
"ExecMainPID": "595",
|
|
|
|
"ExecMainStartTimestamp": "Sun 2016-05-15 18:28:49 EDT",
|
|
|
|
"ExecMainStartTimestampMonotonic": "8134990",
|
|
|
|
"ExecMainStatus": "0",
|
|
|
|
"ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
|
|
|
|
"ExecStart": "{ path=/usr/sbin/crond ; argv[]=/usr/sbin/crond -n $CRONDARGS ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
|
|
|
|
"FragmentPath": "/usr/lib/systemd/system/crond.service",
|
|
|
|
"GuessMainPID": "yes",
|
|
|
|
"IOScheduling": "0",
|
|
|
|
"Id": "crond.service",
|
|
|
|
"IgnoreOnIsolate": "no",
|
|
|
|
"IgnoreOnSnapshot": "no",
|
|
|
|
"IgnoreSIGPIPE": "yes",
|
|
|
|
"InactiveEnterTimestampMonotonic": "0",
|
|
|
|
"InactiveExitTimestamp": "Sun 2016-05-15 18:28:49 EDT",
|
|
|
|
"InactiveExitTimestampMonotonic": "8135942",
|
|
|
|
"JobTimeoutUSec": "0",
|
|
|
|
"KillMode": "process",
|
|
|
|
"KillSignal": "15",
|
|
|
|
"LimitAS": "18446744073709551615",
|
|
|
|
"LimitCORE": "18446744073709551615",
|
|
|
|
"LimitCPU": "18446744073709551615",
|
|
|
|
"LimitDATA": "18446744073709551615",
|
|
|
|
"LimitFSIZE": "18446744073709551615",
|
|
|
|
"LimitLOCKS": "18446744073709551615",
|
|
|
|
"LimitMEMLOCK": "65536",
|
|
|
|
"LimitMSGQUEUE": "819200",
|
|
|
|
"LimitNICE": "0",
|
|
|
|
"LimitNOFILE": "4096",
|
|
|
|
"LimitNPROC": "3902",
|
|
|
|
"LimitRSS": "18446744073709551615",
|
|
|
|
"LimitRTPRIO": "0",
|
|
|
|
"LimitRTTIME": "18446744073709551615",
|
|
|
|
"LimitSIGPENDING": "3902",
|
|
|
|
"LimitSTACK": "18446744073709551615",
|
|
|
|
"LoadState": "loaded",
|
|
|
|
"MainPID": "595",
|
|
|
|
"MemoryAccounting": "no",
|
|
|
|
"MemoryLimit": "18446744073709551615",
|
|
|
|
"MountFlags": "0",
|
|
|
|
"Names": "crond.service",
|
|
|
|
"NeedDaemonReload": "no",
|
|
|
|
"Nice": "0",
|
|
|
|
"NoNewPrivileges": "no",
|
|
|
|
"NonBlocking": "no",
|
|
|
|
"NotifyAccess": "none",
|
|
|
|
"OOMScoreAdjust": "0",
|
|
|
|
"OnFailureIsolate": "no",
|
|
|
|
"PermissionsStartOnly": "no",
|
|
|
|
"PrivateNetwork": "no",
|
|
|
|
"PrivateTmp": "no",
|
|
|
|
"RefuseManualStart": "no",
|
|
|
|
"RefuseManualStop": "no",
|
|
|
|
"RemainAfterExit": "no",
|
|
|
|
"Requires": "basic.target",
|
|
|
|
"Restart": "no",
|
|
|
|
"RestartUSec": "100ms",
|
|
|
|
"Result": "success",
|
|
|
|
"RootDirectoryStartOnly": "no",
|
|
|
|
"SameProcessGroup": "no",
|
|
|
|
"SecureBits": "0",
|
|
|
|
"SendSIGHUP": "no",
|
|
|
|
"SendSIGKILL": "yes",
|
|
|
|
"Slice": "system.slice",
|
|
|
|
"StandardError": "inherit",
|
|
|
|
"StandardInput": "null",
|
|
|
|
"StandardOutput": "journal",
|
|
|
|
"StartLimitAction": "none",
|
|
|
|
"StartLimitBurst": "5",
|
|
|
|
"StartLimitInterval": "10000000",
|
|
|
|
"StatusErrno": "0",
|
|
|
|
"StopWhenUnneeded": "no",
|
|
|
|
"SubState": "running",
|
|
|
|
"SyslogLevelPrefix": "yes",
|
|
|
|
"SyslogPriority": "30",
|
|
|
|
"TTYReset": "no",
|
|
|
|
"TTYVHangup": "no",
|
|
|
|
"TTYVTDisallocate": "no",
|
|
|
|
"TimeoutStartUSec": "1min 30s",
|
|
|
|
"TimeoutStopUSec": "1min 30s",
|
|
|
|
"TimerSlackNSec": "50000",
|
|
|
|
"Transient": "no",
|
|
|
|
"Type": "simple",
|
|
|
|
"UMask": "0022",
|
|
|
|
"UnitFileState": "enabled",
|
|
|
|
"WantedBy": "multi-user.target",
|
|
|
|
"Wants": "system.slice",
|
|
|
|
"WatchdogTimestampMonotonic": "0",
|
|
|
|
"WatchdogUSec": "0",
|
|
|
|
}
|
2017-03-23 01:50:28 +00:00
|
|
|
''' # NOQA
|
2016-05-25 21:20:08 +00:00
|
|
|
|
2019-01-16 17:36:41 +00:00
|
|
|
import os
|
|
|
|
|
2016-05-25 21:20:08 +00:00
|
|
|
from ansible.module_utils.basic import AnsibleModule
|
2019-01-14 20:45:05 +00:00
|
|
|
from ansible.module_utils.facts.system.chroot import is_chroot
|
2016-11-09 18:51:26 +00:00
|
|
|
from ansible.module_utils.service import sysv_exists, sysv_is_enabled, fail_if_missing
|
|
|
|
from ansible.module_utils._text import to_native
|
2016-05-25 21:20:08 +00:00
|
|
|
|
2016-12-15 16:14:33 +00:00
|
|
|
|
|
|
|
def is_running_service(service_status):
|
|
|
|
return service_status['ActiveState'] in set(['active', 'activating'])
|
|
|
|
|
2017-10-30 00:04:57 +00:00
|
|
|
|
2017-04-24 23:53:12 +00:00
|
|
|
def request_was_ignored(out):
|
|
|
|
return '=' not in out and 'ignoring request' in out
|
|
|
|
|
2017-10-30 00:04:57 +00:00
|
|
|
|
2017-02-23 06:41:38 +00:00
|
|
|
def parse_systemctl_show(lines):
|
|
|
|
# The output of 'systemctl show' can contain values that span multiple lines. At first glance it
|
|
|
|
# appears that such values are always surrounded by {}, so the previous version of this code
|
|
|
|
# assumed that any value starting with { was a multi-line value; it would then consume lines
|
|
|
|
# until it saw a line that ended with }. However, it is possible to have a single-line value
|
|
|
|
# that starts with { but does not end with } (this could happen in the value for Description=,
|
|
|
|
# for example), and the previous version of this code would then consume all remaining lines as
|
|
|
|
# part of that value. Cryptically, this would lead to Ansible reporting that the service file
|
|
|
|
# couldn't be found.
|
|
|
|
#
|
|
|
|
# To avoid this issue, the following code only accepts multi-line values for keys whose names
|
|
|
|
# start with Exec (e.g., ExecStart=), since these are the only keys whose values are known to
|
|
|
|
# span multiple lines.
|
|
|
|
parsed = {}
|
|
|
|
multival = []
|
|
|
|
k = None
|
|
|
|
for line in lines:
|
|
|
|
if k is None:
|
|
|
|
if '=' in line:
|
|
|
|
k, v = line.split('=', 1)
|
|
|
|
if k.startswith('Exec') and v.lstrip().startswith('{'):
|
|
|
|
if not v.rstrip().endswith('}'):
|
|
|
|
multival.append(v)
|
|
|
|
continue
|
|
|
|
parsed[k] = v.strip()
|
|
|
|
k = None
|
|
|
|
else:
|
|
|
|
multival.append(line)
|
|
|
|
if line.rstrip().endswith('}'):
|
|
|
|
parsed[k] = '\n'.join(multival).strip()
|
|
|
|
multival = []
|
|
|
|
k = None
|
|
|
|
return parsed
|
|
|
|
|
2016-12-15 16:14:33 +00:00
|
|
|
|
2016-05-25 21:20:08 +00:00
|
|
|
# ===========================================
|
|
|
|
# Main control flow
|
|
|
|
|
|
|
|
def main():
|
2016-11-09 18:51:26 +00:00
|
|
|
# initialize
|
2016-05-25 21:20:08 +00:00
|
|
|
module = AnsibleModule(
|
2017-10-30 00:04:57 +00:00
|
|
|
argument_spec=dict(
|
|
|
|
name=dict(type='str', aliases=['service', 'unit']),
|
2017-10-30 10:14:06 +00:00
|
|
|
state=dict(type='str', choices=['reloaded', 'restarted', 'started', 'stopped']),
|
2017-10-30 00:04:57 +00:00
|
|
|
enabled=dict(type='bool'),
|
2018-02-21 01:47:29 +00:00
|
|
|
force=dict(type='bool'),
|
2017-10-30 00:04:57 +00:00
|
|
|
masked=dict(type='bool'),
|
|
|
|
daemon_reload=dict(type='bool', default=False, aliases=['daemon-reload']),
|
2018-09-22 06:13:33 +00:00
|
|
|
daemon_reexec=dict(type='bool', default=False, aliases=['daemon-reexec']),
|
2018-09-06 17:24:44 +00:00
|
|
|
user=dict(type='bool'),
|
|
|
|
scope=dict(type='str', choices=['system', 'user', 'global']),
|
2017-10-30 00:04:57 +00:00
|
|
|
no_block=dict(type='bool', default=False),
|
2017-01-29 07:28:53 +00:00
|
|
|
),
|
2017-01-28 09:39:40 +00:00
|
|
|
supports_check_mode=True,
|
|
|
|
required_one_of=[['state', 'enabled', 'masked', 'daemon_reload']],
|
Introduce new 'required_by' argument_spec option (#28662)
* Introduce new "required_by' argument_spec option
This PR introduces a new **required_by** argument_spec option which allows you to say *"if parameter A is set, parameter B and C are required as well"*.
- The difference with **required_if** is that it can only add dependencies if a parameter is set to a specific value, not when it is just defined.
- The difference with **required_together** is that it has a commutative property, so: *"Parameter A and B are required together, if one of them has been defined"*.
As an example, we need this for the complex options that the xml module provides. One of the issues we often see is that users are not using the correct combination of options, and then are surprised that the module does not perform the requested action(s).
This would be solved by adding the correct dependencies, and mutual exclusives. For us this is important to get this shipped together with the new xml module in Ansible v2.4. (This is related to bugfix https://github.com/ansible/ansible/pull/28657)
```python
module = AnsibleModule(
argument_spec=dict(
path=dict(type='path', aliases=['dest', 'file']),
xmlstring=dict(type='str'),
xpath=dict(type='str'),
namespaces=dict(type='dict', default={}),
state=dict(type='str', default='present', choices=['absent',
'present'], aliases=['ensure']),
value=dict(type='raw'),
attribute=dict(type='raw'),
add_children=dict(type='list'),
set_children=dict(type='list'),
count=dict(type='bool', default=False),
print_match=dict(type='bool', default=False),
pretty_print=dict(type='bool', default=False),
content=dict(type='str', choices=['attribute', 'text']),
input_type=dict(type='str', default='yaml', choices=['xml',
'yaml']),
backup=dict(type='bool', default=False),
),
supports_check_mode=True,
required_by=dict(
add_children=['xpath'],
attribute=['value', 'xpath'],
content=['xpath'],
set_children=['xpath'],
value=['xpath'],
),
required_if=[
['count', True, ['xpath']],
['print_match', True, ['xpath']],
],
required_one_of=[
['path', 'xmlstring'],
['add_children', 'content', 'count', 'pretty_print', 'print_match', 'set_children', 'value'],
],
mutually_exclusive=[
['add_children', 'content', 'count', 'print_match','set_children', 'value'],
['path', 'xmlstring'],
],
)
```
* Rebase and fix conflict
* Add modules that use required_by functionality
* Update required_by schema
* Fix rebase issue
2019-02-15 00:57:45 +00:00
|
|
|
required_by=dict(
|
|
|
|
state=('name', ),
|
|
|
|
enabled=('name', ),
|
|
|
|
masked=('name', ),
|
|
|
|
),
|
2018-09-06 17:24:44 +00:00
|
|
|
mutually_exclusive=[['scope', 'user']],
|
2017-10-30 00:04:57 +00:00
|
|
|
)
|
2016-05-25 21:20:08 +00:00
|
|
|
|
2017-02-06 19:51:37 +00:00
|
|
|
systemctl = module.get_bin_path('systemctl', True)
|
2018-09-06 17:24:44 +00:00
|
|
|
|
2019-01-16 17:36:41 +00:00
|
|
|
if os.getenv('XDG_RUNTIME_DIR') is None:
|
|
|
|
os.environ['XDG_RUNTIME_DIR'] = '/run/user/%s' % os.geteuid()
|
|
|
|
|
2018-09-06 17:24:44 +00:00
|
|
|
''' Set CLI options depending on params '''
|
|
|
|
if module.params['user'] is not None:
|
|
|
|
# handle user deprecation, mutually exclusive with scope
|
|
|
|
module.deprecate("The 'user' option is being replaced by 'scope'", version='2.11')
|
|
|
|
if module.params['user']:
|
|
|
|
module.params['scope'] = 'user'
|
|
|
|
else:
|
|
|
|
module.params['scope'] = 'system'
|
|
|
|
|
|
|
|
# if scope is 'system' or None, we can ignore as there is no extra switch.
|
|
|
|
# The other choices match the corresponding switch
|
|
|
|
if module.params['scope'] not in (None, 'system'):
|
|
|
|
systemctl += " --%s" % module.params['scope']
|
|
|
|
|
2016-11-06 18:47:39 +00:00
|
|
|
if module.params['no_block']:
|
2018-09-06 17:24:44 +00:00
|
|
|
systemctl += " --no-block"
|
|
|
|
|
2018-02-21 01:47:29 +00:00
|
|
|
if module.params['force']:
|
2018-09-06 17:24:44 +00:00
|
|
|
systemctl += " --force"
|
|
|
|
|
2016-05-25 21:20:08 +00:00
|
|
|
unit = module.params['name']
|
|
|
|
rc = 0
|
|
|
|
out = err = ''
|
2017-10-30 00:04:57 +00:00
|
|
|
result = dict(
|
|
|
|
name=unit,
|
|
|
|
changed=False,
|
|
|
|
status=dict(),
|
|
|
|
)
|
2016-05-25 21:20:08 +00:00
|
|
|
|
2016-07-05 12:54:08 +00:00
|
|
|
# Run daemon-reload first, if requested
|
2017-10-05 22:16:11 +00:00
|
|
|
if module.params['daemon_reload'] and not module.check_mode:
|
2016-07-05 12:54:08 +00:00
|
|
|
(rc, out, err) = module.run_command("%s daemon-reload" % (systemctl))
|
|
|
|
if rc != 0:
|
|
|
|
module.fail_json(msg='failure %d during daemon-reload: %s' % (rc, err))
|
|
|
|
|
2018-09-22 06:13:33 +00:00
|
|
|
# Run daemon-reexec
|
|
|
|
if module.params['daemon_reexec'] and not module.check_mode:
|
|
|
|
(rc, out, err) = module.run_command("%s daemon-reexec" % (systemctl))
|
|
|
|
if rc != 0:
|
|
|
|
module.fail_json(msg='failure %d during daemon-reexec: %s' % (rc, err))
|
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
if unit:
|
|
|
|
found = False
|
|
|
|
is_initd = sysv_exists(unit)
|
|
|
|
is_systemd = False
|
|
|
|
|
|
|
|
# check service data, cannot error out on rc as it changes across versions, assume not found
|
|
|
|
(rc, out, err) = module.run_command("%s show '%s'" % (systemctl, unit))
|
|
|
|
|
|
|
|
if request_was_ignored(out) or request_was_ignored(err):
|
|
|
|
# fallback list-unit-files as show does not work on some systems (chroot)
|
|
|
|
# not used as primary as it skips some services (like those using init.d) and requires .service/etc notation
|
|
|
|
(rc, out, err) = module.run_command("%s list-unit-files '%s'" % (systemctl, unit))
|
|
|
|
if rc == 0:
|
|
|
|
is_systemd = True
|
|
|
|
|
|
|
|
elif rc == 0:
|
|
|
|
# load return of systemctl show into dictionary for easy access and return
|
|
|
|
if out:
|
2017-02-23 06:41:38 +00:00
|
|
|
result['status'] = parse_systemctl_show(to_native(out).split('\n'))
|
2017-04-25 00:54:14 +00:00
|
|
|
|
|
|
|
is_systemd = 'LoadState' in result['status'] and result['status']['LoadState'] != 'not-found'
|
|
|
|
|
2018-08-27 19:13:35 +00:00
|
|
|
is_masked = 'LoadState' in result['status'] and result['status']['LoadState'] == 'masked'
|
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
# Check for loading error
|
2018-08-27 19:13:35 +00:00
|
|
|
if is_systemd and not is_masked and 'LoadError' in result['status']:
|
2017-04-25 00:54:14 +00:00
|
|
|
module.fail_json(msg="Error loading unit file '%s': %s" % (unit, result['status']['LoadError']))
|
|
|
|
else:
|
|
|
|
# Check for systemctl command
|
|
|
|
module.run_command(systemctl, check_rc=True)
|
2016-05-25 21:20:08 +00:00
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
# Does service exist?
|
|
|
|
found = is_systemd or is_initd
|
|
|
|
if is_initd and not is_systemd:
|
|
|
|
module.warn('The service (%s) is actually an init script but the system is managed by systemd' % unit)
|
2016-05-25 21:20:08 +00:00
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
# mask/unmask the service, if requested, can operate on services before they are installed
|
|
|
|
if module.params['masked'] is not None:
|
|
|
|
# state is not masked unless systemd affirms otherwise
|
|
|
|
masked = ('LoadState' in result['status'] and result['status']['LoadState'] == 'masked')
|
2016-11-09 18:51:26 +00:00
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
if masked != module.params['masked']:
|
|
|
|
result['changed'] = True
|
|
|
|
if module.params['masked']:
|
|
|
|
action = 'mask'
|
|
|
|
else:
|
|
|
|
action = 'unmask'
|
2016-11-09 18:51:26 +00:00
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
if not module.check_mode:
|
|
|
|
(rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit))
|
|
|
|
if rc != 0:
|
|
|
|
# some versions of system CAN mask/unmask non existing services, we only fail on missing if they don't
|
|
|
|
fail_if_missing(module, found, unit, msg='host')
|
2016-11-09 18:51:26 +00:00
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
# Enable/disable service startup at boot if requested
|
|
|
|
if module.params['enabled'] is not None:
|
2016-05-25 21:20:08 +00:00
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
if module.params['enabled']:
|
|
|
|
action = 'enable'
|
|
|
|
else:
|
|
|
|
action = 'disable'
|
2017-01-13 21:29:29 +00:00
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
fail_if_missing(module, found, unit, msg='host')
|
|
|
|
|
|
|
|
# do we need to enable the service?
|
|
|
|
enabled = False
|
|
|
|
(rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit))
|
|
|
|
|
|
|
|
# check systemctl result or if it is a init script
|
|
|
|
if rc == 0:
|
2016-08-11 13:43:16 +00:00
|
|
|
enabled = True
|
2017-04-25 00:54:14 +00:00
|
|
|
elif rc == 1:
|
2018-08-02 23:05:20 +00:00
|
|
|
# if not a user or global user service and both init script and unit file exist stdout should have enabled/disabled, otherwise use rc entries
|
2018-09-28 16:05:48 +00:00
|
|
|
if module.params['scope'] in (None, 'system') and \
|
2018-08-02 23:05:20 +00:00
|
|
|
not module.params['user'] and \
|
2017-11-07 08:38:59 +00:00
|
|
|
is_initd and \
|
2018-09-28 16:05:48 +00:00
|
|
|
not out.strip().endswith('disabled') and \
|
|
|
|
sysv_is_enabled(unit):
|
2017-04-25 00:54:14 +00:00
|
|
|
enabled = True
|
|
|
|
|
|
|
|
# default to current state
|
|
|
|
result['enabled'] = enabled
|
2016-05-25 21:20:08 +00:00
|
|
|
|
2017-04-25 00:54:14 +00:00
|
|
|
# Change enable/disable if needed
|
|
|
|
if enabled != module.params['enabled']:
|
2016-11-09 18:51:26 +00:00
|
|
|
result['changed'] = True
|
2016-05-25 21:20:08 +00:00
|
|
|
if not module.check_mode:
|
|
|
|
(rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit))
|
|
|
|
if rc != 0:
|
2017-04-25 00:54:14 +00:00
|
|
|
module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, out + err))
|
|
|
|
|
|
|
|
result['enabled'] = not enabled
|
|
|
|
|
|
|
|
# set service state if requested
|
|
|
|
if module.params['state'] is not None:
|
|
|
|
fail_if_missing(module, found, unit, msg="host")
|
|
|
|
|
|
|
|
# default to desired state
|
|
|
|
result['state'] = module.params['state']
|
|
|
|
|
|
|
|
# What is current service state?
|
|
|
|
if 'ActiveState' in result['status']:
|
|
|
|
action = None
|
|
|
|
if module.params['state'] == 'started':
|
|
|
|
if not is_running_service(result['status']):
|
|
|
|
action = 'start'
|
|
|
|
elif module.params['state'] == 'stopped':
|
|
|
|
if is_running_service(result['status']):
|
|
|
|
action = 'stop'
|
|
|
|
else:
|
|
|
|
if not is_running_service(result['status']):
|
|
|
|
action = 'start'
|
|
|
|
else:
|
2017-10-30 00:04:57 +00:00
|
|
|
action = module.params['state'][:-2] # remove 'ed' from restarted/reloaded
|
2017-04-25 00:54:14 +00:00
|
|
|
result['state'] = 'started'
|
|
|
|
|
|
|
|
if action:
|
|
|
|
result['changed'] = True
|
|
|
|
if not module.check_mode:
|
|
|
|
(rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit))
|
|
|
|
if rc != 0:
|
|
|
|
module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, err))
|
2019-01-14 20:45:05 +00:00
|
|
|
# check for chroot
|
|
|
|
elif is_chroot():
|
|
|
|
module.warn("Target is a chroot. This can lead to false positives or prevent the init system tools from working.")
|
2017-04-25 00:54:14 +00:00
|
|
|
else:
|
|
|
|
# this should not happen?
|
|
|
|
module.fail_json(msg="Service is in unknown state", status=result['status'])
|
2016-05-25 21:20:08 +00:00
|
|
|
|
|
|
|
module.exit_json(**result)
|
|
|
|
|
2017-10-30 00:04:57 +00:00
|
|
|
|
2016-05-25 21:20:08 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|