How to filter gathering facts inside a playbook?

对着背影说爱祢 提交于 2019-11-28 21:31:54

Yes, that's possible, but not in the default behavior of gathering facts. Having set gather_facts to true simply calls the setup module as very first task of the play. This way you do not have any way to parameterize the setup module call.

But you can disable the default behavior and call setup yourself with the filter parameter.

- hosts: all
  sudo: yes
  gather_facts: False
  tasks:
   - setup:
       filter: ansible_*

Since you're working on a role and might not want to have this setup call in your role, you could make use of pre_tasks.

- hosts: all
  sudo: yes
  gather_facts: False
  pre_tasks:
   - setup:
       filter: ansible_*
  roles:
   - your_role_here

The Ansible way at the top of the playbook (Additional way):

----
- hosts: web
  gather_facts: True
  gather_subset:
    - network
    - virtual

Debug vars with:

  - name: Print some debug information 
    vars: 
      msg: |
          Module Variables ("vars"):
          --------------------------------
          {{ vars | to_nice_json }} 

          Environment Variables ("environment"):
          --------------------------------
          {{ environment | to_nice_json }} 

          GROUP NAMES Variables ("group_names"):
          --------------------------------
          {{ group_names | to_nice_json }}

          GROUPS Variables ("groups"):
          --------------------------------
          {{ groups | to_nice_json }}

          HOST Variables ("hostvars"):
          --------------------------------
          {{ hostvars | to_nice_json }} 

    debug: 
      msg: "{{ msg.split('\n') }}"       
    tags: debug_info

After this question was asked and answered, Ansible 2.1 added the gather_subset option to the setup module so its now possible to use the !facter,!ohai,network syntax described in the documentation rather than a regex filter:

- hosts: all
  sudo: yes
  gather_facts: False
  pre_tasks:
   - setup:
       gather_subset: !facter,!ohai,network
  roles:
   - your_role_here

If all you're interested in is the hostname of each host then simply doing something like this should do what you need:

- hosts: all
  gather_facts: false
  tasks:

    - name: Get hostname
      command: /bin/hostname
      register: my_hostname

    - debug: var=my_hostname

If it's some other fact that you're interested in then just specify the appropriate command, and refer to the fact via the registered variable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!