Ansible in a docker container ("Service is in unknown state" error)

Hi, I have a playbook which tried to start the nginx daemon in a docker container:

- name: start and enable nginx
  service:
    name: nginx
    state: started
    enabled: true

When I run this in docker container, based on debian:stable, it returns a fatal error:

FAILED! => {"changed": false, "msg": "Service is in unknown state", "status": {}}

Reading the docs, my first suspicion is that the service module does not pick the right service manager (e.g. it tries to interface with systemd instead of sysVinit or vice versa).

When I start/stop the service manual, it works (almost) fine:

# service nginx start
Starting nginx: nginx.
# service nginx status
nginx is running.
# service nginx stop
Stopping nginx: nginx.
# service nginx status
nginx is not running ... failed!

The only that that is odd is that status reports “failed” when it is not running, but it seem harmless, as it does work – nginx served a page to my webbrowser after it was started.

The good news is that I got my Ansible playbook working by adding the use parameter.
use: systemd fails, but any(!) other value works fine. Yes, any:

- name: start and enable nginx
  service:
    name: nginx
    state: started
    enabled: true
    use: "a turnip"

Never underestimate a good turnip, I guess.

In the mean time, I suspect that this is the underlying cause:

# /bin/systemctl
System has not been booted with systemd as init system (PID 1). Can't operate.

This is not entirely surprising; docker containers usually only contain one application, and not a whole init system.
In my case, my use case is to test the configuration of my webserver before development, and this is slightly faster than testing it on a VM.

So there you have it. In case this is useful to you, you’re welcome.

In case you have some generic advice how to debug such an issue (because the problem was not evident from the beginning to me!), or if you know more about valid values for the “use” parameter, please leave a reply. Because surely, if I leave that turnip there, and I reread the code in a year from now, I will most certainly be very confused. :slight_smile:

4 Likes

I have Docker containers running with Systemd for testing Ansible roles using Molecule via GitLab CI, see this post on the GitLab Discourse forum:

2 Likes

FYI, in the end I solved this by running systemd in the Docker container. It even works without the entrypoint.sh file, and using /usr/lib/systemd/systemd as the entrypoint in the Dockerfile. This may not work for gitlab runners (in the post from Chris on the GitLab forum), but it works for my use-case.

I also got it to work in a non-privileged Docker container, but that was a bit work work, and seems a bit error-prone. The Dockerfile and documentation can be found on https://gitlab.com/macfreek/empty-container or GitHub - macfreek/empty-container

2 Likes