You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ansible配置pm2-logrotate遇PM2内存版本过期及配置优化问询

问题1:执行pm2 update后仍然提示内存版本过时的修复

根本原因

PM2属于用户级守护进程,不同操作系统用户的PM2运行实例完全独立,互不影响。
你的配置全局开启了become: true,所有PM2相关命令都以root身份执行,pm2 update只会更新root用户的内存PM2进程。如果你后续登录后是切换到ubuntu等普通用户执行sudo pm2 ls,或者直接以普通用户身份操作PM2,访问的是对应用户的PM2实例,自然还会触发版本过时提示。
另外你当前复制pm2-logrotate配置的任务,把/home/ubuntu/.pm2/module_conf.json的属主设为了root,普通用户没有权限读取该配置,也会导致pm2-logrotate运行异常。

修复后的任务配置

---
# RUN playbook
# ansible-playbook -K pm2-setup.yml

- name: Setup pm2 and pm2-logrotate
  hosts: devdebugs
  remote_user: ansible
  # 取消全局become,仅在需要提权的任务单独开启
  # become: true

  tasks:
    - name: Install/Update pm2 globally
      community.general.npm: 
        name: pm2
        global: yes
        state: latest
      become: true # 全局安装npm包需要提权

    - name: Update In-memory pm2 for ubuntu user
      ansible.builtin.shell: pm2 update
      become: true
      become_user: ubuntu # 指定用ubuntu用户执行,更新对应实例

    # 新增检查pm2模块的任务,用于判断是否需要安装pm2-logrotate
    - name: Check if pm2-logrotate is installed
      ansible.builtin.shell: pm2 ls | grep -q pm2-logrotate
      register: pm2_logrotate_check
      become: true
      become_user: ubuntu
      ignore_errors: true
      changed_when: false # 该任务永远不会标记为系统状态变更

    - name: Install pm2-logrotate for ubuntu user
      ansible.builtin.shell: pm2 install pm2-logrotate
      become: true
      become_user: ubuntu
      # 只有检查命令返回值非0(未找到pm2-logrotate)时才执行安装
      when: pm2_logrotate_check.rc != 0

    - name: Copy pm2-logrotate config
      ansible.builtin.copy:
        src: /home/ubuntu/files/pm2-logrotate-conf.json
        dest: /home/ubuntu/.pm2/module_conf.json
        owner: ubuntu # 把属主改回ubuntu,确保有权限读取
        group: ubuntu
        mode: '0644'
...
问题2:pm2-logrotate安装幂等性实现

上述配置已经实现了自动跳过已安装场景的逻辑:

  • 先执行pm2 ls | grep -q pm2-logrotate检查现有模块,结果存入寄存器pm2_logrotate_check
  • 安装任务仅在检查返回值非0(即未找到模块)时执行,已经安装的场景下会自动标记为Skipped,不会重复执行安装命令。
    如果你不需要统一复制配置文件,也可以直接用pm2 set命令配置参数,避免文件权限问题:
- name: Configure pm2-logrotate parameters
  ansible.builtin.shell: |
    pm2 set pm2-logrotate:max_size 100M
    pm2 set pm2-logrotate:retain 30
    pm2 set pm2-logrotate:compress true
  become: true
  become_user: ubuntu
  changed_when: false

内容的提问来源于stack exchange,提问作者Bix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 06:27:02