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

如何用Ansible筛选匹配模式且已变更的PostgreSQL配置文件

解决方案

方法一:用Ansible原生模块组合筛选

通过find获取文件状态,结合内容检查来筛选同时满足「已变更」和「包含目标模式」的文件:

- name: 定位包含pg_show_plans且已变更的PostgreSQL配置文件
  hosts: your_postgres_hosts
  tasks:
    - name: 获取conf.d下所有conf文件及校验和
      ansible.builtin.find:
        path: /srv/postgresql/config/conf.d
        patterns: "*.conf"
        get_checksum: yes
      register: conf_files

    - name: 筛选符合条件的文件
      ansible.builtin.set_fact:
        target_files: "{{ target_files | default([]) + [item.path] }}"
      loop: "{{ conf_files.files }}"
      when:
        # 这里以校验和变化作为变更判断,可替换为修改时间/默认文件对比等逻辑
        - item.checksum != item.stat.checksum | default('')
        - lookup('file', item.path) is search('pg_show_plans')

    - name: 输出结果
      ansible.builtin.debug:
        msg: "匹配文件: {{ target_files }}"

方法二:用Shell命令直接批量处理

如果有明确的变更基准(比如和默认配置目录对比),可以用shell命令一次性完成筛选:

- name: 用Shell命令筛选目标文件
  hosts: your_postgres_hosts
  tasks:
    - name: 找出已变更且包含pg_show_plans的conf文件
      ansible.builtin.command: >
        cd /srv/postgresql/config/conf.d && 
        for file in *.conf; do
          # 替换成你的变更判断逻辑,这里是和默认配置目录的同名文件对比
          if ! cmp -s "$file" "../conf.default.d/$file"; then
            if grep -q 'pg_show_plans' "$file"; then
              echo "$file";
            fi
          fi
        done
      register: result

    - name: 输出结果
      ansible.builtin.debug:
        msg: "匹配文件: {{ result.stdout_lines }}"

关键注意点

  • 「已变更」的判断逻辑需要根据实际场景调整:可以是校验和变化、文件修改时间晚于某个节点、和默认配置文件存在差异等,上面的示例提供了两种常见思路。
  • 如果是要追踪Ansible执行过程中产生的变更,可以在配置文件部署模块(如template/copy)后注册变更结果,再结合内容检查筛选。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:05:21