0

I have worked with Ansible for a while now and am comfortable with it, but am only now beginning to explore writing custom modules and plugins. I have come up with some simple concepts for modules and plugins that I'd like to write as an exercise to develop my understanding.

One module I had in mind would be to set a fact for a group of hosts, essentially accomplishing what a group_vars file would, but dynamically in a task. I would like to set the fact across all hosts in the group and report back which hosts were affected (excluding hosts where the fact already existed with the specified value). This requires me to read and write facts on other hosts.

Currently, I can set a fact across a group with a loop, and it's possible this is already the best way to accomplish this:

- set_fact:
    foo: bar
  delegate_to: "{{ item }}"
  delegate_facts: true
  loop: "{{ groups['baz_group'] }}"

But if it is possible to read and/or write facts to other hosts (effectively handle multiple delegations) within a module/action-plugin, I want to understand how to do that.

Based on the debug action plugin, my understanding is that to read/interpret a fact from the target host, this code is used:

foo = self._templar.template('foo', convert_bare=True, fail_on_undefined=True )

And based on the set_fact action plugin, my understanding is that to write a fact to the target host, this code is used:

result['ansible_facts']['foo'] = foo
return result

But I haven't seen any indication of how to access facts on other hosts. If this simply isn't possible by design, then that's the answer I'm looking for.


Also, if anyone knows of a good resource for writing Ansible plugins and/or modules, I'd love to see it. The Ansible documentation is pretty sparse and simply directs me to look through the examples in core (which I did), but it can be difficult to parse without a greater understanding of Ansible as a whole. That said, I'm also not much of a Python dev, so maybe that's most of my problem...

Thanks in advances for any responses!


Update 2022/11/26

At least some of the special keys for the returned dictionary are enumerated in the strategy plugin's __init__.py. They include add_host and add_group. Based on the add_host module behavior, I should be able to add variables to an existing host this way, but only affecting one host at a time. I am still unsure how to access facts on a different host or if that's possible at all.

oO.o
  • 87
  • 1
  • 1
  • 6

0 Answers0