简体   繁体   English

将 pm2 与 ansible 一起使用

[英]using pm2 with ansible

I am trying to start a node program using pm2 via ansible.我正在尝试通过 ansible 使用 pm2 启动节点程序。 The problem is that the pm2 start command is not idempotent under ansible.问题是在ansible下pm2 pm2 start命令不是幂等的。 It gives error when run again.再次运行时会报错。

This is my ansible play这是我的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.解决此错误并通过 ansible 正确处理 pm2 的正确方法是什么。

Before starting the script you should delete previous, like this:在启动脚本之前,您应该删除以前的脚本,如下所示:

 - name: delete existing pm2 processes if running
   command: "pm2 delete {{ server_id }}"
   ignore_errors: True
   become: yes
   become_user: rw_user


 - name: start pm2 process
   command: 'pm2 start -x -i 4 --name "{{server_id}}" server.js'
   become: yes
   become_user: rw_user
   environment:
    NODE_ENV: "{{server_env}}"

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.我最终在此页面上寻找一种解决方案,以便在我重新运行我的剧本时多次start PM2。 I also wanted PM2 to reload the server when it was already running and pickup the new code I might have deployed.我还希望 PM2 在服务器已经运行时重新加载服务器并获取我可能已经部署的新代码。 It turns out that PM2 has such an interface:原来pm2有这么一个接口:

- 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. startOrReload命令需要存在所谓的“生态系统”文件。 See the documentation for more details: Ecosystem File .有关详细信息,请参阅文档: 生态系统文件

This is a minimal pm2.ecosystem.config.js that is working for me:这是为我工作的最小pm2.ecosystem.config.js

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.并使用 APP_STATUS.stdout 进行有条件的启动和重新启动任务。 This way we don't need a pm2 delete step.这样我们就不需要 pm2 删除步骤了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM