We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Delegation of service action fails when using different init systems
Hello ansible devs,
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

`service` action, as determined by `lib/ansible/plugins/action/service.py`
##### ANSIBLE VERSION

```
ansible 2.2.0 (devel 1c33b5a9f0) last updated 2016/08/30 09:23:53 (GMT +200)
  lib/ansible/modules/core: (detached HEAD 5310bab12f) last updated 2016/08/30 09:23:59 (GMT +200)
  lib/ansible/modules/extras: (detached HEAD 2ef4a34eee) last updated 2016/08/30 09:23:59 (GMT +200)
  config file = 
  configured module search path = Default w/o overrides
```
##### CONFIGURATION

nothing specific to this bug
##### OS / ENVIRONMENT

Debian stretch/testing on amd64, clients are wheezy systems running sysvinit and jessie systems running systemd.
##### SUMMARY

Depending on the gathered host systems facts, ansible decides which `service_mgr` to use. On systemd systems, this is going to be `systemd`, on sysvinit systems, it's `service` and so on. The problem is, when delegating a service action from a system running systemd to a system running something else, ansible still uses the systemd service_mgr, which obviously fails.

A workaround is forcing the action to `service` with the un(der)documented `use` option as shown in the third play.
##### STEPS TO REPRODUCE

consider the following playbook. on some_sysvinit_host, the icinga service needs to be restarted. This fails when that action is delegated and no special care is taken to work around the bug:

```
- hosts: monitoring_running_sysvinit
  name: Verify that direct service restart works
  tasks:
    - service: name=icinga state=restarted

- hosts: client_with_systemd
  name: Check whether it falls back to generic action w/o facts
  gather_facts: false
  tasks:
    - service: name=icinga state=restarted
      delegate_to: monitoring_running_sysvinit

- hosts: client_with_systemd
  name: Delegated to host running sysvinit, force 'service' handler
  tasks:
    - service: name=icinga state=restarted use=service
      delegate_to: monitoring_running_sysvinit

- hosts: client_with_systemd
  name: Delegated to host running sysvinit
  tasks:
    - service: name=icinga state=restarted
      delegate_to: monitoring_running_sysvinit
```
##### EXPECTED RESULTS

All four actions should restart the icinga service on monitoring_running_sysvinit successfully.
##### ACTUAL RESULTS

The first action, running directly on the monitoring_running_sysvinit host restarts correctly.

Delegation works when we're working around the bug by either not gathering facts (and so, forcing client_with_systemd's service_mgr to the fallback `service`) or by overwriting the helper action to `service` by setting the `use` action for the delegated service action.

When just delegating from the systemd host to the sysvinit (or any other combination), the incompatible action fails:

```
$ ansible-playbook test-delegation-service.yml  --sudo --verbose --diff
PLAY [Verify that direct service restart works] ********************************

TASK [setup] *******************************************************************
ok: [monitoring_running_sysvinit]

TASK [service] *****************************************************************
changed: [monitoring_running_sysvinit] => {"changed": true, "name": "icinga", "state": "started"}

PLAY [Check whether it falls back to generic action w/o facts] *****************

TASK [service] *****************************************************************
changed: [client_with_systemd -> monitoring_running_sysvinit] => {"changed": true, "name": "icinga", "state": "started"}

PLAY [Delegated to host running sysvinit, force 'service' handler] *************

TASK [setup] *******************************************************************
ok: [client_with_systemd]

TASK [service] *****************************************************************
changed: [client_with_systemd -> monitoring_running_sysvinit] => {"changed": true, "name": "icinga", "state": "started"}

PLAY [Delegated to host running sysvinit] **************************************

TASK [setup] *******************************************************************
ok: [client_with_systemd]

TASK [service] *****************************************************************
fatal: [client_with_systemd -> monitoring_running_sysvinit]: FAILED! => {"changed": false, "cmd": "None show icinga", "failed": true, "msg": "[Errno 2] No such file or directory", "rc": 2}
        to retry, use: --limit @test-delegation-service.retry

PLAY RECAP *********************************************************************
client_with_systemd               : ok=4    changed=2    unreachable=0    failed=1   
monitoring_running_sysvinit       : ok=2    changed=1    unreachable=0    failed=0   

```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `lib/ansible/plugins/action/service.py`
Content:
```
1 # (c) 2015, Ansible Inc,
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
17 from __future__ import (absolute_import, division, print_function)
18 __metaclass__ = type
19 
20 
21 from ansible.plugins.action import ActionBase
22 
23 
24 class ActionModule(ActionBase):
25 
26     TRANSFERS_FILES = False
27 
28     UNUSED_PARAMS = {
29         'systemd': ['pattern', 'runlevels', 'sleep', 'arguments'],
30     }
31 
32     def run(self, tmp=None, task_vars=None):
33         ''' handler for package operations '''
34         if task_vars is None:
35             task_vars = dict()
36 
37         result = super(ActionModule, self).run(tmp, task_vars)
38 
39         module = self._task.args.get('use', 'auto').lower()
40 
41         if module == 'auto':
42             try:
43                 module = self._templar.template('{{ansible_service_mgr}}')
44             except:
45                 pass # could not get it from template!
46 
47         if module == 'auto':
48             facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars)
49             self._display.debug("Facts %s" % facts)
50             if 'ansible_facts' in facts and  'ansible_service_mgr' in facts['ansible_facts']:
51                 module = facts['ansible_facts']['ansible_service_mgr']
52 
53         if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader:
54             module = 'service'
55 
56         if module != 'auto':
57             # run the 'service' module
58             new_module_args = self._task.args.copy()
59             if 'use' in new_module_args:
60                 del new_module_args['use']
61 
62             # for backwards compatibility
63             if 'state' in new_module_args and new_module_args['state'] == 'running':
64                 new_module_args['state'] = 'started'
65 
66             if module in self.UNUSED_PARAMS:
67                 for unused in self.UNUSED_PARAMS[module]:
68                     if unused in new_module_args:
69                         del new_module_args[unused]
70                         self._display.warning('Ignoring "%s" as it is not used in "%s"' % (unused, module))
71 
72             self._display.vvvv("Running %s" % module)
73             result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))
74         else:
75             result['failed'] = True
76             result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the "use" option.'
77 
78         return result
79
```

Path: `lib/ansible/plugins/action/package.py`
Content:
```
1 # (c) 2015, Ansible Inc,
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
17 from __future__ import (absolute_import, division, print_function)
18 __metaclass__ = type
19 
20 from ansible.plugins.action import ActionBase
21 
22 try:
23     from __main__ import display
24 except ImportError:
25     from ansible.utils.display import Display
26     display = Display()
27 
28 
29 class ActionModule(ActionBase):
30 
31     TRANSFERS_FILES = False
32 
33     def run(self, tmp=None, task_vars=None):
34         ''' handler for package operations '''
35         if task_vars is None:
36             task_vars = dict()
37 
38         result = super(ActionModule, self).run(tmp, task_vars)
39 
40         module = self._task.args.get('use', 'auto')
41 
42         if module == 'auto':
43             try:
44                 module = self._templar.template('{{ansible_pkg_mgr}}')
45             except:
46                 pass # could not get it from template!
47 
48         if module == 'auto':
49             facts = self._execute_module(module_name='setup', module_args=dict(filter='ansible_pkg_mgr', gather_subset='!all'), task_vars=task_vars)
50             display.debug("Facts %s" % facts)
51             if 'ansible_facts' in facts and  'ansible_pkg_mgr' in facts['ansible_facts']:
52                 module = getattr(facts['ansible_facts'], 'ansible_pkg_mgr', 'auto')
53 
54         if module != 'auto':
55 
56             if module not in self._shared_loader_obj.module_loader:
57                 result['failed'] = True
58                 result['msg'] = 'Could not find a module for %s.' % module
59                 return result
60 
61             # run the 'package' module
62             new_module_args = self._task.args.copy()
63             if 'use' in new_module_args:
64                 del new_module_args['use']
65 
66             display.vvvv("Running %s" % module)
67             result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))
68             return result
69         else:
70             result['failed'] = True
71             result['msg'] = 'Could not detect which package manager to use. Try gathering facts or setting the "use" option.'
72             return result
73
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/lib/ansible/plugins/action/package.py b/lib/ansible/plugins/action/package.py
--- a/lib/ansible/plugins/action/package.py
+++ b/lib/ansible/plugins/action/package.py
@@ -41,7 +41,10 @@
 
         if module == 'auto':
             try:
-                module = self._templar.template('{{ansible_pkg_mgr}}')
+                if self._task.delegate_to: # if we delegate, we should use delegated host's facts
+                    module = self._templar.template("{{hostvars['%s']['ansible_pkg_mgr']}}" % self._task.delegate_to)
+                else:
+                    module = self._templar.template('{{ansible_pkg_mgr}}')
             except:
                 pass # could not get it from template!
 
diff --git a/lib/ansible/plugins/action/service.py b/lib/ansible/plugins/action/service.py
--- a/lib/ansible/plugins/action/service.py
+++ b/lib/ansible/plugins/action/service.py
@@ -40,7 +40,10 @@
 
         if module == 'auto':
             try:
-                module = self._templar.template('{{ansible_service_mgr}}')
+                if self._task.delegate_to: # if we delegate, we should use delegated host's facts
+                    module = self._templar.template("{{hostvars['%s']['ansible_service_mgr']}}" % self._task.delegate_to)
+                else:
+                    module = self._templar.template('{{ansible_service_mgr}}')
             except:
                 pass # could not get it from template!

{"golden_diff": "diff --git a/lib/ansible/plugins/action/package.py b/lib/ansible/plugins/action/package.py\n--- a/lib/ansible/plugins/action/package.py\n+++ b/lib/ansible/plugins/action/package.py\n@@ -41,7 +41,10 @@\n \n         if module == 'auto':\n             try:\n-                module = self._templar.template('{{ansible_pkg_mgr}}')\n+                if self._task.delegate_to: # if we delegate, we should use delegated host's facts\n+                    module = self._templar.template(\"{{hostvars['%s']['ansible_pkg_mgr']}}\" % self._task.delegate_to)\n+                else:\n+                    module = self._templar.template('{{ansible_pkg_mgr}}')\n             except:\n                 pass # could not get it from template!\n \ndiff --git a/lib/ansible/plugins/action/service.py b/lib/ansible/plugins/action/service.py\n--- a/lib/ansible/plugins/action/service.py\n+++ b/lib/ansible/plugins/action/service.py\n@@ -40,7 +40,10 @@\n \n         if module == 'auto':\n             try:\n-                module = self._templar.template('{{ansible_service_mgr}}')\n+                if self._task.delegate_to: # if we delegate, we should use delegated host's facts\n+                    module = self._templar.template(\"{{hostvars['%s']['ansible_service_mgr']}}\" % self._task.delegate_to)\n+                else:\n+                    module = self._templar.template('{{ansible_service_mgr}}')\n             except:\n                 pass # could not get it from template!\n", "issue": "Delegation of service action fails when using different init systems\nHello ansible devs,\n##### ISSUE TYPE\n- Bug Report\n##### COMPONENT NAME\n\n`service` action, as determined by `lib/ansible/plugins/action/service.py`\n##### ANSIBLE VERSION\n\n```\nansible 2.2.0 (devel 1c33b5a9f0) last updated 2016/08/30 09:23:53 (GMT +200)\n  lib/ansible/modules/core: (detached HEAD 5310bab12f) last updated 2016/08/30 09:23:59 (GMT +200)\n  lib/ansible/modules/extras: (detached HEAD 2ef4a34eee) last updated 2016/08/30 09:23:59 (GMT +200)\n  config file = \n  configured module search path = Default w/o overrides\n```\n##### CONFIGURATION\n\nnothing specific to this bug\n##### OS / ENVIRONMENT\n\nDebian stretch/testing on amd64, clients are wheezy systems running sysvinit and jessie systems running systemd.\n##### SUMMARY\n\nDepending on the gathered host systems facts, ansible decides which `service_mgr` to use. On systemd systems, this is going to be `systemd`, on sysvinit systems, it's `service` and so on. The problem is, when delegating a service action from a system running systemd to a system running something else, ansible still uses the systemd service_mgr, which obviously fails.\n\nA workaround is forcing the action to `service` with the un(der)documented `use` option as shown in the third play.\n##### STEPS TO REPRODUCE\n\nconsider the following playbook. on some_sysvinit_host, the icinga service needs to be restarted. This fails when that action is delegated and no special care is taken to work around the bug:\n\n```\n- hosts: monitoring_running_sysvinit\n  name: Verify that direct service restart works\n  tasks:\n    - service: name=icinga state=restarted\n\n- hosts: client_with_systemd\n  name: Check whether it falls back to generic action w/o facts\n  gather_facts: false\n  tasks:\n    - service: name=icinga state=restarted\n      delegate_to: monitoring_running_sysvinit\n\n- hosts: client_with_systemd\n  name: Delegated to host running sysvinit, force 'service' handler\n  tasks:\n    - service: name=icinga state=restarted use=service\n      delegate_to: monitoring_running_sysvinit\n\n- hosts: client_with_systemd\n  name: Delegated to host running sysvinit\n  tasks:\n    - service: name=icinga state=restarted\n      delegate_to: monitoring_running_sysvinit\n```\n##### EXPECTED RESULTS\n\nAll four actions should restart the icinga service on monitoring_running_sysvinit successfully.\n##### ACTUAL RESULTS\n\nThe first action, running directly on the monitoring_running_sysvinit host restarts correctly.\n\nDelegation works when we're working around the bug by either not gathering facts (and so, forcing client_with_systemd's service_mgr to the fallback `service`) or by overwriting the helper action to `service` by setting the `use` action for the delegated service action.\n\nWhen just delegating from the systemd host to the sysvinit (or any other combination), the incompatible action fails:\n\n```\n$ ansible-playbook test-delegation-service.yml  --sudo --verbose --diff\nPLAY [Verify that direct service restart works] ********************************\n\nTASK [setup] *******************************************************************\nok: [monitoring_running_sysvinit]\n\nTASK [service] *****************************************************************\nchanged: [monitoring_running_sysvinit] => {\"changed\": true, \"name\": \"icinga\", \"state\": \"started\"}\n\nPLAY [Check whether it falls back to generic action w/o facts] *****************\n\nTASK [service] *****************************************************************\nchanged: [client_with_systemd -> monitoring_running_sysvinit] => {\"changed\": true, \"name\": \"icinga\", \"state\": \"started\"}\n\nPLAY [Delegated to host running sysvinit, force 'service' handler] *************\n\nTASK [setup] *******************************************************************\nok: [client_with_systemd]\n\nTASK [service] *****************************************************************\nchanged: [client_with_systemd -> monitoring_running_sysvinit] => {\"changed\": true, \"name\": \"icinga\", \"state\": \"started\"}\n\nPLAY [Delegated to host running sysvinit] **************************************\n\nTASK [setup] *******************************************************************\nok: [client_with_systemd]\n\nTASK [service] *****************************************************************\nfatal: [client_with_systemd -> monitoring_running_sysvinit]: FAILED! => {\"changed\": false, \"cmd\": \"None show icinga\", \"failed\": true, \"msg\": \"[Errno 2] No such file or directory\", \"rc\": 2}\n        to retry, use: --limit @test-delegation-service.retry\n\nPLAY RECAP *********************************************************************\nclient_with_systemd               : ok=4    changed=2    unreachable=0    failed=1   \nmonitoring_running_sysvinit       : ok=2    changed=1    unreachable=0    failed=0   \n\n```\n\n", "before_files": [{"content": "# (c) 2015, Ansible Inc,\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\n\nfrom ansible.plugins.action import ActionBase\n\n\nclass ActionModule(ActionBase):\n\n    TRANSFERS_FILES = False\n\n    UNUSED_PARAMS = {\n        'systemd': ['pattern', 'runlevels', 'sleep', 'arguments'],\n    }\n\n    def run(self, tmp=None, task_vars=None):\n        ''' handler for package operations '''\n        if task_vars is None:\n            task_vars = dict()\n\n        result = super(ActionModule, self).run(tmp, task_vars)\n\n        module = self._task.args.get('use', 'auto').lower()\n\n        if module == 'auto':\n            try:\n                module = self._templar.template('{{ansible_service_mgr}}')\n            except:\n                pass # could not get it from template!\n\n        if module == 'auto':\n            facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars)\n            self._display.debug(\"Facts %s\" % facts)\n            if 'ansible_facts' in facts and  'ansible_service_mgr' in facts['ansible_facts']:\n                module = facts['ansible_facts']['ansible_service_mgr']\n\n        if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader:\n            module = 'service'\n\n        if module != 'auto':\n            # run the 'service' module\n            new_module_args = self._task.args.copy()\n            if 'use' in new_module_args:\n                del new_module_args['use']\n\n            # for backwards compatibility\n            if 'state' in new_module_args and new_module_args['state'] == 'running':\n                new_module_args['state'] = 'started'\n\n            if module in self.UNUSED_PARAMS:\n                for unused in self.UNUSED_PARAMS[module]:\n                    if unused in new_module_args:\n                        del new_module_args[unused]\n                        self._display.warning('Ignoring \"%s\" as it is not used in \"%s\"' % (unused, module))\n\n            self._display.vvvv(\"Running %s\" % module)\n            result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))\n        else:\n            result['failed'] = True\n            result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the \"use\" option.'\n\n        return result\n", "path": "lib/ansible/plugins/action/service.py"}, {"content": "# (c) 2015, Ansible Inc,\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nfrom ansible.plugins.action import ActionBase\n\ntry:\n    from __main__ import display\nexcept ImportError:\n    from ansible.utils.display import Display\n    display = Display()\n\n\nclass ActionModule(ActionBase):\n\n    TRANSFERS_FILES = False\n\n    def run(self, tmp=None, task_vars=None):\n        ''' handler for package operations '''\n        if task_vars is None:\n            task_vars = dict()\n\n        result = super(ActionModule, self).run(tmp, task_vars)\n\n        module = self._task.args.get('use', 'auto')\n\n        if module == 'auto':\n            try:\n                module = self._templar.template('{{ansible_pkg_mgr}}')\n            except:\n                pass # could not get it from template!\n\n        if module == 'auto':\n            facts = self._execute_module(module_name='setup', module_args=dict(filter='ansible_pkg_mgr', gather_subset='!all'), task_vars=task_vars)\n            display.debug(\"Facts %s\" % facts)\n            if 'ansible_facts' in facts and  'ansible_pkg_mgr' in facts['ansible_facts']:\n                module = getattr(facts['ansible_facts'], 'ansible_pkg_mgr', 'auto')\n\n        if module != 'auto':\n\n            if module not in self._shared_loader_obj.module_loader:\n                result['failed'] = True\n                result['msg'] = 'Could not find a module for %s.' % module\n                return result\n\n            # run the 'package' module\n            new_module_args = self._task.args.copy()\n            if 'use' in new_module_args:\n                del new_module_args['use']\n\n            display.vvvv(\"Running %s\" % module)\n            result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))\n            return result\n        else:\n            result['failed'] = True\n            result['msg'] = 'Could not detect which package manager to use. Try gathering facts or setting the \"use\" option.'\n            return result\n", "path": "lib/ansible/plugins/action/package.py"}], "after_files": [{"content": "# (c) 2015, Ansible Inc,\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\n\nfrom ansible.plugins.action import ActionBase\n\n\nclass ActionModule(ActionBase):\n\n    TRANSFERS_FILES = False\n\n    UNUSED_PARAMS = {\n        'systemd': ['pattern', 'runlevels', 'sleep', 'arguments'],\n    }\n\n    def run(self, tmp=None, task_vars=None):\n        ''' handler for package operations '''\n        if task_vars is None:\n            task_vars = dict()\n\n        result = super(ActionModule, self).run(tmp, task_vars)\n\n        module = self._task.args.get('use', 'auto').lower()\n\n        if module == 'auto':\n            try:\n                if self._task.delegate_to: # if we delegate, we should use delegated host's facts\n                    module = self._templar.template(\"{{hostvars['%s']['ansible_service_mgr']}}\" % self._task.delegate_to)\n                else:\n                    module = self._templar.template('{{ansible_service_mgr}}')\n            except:\n                pass # could not get it from template!\n\n        if module == 'auto':\n            facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars)\n            self._display.debug(\"Facts %s\" % facts)\n            if 'ansible_facts' in facts and  'ansible_service_mgr' in facts['ansible_facts']:\n                module = facts['ansible_facts']['ansible_service_mgr']\n\n        if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader:\n            module = 'service'\n\n        if module != 'auto':\n            # run the 'service' module\n            new_module_args = self._task.args.copy()\n            if 'use' in new_module_args:\n                del new_module_args['use']\n\n            # for backwards compatibility\n            if 'state' in new_module_args and new_module_args['state'] == 'running':\n                new_module_args['state'] = 'started'\n\n            if module in self.UNUSED_PARAMS:\n                for unused in self.UNUSED_PARAMS[module]:\n                    if unused in new_module_args:\n                        del new_module_args[unused]\n                        self._display.warning('Ignoring \"%s\" as it is not used in \"%s\"' % (unused, module))\n\n            self._display.vvvv(\"Running %s\" % module)\n            result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))\n        else:\n            result['failed'] = True\n            result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the \"use\" option.'\n\n        return result\n", "path": "lib/ansible/plugins/action/service.py"}, {"content": "# (c) 2015, Ansible Inc,\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nfrom ansible.plugins.action import ActionBase\n\ntry:\n    from __main__ import display\nexcept ImportError:\n    from ansible.utils.display import Display\n    display = Display()\n\n\nclass ActionModule(ActionBase):\n\n    TRANSFERS_FILES = False\n\n    def run(self, tmp=None, task_vars=None):\n        ''' handler for package operations '''\n        if task_vars is None:\n            task_vars = dict()\n\n        result = super(ActionModule, self).run(tmp, task_vars)\n\n        module = self._task.args.get('use', 'auto')\n\n        if module == 'auto':\n            try:\n                if self._task.delegate_to: # if we delegate, we should use delegated host's facts\n                    module = self._templar.template(\"{{hostvars['%s']['ansible_pkg_mgr']}}\" % self._task.delegate_to)\n                else:\n                    module = self._templar.template('{{ansible_pkg_mgr}}')\n            except:\n                pass # could not get it from template!\n\n        if module == 'auto':\n            facts = self._execute_module(module_name='setup', module_args=dict(filter='ansible_pkg_mgr', gather_subset='!all'), task_vars=task_vars)\n            display.debug(\"Facts %s\" % facts)\n            if 'ansible_facts' in facts and  'ansible_pkg_mgr' in facts['ansible_facts']:\n                module = getattr(facts['ansible_facts'], 'ansible_pkg_mgr', 'auto')\n\n        if module != 'auto':\n\n            if module not in self._shared_loader_obj.module_loader:\n                result['failed'] = True\n                result['msg'] = 'Could not find a module for %s.' % module\n                return result\n\n            # run the 'package' module\n            new_module_args = self._task.args.copy()\n            if 'use' in new_module_args:\n                del new_module_args['use']\n\n            display.vvvv(\"Running %s\" % module)\n            result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))\n            return result\n        else:\n            result['failed'] = True\n            result['msg'] = 'Could not detect which package manager to use. Try gathering facts or setting the \"use\" option.'\n            return result\n", "path": "lib/ansible/plugins/action/package.py"}]}