I would like to display the variables being used in my playbook. The variable hostvars[inventory_hostname] has all the information I want, but about 70% of the variables start with 'ansible_', which I would like to filter out.

I suspect I can use a filter such as

{{ hostvars[inventory_hostname] | rejectattr('ansible[*]', 'defined') }} 

but I'm not finding the correct format that gives me the output I want. Most of the filters operate on the attributes of a variable as opposed to the variable name itself. I suspect I can use | to_json but I'm still having difficulty manipulating the output.

  1. Is there an alternate variable group I can use other than hostvars that doesn't require filtering?
  2. If a filter is the way to go, any suggestions?

1 Answer

Is there an alternate variable group I can use other than hostvars that doesn't require filtering?

No. hostvars is a list of variables set for this host, which includes facts set via the setup task as well as those you set explicitly using set_fact, host_vars files, etc.

If a filter is the way to go, any suggestions?

You're on the right track! You can use the dict2items to transform the dictionary into something that is more amendable to filtering with rejectattr, like this:

- hosts: localhost gather_facts: true tasks: - debug: var: hostvars[inventory_hostname]|dict2items|rejectattr("key", "match", "ansible")|items2dict 

We're using the match test here, which matches regular expression anchored to the beginning of the string, so this will reject any keys that start with ansible.

Running that playbook on my system produces:

TASK [debug] ******************************************************************************************** ok: [localhost] => { "hostvars[inventory_hostname]|dict2items|rejectattr(\"key\", \"match\", \"ansible\")|items2dict": { "gather_subset": [ "all" ], "group_names": [], "groups": { "all": [], "ungrouped": [] }, "inventory_hostname": "localhost", "inventory_hostname_short": "localhost", "module_setup": true, "omit": "__omit_place_holder__ef809c7b9cdf63b1506089085eb169c56682b5e3", "playbook_dir": "/home/lars/tmp/ansible" } } 
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.