Question:
I have created a script to start/stop my application. Now I want to add it as a centos system service. First I created a task to create a link from my script to /etc/init.d/service_name as below.
1 2 3 4 5 |
--- - name: create startup link file: src={{ cooltoo_service_script }} dest={{ cooltoo_service_init }} state=link |
After create the service, I want to add it to system service. The command used to do that is “chkconfig –add service_name”. I wonder whether there is a ansible module to do that instead of hardcoded the command in ansible-playbook file. I have looked at this page http://docs.ansible.com/ansible/service_module.html but it only shows how to manage a service not create a new one.
Answer:
The ‘service’ module supports an ‘enabled’ argument.
Here’s an example part of a playbook, which I will freely admit does look like a newbie attempt. This assumes RHEL/CentOS 6.x, which uses SysV, not systemd.
1 2 3 4 5 6 7 8 9 10 11 12 |
- name: install rhel sysv supervisord init script copy: src=etc/rc.d/init.d/supervisord dest=/etc/rc.d/init.d/supervisord owner=root group=root mode=0755 - name: install rhel sysv supervisord sysconfig copy: src=etc/sysconfig/supervisord dest=/etc/sysconfig/supervisord owner=root group=root mode=0640 - name: enable sysv supervisord service service: name=supervisord enabled=yes - name: start supervisord service: name=supervisord state=started |
IMPORTANT A lot of custom init scripts WILL FAIL with Ansible and SysV init; the reason being that the ‘status’ option (service supervisord status) needs to a return an LSB-compliant return code. Otherwise, Ansible will not know if a service is up or down, and idempotency will fail (restart will still work because that is unconditional)
Here’s part of a script, which I’ve just rewritten to make use of the ‘status’ function within /etc/init.d/functions (you’ll notice this same pattern in other Red Hat provided init-scripts in /etc/init.d/
1 2 3 4 5 6 7 8 9 10 |
status) /usr/bin/supervisorctl $OPTIONS status status -p $PIDFILE supervisord # The 'status' option should return one of the LSB-defined return-codes, # in particular, return-code 3 should mean that the service is not # currently running. This is particularly important for Ansible's 'service' # module, as without this behaviour it won't know if a service is up or down. RETVAL=$? ;; |
Reference: http://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
If the status action is requested, the init script will return the
following exit status codes.0 program is running or service is OK 1 program is dead and /var/run
pid file exists 2 program is dead and /var/lock lock file exists
3 program is not running 4 program or service status is unknown
5-99 reserved for future LSB use 100-149 reserved for distribution use
150-199 reserved for application use 200-254 reserved