Ansible: Access host/group vars from within custom module

Is there a way how one can access host/group vars from within a custom written module? I would like to avoid to pass all required vars as module parameters.

My module is written in Python and I use the boilerplate. I checked pretty much all available vars but they are not stored anywhere:

def main():
    pprint(dir())
    pprint(globals())
    pprint(locals())
    for name in vars().keys():
        print(name)

Now my only hope is they are somehow accessible through the undocumented module utils.

I guess it is not possible, since the module runs on the target machine and probably the facts/host/group vars are not transferred along with the module...

Edit: Found the module utils now and it doesn't look promising.


I think you pretty much hit the nail on the head with your thinking here:

I guess it is not possible, since the module runs on the target machine and probably the facts/host/group vars are not transferred along with the module...

However, having said that, if you really have a need for this then there might be a slightly messy way of doing it. As of Ansible 1.8 you can set up fact caching, which uses redis to cache facts between runs of plays. Since redis is pretty easy to use and has clients for most popular programming languages, you could have your module query the redis server for any facts you need. It's not exactly the cleanest way to do it, but it just might work.


Is there a way how one can access host/group vars from within a custom written module?

Not built-in.

You will have to pass them yourself one way or the other:

  • Module args.
  • Serialize to local file system (with pickle or yaml.dump() or json or ...) and send the file over.
  • any other innovative ideas you can come up with.
  • Unfortunately you can't just send over whole host/groupvar files as-it-is because you would have to implement the variable scope/precedence resolution algorithm of ansible which is undefined (it's not the Zen philosophy of ansible to define such petty things :P ).

    链接地址: http://www.djcxy.com/p/84096.html

    上一篇: 通过AES算法在python和android中加密和解密

    下一篇: Ansible:从自定义模块中访问主机/组变量