skip to Main Content

I have plenty of EC2 servers in AWS and want to categorize them based on facts gathered from ansible_facts (by module setup). For example to have a group “CentOS” where ansible_facts['distribution'] == 'CentOS' and so on. But having file inventory/constructed.yml:

plugin: constructed
strict: False
keyed_groups:
  # this creates a group per distro (distro_CentOS, distro_Debian) and assigns the hosts that have matching values to it,
  # using the default separator "_"
  - prefix: distro
    key: ansible_distribution

I don’t see a distro_CentOS group in the output of the command ansible-inventory --graph.

The plugin is enabled in ansible.cfg:

[inventory]
enable_plugins = host_list, ini, aws_ec2, constructed

How I can sort EC2 instances based on gathered ansible facts, avoiding the need to tag each instance?

2

Answers


  1. The constructed inventory plugin relies on already known facts. This means they either need to be variables in the inventory file, or cached facts.

    Try setting up a simple local jsonfile cache. Take a look at https://docs.ansible.com/ansible/latest/plugins/cache.html or just add something similar to this to your ansible.cfg file:

    [defaults]
    fact_caching = jsonfile
    gathering = smart
    fact_caching_timeout = 600
    fact_caching_connection = /home/<user>/facts_cache
    

    Next, run an ad-hoc command across all hosts to collect facts:

    ansible all -m setup
    

    Now try and list your inventory again. You should see the auto generated groups based on ansible_distribution

    Note that when the facts cache timeout is reached (10 minutes in my sample config file above), the facts variables cannot be used with the constructed plugin, so you will need to collect all facts again.

    Login or Signup to reply.
  2. The inventory plugin runs before the setup module runs and can’t rely on its output (the caching can change that)

    The group_by module seems to be designed exactly for this use case:

    - group_by:
        key: distro_{{ ansible_distribution }}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search