Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...