首页 > 解决方案 > 使用 ad-hoc 命令的 Ansible 过滤器

问题描述

如何使用 ad-hoc 命令过滤nocache块或块?free我试过ansible centos1 -m setup -a 'filter=ansible_memory_mb.nocache'了,但没有过滤掉。

ansible centos1 -m setup -a 'filter=ansible_memory_mb'
centos1 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 11808,
                "used": 926
            },
            "real": {
                "free": 10686,
                "total": 12734,
                "used": 2048
            },
            "swap": {
                "cached": 0,
                "free": 4096,
                "total": 4096,
                "used": 0
            }
        },
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

标签: ansible

解决方案


几个月前有同样的问题,但答案是如果你需要访问特定的内部块,你需要使用 Ansible Playbook,不幸的是你不能使用临时命令来做到这一点。例如在您的本地主机的日期时间:

ansible -m setup localhost -a 'filter=ansible_date_time'

会返回很多具体的信息,比如秒、年、分等等。如果您只想返回像“2021-10-16”这样的格式日期,则需要使用剧本。这里有一些特定的剧本来创建具有特定日期格式的文件夹:

  tasks:
    - name: Collect Year, Month and Day.
      setup:
        filter: "ansible_date_time"
        gather_subset: "!all"
    
    - name: Put today's date in a variable.
      set_fact:
        DTG: "{{ ansible_date_time.date }}"

    - name: Create directory with the following path C:\bkp_"year-month-day"\Switches\
      file:
        path: /mnt/c/bkp_{{ hostvars.localhost.DTG }}/Switches/
        state: directory

推荐阅读