Search code examples
shellansibleinlinesystemctl

How to properly start Linux services with ansible shell module inline?


I'm trying to use ansible shell module in order to start a bunch of services on RHEL hosts. It works well with systemctl stop and status and lies with the start one...

ansible all -i "host1,host2," -m shell -a "systemctl start example-service" -u priv-user -K

Actually, it starts a service for 3-4s or so and outputs pid of the process, which goes down eventually.

So, some services manage to survive with the line below. Anyway, this trick is not universal...

ansible all -i "host1,host2," -m shell -a "systemctl start example-service; sleep 10" -u priv-user -K

I know playbooks can cover it with no problem with async and poll. However, I prefer to use shell module inline to quickly fix or check some minor stuff.


Solution

  • Using the shell module for that is very bad practice. You should use the service or systemd (as you are using systemd) module.

    ansible all -i "host1,host2," -m systemd -a "name=example-service state=started" -u priv-user -K
    

    Or with service:

    ansible all -i "host1,host2," -m service -a "name=example-service state=started" -u priv-user -K
    

    Documentation of the service and systemd modules.