How to Stop/Start Tomcat with Ansible

, I assume that you have already installed Tomcat, Tomcat System Service, and Ansible. If you have not, please check my blog for instructions.

First we need a inventory file. Let’s create /etc/ansible/hosts file copying foloowing lines. You need to use your tomcat sever ip and user information.

[tomcat]
192.168.1.160 ansible_connection=ssh ansible_ssh_user=tomcat ansible_ssh_pass=tomcat

Now we can check the connection

ansible tomcat -m ping

if you encounter the following error, just install sshpass package with yum

FAILED! => {
“msg”: “to use the ‘ssh’ connection type with passwords or pkcs11_provider, you must install the sshpass program”
}

yum install sshpass

We succesfuly reached the tomcat server via ssh in ansible.

For disable sudo password add lines below to /etc/sudoers file in your tomcat server.

tomcat ALL=(ALL) NOPASSWD:ALL

Ok, moving on.

Let’s create a yml file to stop  tomcat service.

I will be create a stopTomcat.yml. You need to change hosts parameter with your inventory file sever alias and name parameter for tomcat service name. My inventory file sever group is “tomcat” and service name is “tomcat11”.

- hosts: tomcat
  become: yes
  tasks:
    - name: Stop Tomcat service
      ansible.builtin.service:
        name: tomcat11
        state: stopped
      register: _state

    - name : debug
      debug:
        msg : " Service {{_state.name}} is {{_state.state}}"

 

Executing with ansible-playbook

ansible-playbook stopTomcat.yml

checking service

Ok, it ‘s stopped. Now time to start. Create a startTomcat.yml file with following lines. just state paramer is changed to “started”

- hosts: tomcat
  become: yes
  tasks:
    - name: StartTomcat service
      ansible.builtin.service:
        name: tomcat11
        state: started
      register: _state

    - name : debug
      debug:
        msg : " Service {{_state.name}} is {{_state.state}}"

 

Checking service again…

Started successfuly. if you want to use restart instead of stop/start just change state to “restarted”.

Ok, that’s it!

This entry was posted in Ansible and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *