Repository: ansible/ansible

Issue:
Service module doesn't start service, always reports changed, using `service` program
<!---
Verify first that your issue/request is not already reported on GitHub.
THIS FORM WILL BE READ BY A MACHINE, COMPLETE ALL SECTIONS AS DESCRIBED.
Also test if the latest release, and devel branch are affected too.
ALWAYS add information AFTER (OUTSIDE) these html comments.
Otherwise it may end up being automatically closed by our bot. -->

##### SUMMARY
<!--- Explain the problem briefly -->
The `service` module does not seem to do anything when instructing it to start a service. It always reports changed as well, even if the service is already started. This seems like it might be specific to machines where one uses `service`, the program (rather than for example `systemctl`)

##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
<!--- Insert, BELOW THIS COMMENT, the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path-->
service

##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.6.1
  config file = None
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0]
```

##### CONFIGURATION
<!--- If using Ansible 2.4 or above, paste, BELOW THIS COMMENT, the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).-->
Everything was using the defaults. `ansible-config dump --only-changed` did not return anything.

##### OS / ENVIRONMENT
<!--- Mention, BELOW THIS COMMENT, the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.-->
I am managing from a `ubuntu:18.04` Docker container.
I am managing another `ubuntu:18.04` Docker container.

It's probably relevant that in the container only `service` is available, and not `systemctl` for example.

Another thing that may be relevant is that when I run it from my arch host to the `ubuntu:18.04` container, it works fine. My arch is running ansible 2.5.4 though.

##### STEPS TO REPRODUCE
<!--- For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used. -->
This is using molecule to test my role in a Docker container. I'm on Arch myself, but I was having problem in my Bitbucket pipeline which runs in Docker as well. In order to reproduce the bug I first run `docker run -it -v /var/run/docker.sock:/var/run/docker.sock --memory=2048m ubuntu:18.04 bash` to get into the host container. Now I use molecule to run this in yet another container, but I'd expect the same results if you ran it on itself.

First I install the ssh-server. Then I start the service, as with the commands below. Then I run the commands once more.

<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: Install SSH server
  apt:
    name: openssh-server
    update_cache: true
    state: present
  become: true

- name: Start SSH Daemon
  service:
    name: ssh
    state: started
  become: true
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
The second run returns only `ok` messages, as the commands are idempotent. The target system has a running ssh daemon.

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->
Running this again still gets me `changed` on the starting of the service.

To my surprise, when I entered the container to see the result, it turned out the service wasn't started at all! I started it by hand using `service ssh start`, and ran the playbook again. I got `changed` again. I wondered whether perhaps it had something to do with `ssh` specifically so I tried `fail2ban` too, and it had the same problem.

Here is the output of the `ssh` example with extra verbosity in the just provided context of already having ran and started:

<!--- Paste verbatim command output between quotes below -->
```
TASK [ansible-ssh-server : Start SSH Daemon] ***********************************
    task path: /ansible-ssh-server/tasks/main.yml:24
    <instance> ESTABLISH DOCKER CONNECTION FOR USER: root
    <instance> EXEC ['/usr/bin/docker', 'exec', '-i', u'instance', u'/bin/sh', '-c', u"/bin/sh -c 'echo ~ && sleep 0'"]
    <instance> EXEC ['/usr/bin/docker', 'exec', '-i', u'instance', u'/bin/sh', '-c', u'/bin/sh -c \'( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1531308482.36-152745944531654 `" && echo ansible-tmp-1531308482.36-152745944531654="` echo /root/.ansible/tmp/ansible-tmp-1531308482.36-152745944531654 `" ) && sleep 0\'']
    Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/system/sysvinit.py
    <instance> PUT /root/.ansible/tmp/ansible-local-8097l0_bJL/tmp0ORtSX TO /root/.ansible/tmp/ansible-tmp-1531308482.36-152745944531654/sysvinit.py
    <instance> EXEC ['/usr/bin/docker', 'exec', '-i', u'instance', u'/bin/sh', '-c', u"/bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1531308482.36-152745944531654/ /root/.ansible/tmp/ansible-tmp-1531308482.36-152745944531654/sysvinit.py && sleep 0'"]
    <instance> EXEC ['/usr/bin/docker', 'exec', '-i', u'instance', u'/bin/sh', '-c', u'/bin/sh -c \'sudo -H -S -n -u root /bin/sh -c \'"\'"\'echo BECOME-SUCCESS-xlsjfjizpvhoawxolcpjseuidaoyphix; /usr/bin/python /root/.ansible/tmp/ansible-tmp-1531308482.36-152745944531654/sysvinit.py\'"\'"\' && sleep 0\'']
    <instance> EXEC ['/usr/bin/docker', 'exec', '-i', u'instance', u'/bin/sh', '-c', u"/bin/sh -c 'rm -f -r /root/.ansible/tmp/ansible-tmp-1531308482.36-152745944531654/ > /dev/null 2>&1 && sleep 0'"]
    changed: [instance] => {
        "changed": true, 
        "invocation": {
            "module_args": {
                "arguments": null, 
                "daemonize": false, 
                "enabled": null, 
                "name": "ssh", 
                "pattern": null, 
                "runlevels": null, 
                "sleep": 1, 
                "state": "started"
            }
        }, 
        "name": "ssh", 
        "status": {
            "enabled": {
                "changed": true, 
                "rc": 0, 
                "stderr": "", 
                "stdout": " * sshd is running\n"
            }, 
            "started": {
                "changed": false, 
                "rc": null, 
                "stderr": null, 
                "stdout": null
            }
        }
    }
    META: ran handlers
    META: ran handlers
```



Discussion:
Files identified in the description:
* [lib/ansible/modules/system/service.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/system/service.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
Possibly much more interesting information is the output of trying to start the service when it has not started yet. Just having a `service` task with `name: ssh` and `state: started` gets me:

```
changed: [instance] => {
        "changed": true, 
        "invocation": {
            "module_args": {
                "arguments": null, 
                "daemonize": false, 
                "enabled": null, 
                "name": "ssh", 
                "pattern": null, 
                "runlevels": null, 
                "sleep": 1, 
                "state": "started"
            }
        }, 
        "name": "ssh", 
        "status": {
            "enabled": {
                "changed": true, 
                "rc": 3, 
                "stderr": "", 
                "stdout": " * sshd is not running\n"
            }, 
            "started": {
                "changed": true, 
                "rc": 0, 
                "stderr": "Extra argument ssh.\n", 
                "stdout": " * Starting OpenBSD Secure Shell server sshd\n   ...fail!\n"
            }
        }
    }
```

Especially interesting I thought were the last `stderr` and `stdout`.
The actual command that seems to be formed [here](https://github.com/ansible/ansible/blob/stable-2.6/lib/ansible/modules/system/sysvinit.py#L302) is (I just printed it) `/etc/init.d/ssh start ssh None`. This indeed returns the `stderr` and `stdout` that we see in the previous comment. It could be one of many commands to get it working, but closest to current behavior would be `/etc/init.d/ssh start`. This would mean not using the `name` parameter (I'm not sure why that is even there) and making it so that when the arguments are empty we don't get `None` in our command.
I could start the service by replacing [this](https://github.com/ansible/ansible/blob/stable-2.6/lib/ansible/modules/system/sysvinit.py#L302) line with:

```
args = module.params['arguments']
cmd = "%s %s %s" % (script, doit, "" if args is None else args)
```

But like I said I'm not sure what this would break for others. And I still always get `changed` but not because of the `state: started`, but because of this:

```
"enabled": {
                "changed": true, 
                "rc": 0, 
                "stderr": "", 
                "stdout": ""
            }
```

Which is not even a flag I provided so it shouldn't even be doing this afaik

Resolving patch:
diff --git a/lib/ansible/modules/system/sysvinit.py b/lib/ansible/modules/system/sysvinit.py
--- a/lib/ansible/modules/system/sysvinit.py
+++ b/lib/ansible/modules/system/sysvinit.py
@@ -258,7 +258,7 @@ def main():
                 elif location.get('chkconfig'):
                     (rc, out, err) = module.run_command("%s --level %s %s off" % (location['chkconfig'], ''.join(runlevels), name))
     else:
-        if enabled != runlevel_status["enabled"]:
+        if enabled is not None and enabled != runlevel_status["enabled"]:
             result['changed'] = True
             result['status']['enabled']['changed'] = True
 
@@ -299,7 +299,9 @@ def main():
 
         def runme(doit):
 
-            cmd = "%s %s %s %s" % (script, doit, name, module.params['arguments'])
+            args = module.params['arguments']
+            cmd = "%s %s %s" % (script, doit, "" if args is None else args)
+
             # how to run
             if module.params['daemonize']:
                 (rc, out, err) = daemonize(cmd)


Test patch: