Accessing variables programatically

Hello,

I'm developing both an Ansible module and a dynamic inventory script, in Python.

In each case, I need to lookup/obtain the value of a host/group variable.

I've looked through the documentation, and tried a bunch of online searches, but haven't really found anything very illuminating.

Any advice/pointers would be greatly appreciated.

Don

In general neither dynamic inventory scripts nor modules have access to host/group vars.

host/group vars are part of inventory, so for me it feels weird that an inventory script would need access to them, as opposed to providing them.

As far as modules, you should require that the var be passed to the module. The only way to get this by default is to also write an action plugin that could pass the var to the module for you.

In general neither dynamic inventory scripts nor modules have access to host/group vars.

host/group vars are part of inventory, so for me it feels weird that an inventory script would need access to them, as opposed to providing them.

I can see why this might seem weird.

But what if a dynamic inventory script could benefit from a variable defined elsewhere, for example, in a static inventory file?
Sure I could define yet another config file, or use environment variables, but that is just spreading my configuration around in more places.

To give a highly contrived example, what if I was writing a dynamic inventory that was going to dispatch to various cloud-based dynamic inventory scripts,
where the list of cloud providers I currently use is defined in a high level text inventory file
My contrived dispatching cloud inventory script would obtain that list,
and then call each specific cloud inventory script. Again, this is just an example and not really what I am doing,

So there is no way for an inventory script to ask ansible for the value of a variable?
I guess I could shell out to ansible, and give it ad-hoc args to lookup and return the variable, and parse the result. Yuck!

As far as modules, you should require that the var be passed to the module. The only way to get this by default is to also write an action plugin that could pass the var to the module for you.

This is helpful, thanks!

I just found this: Ansible: Modules and Action Plugins, which uses

        template_string = '' % fact_name
        res = template.template(self.basedir, template_string, inject)
        return None if res == template_string else res

to look up the value of a variable. Is this the best way?

It seems to me that there is plenty of configured state that some combination of Ansible itself and modules leverage, things like ansible_python_interpreter, etc.

Think outside the box, ansible is not intended to manipulate data it
is designed to take the data and build a configuration with it, trying
to do other thing will only mess your configuration. Look where you
gather the data outside ansible and access it there.