I hope this is somewhat right; the documentation is not optimal. I've finally managed to have a vars plugin load only once (i.e. I understand the count of "JPJPJP" lines).
[defaults]
inventory = inventory
vars_plugins = vars/
# the following finally works for me: it loads the plugin which runs once
# per group / host. As I have one host only and there are two predefined groups
# the result is three runs:
# JPJPJP, /Users/jpm/take/training/ansible-tests/tobias [all] None my_group
# JPJPJP, /Users/jpm/take/training/ansible-tests/tobias [ungrouped] None my_group
# JPJPJP, /Users/jpm/take/training/ansible-tests/tobias [localhost] None my_host
# (If I add a group with one host, the plugin is invoked 5x)
run_vars_plugins = start
# In addition to `start' above, this option (configured as an option in the plugin)
# disables the plugin if I set it to anything other than 'inventory'. ?!
[vars_custom_hostvars]
jp_vars_stage = inventory
localhost ansible_connection=local
- hosts: localhost
gather_facts: no
tasks:
- debug: var=newpassword
from ansible.inventory.host import Host
from ansible.inventory.host import Group
from ansible.plugins.vars import BaseVarsPlugin
DOCUMENTATION = '''
name: jp
author: JP Mens
short_description: Vars demo plugin
version_added: '0.0.0'
description:
- Don't load any files
options:
stage:
ini:
- key: jp_vars_stage
section: vars_custom_hostvars
env:
- name: ANSIBLE_JP_VARS_PLUGIN_STAGE
'''
class VarsModule(BaseVarsPlugin):
def get_vars(self, loader, path, entities, cache=None):
if not isinstance(entities, list):
entities = [entities]
super(VarsModule, self).get_vars(loader, path, entities)
data = {}
for entity in entities:
if isinstance(entity, Host):
subdir = "my_host"
elif isinstance(entity, Group):
subdir = "my_group"
print("JPJPJP, ", path, entities, cache, subdir)
data["newpassword"] = "ginton1cwithlemon"
return data
$ ansible-playbook jpvars.yml
JPJPJP, /Users/jpm/take/training/ansible-tests/tobias [all] None my_group
JPJPJP, /Users/jpm/take/training/ansible-tests/tobias [ungrouped] None my_group
JPJPJP, /Users/jpm/take/training/ansible-tests/tobias [localhost] None my_host
PLAY [localhost] ***************************************************************
TASK [debug] *******************************************************************
ok: [localhost] => {
"newpassword": "ginton1cwithlemon"
}
PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0