How to use pm2 in Ansible

pm2 is an Ansible module to manage the nodejs processes.

Sample playbook snippet for starting the nodejs application using pm2 is sharing below.

- name: Start APP
  register: npm_finished
  command: pm2 start server.js --name <app-name> chdir=<app-folder>
  ignore_errors: yes
  async: 1
  poll: 0

Here we need to replace app-name and app-folder with the corresponding values.

Please note that there are two additional parameters async and poll is there in playbook. If the nodejs process takes more time to start, there may be a chance of failing the playbook execution. To avoid this problem, we can use asynchronous mode to run this task and then poll until done. Here we need to specify its maximum run time and how frequently you would like to poll for status in playbook itself.

Sample playbook for stopping the nodejs application using pm2 is sharing below.

- name: Stop APP
  command: pm2 stop <app-name> chdir=<app-folder>
  ignore_errors: yes

Here we need to replace app-name and app-folder with the corresponding values.

That's all…

Leave a Reply