using pm2 with ansible

Viewed 8781

I am trying to start a node program using pm2 via ansible. The problem is that the pm2 start command is not idempotent under ansible. It gives error when run again.

This is my ansible play

- name: start the application
  become_user: ubuntu
  command: pm2 start app.js -i max
  tags: 
    - app

Now if i run this the first time then it runs properly but when i run this again then i get the error telling me that the script is already running.

What would be the correct way to get around this error and handle pm2 properly via ansible.

4 Answers

I would use

pm2 reload app.js -i max

It will allow you to reload configuration ;-)

I ended up on this page looking for a solution to start PM2 multiple times when I rerun my playbook. I also wanted PM2 to reload the server when it was already running and pickup the new code I might have deployed. It turns out that PM2 has such an interface:

- name: Start/reload server 
  command: '{{path_to_deployed_pm2}} startOrReload pm2.ecosystem.config.js'

The startOrReload command requires a so-called "ecosystem" file to be present. See the documentation for more details: Ecosystem File.

This is a minimal pm2.ecosystem.config.js that is working for me:

module.exports = {
  apps : [{
    script: 'app.js',
    name: "My app"
  }],
};

Here we can use the "register" module to perform a conditional restart/start.

register the output of following command:

shell: pm2 list | grep <app_name> | awk '{print $2}'
register: APP_STATUS
become: yes

and the use APP_STATUS.stdout to make a conditional start and restart tasks. This way we don't need a pm2 delete step.

Related