Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

ansible - How to filter gathering facts inside a playbook?

I'm working on a role that only needs to gather a single fact.

Performance it's a concern and I know that gathering facts it's time-consuming.

I'm looking for some way to filter gather_facts inside a playbook, this will allow me to gather only the required facts.

This is possible using the setup core module:

ansible -m setup -a 'filter=ansible_hostname' my_host

10.200.0.127 | success >> {
    "ansible_facts": {
        "ansible_hostname": "my_host"
    },
    "changed": false
}

It's possible to use this feature inside the playbook? Something like this?

- hosts: all
  sudo: yes
  gather_facts: True
    filter: "filter=ansible_*"

PS: The code above throws syntax exception.

EDIT 1: If someone needs to get hostname there's also another useful variable inventory_hostname.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...