根据您在your answer here 中的建议,我确实设法通过自定义Action Plugin 读取了host_vars 和本地播放变量。
我发布这个答案是为了完整起见,并给出一个明确的例子来说明如何使用这种方法,尽管你最初给出了这个想法:)
注意 - 就功能齐全的插件而言,此示例是不完整的。它只是展示了如何访问变量。
from ansible.template import is_template
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
# some boilerplate ...
# init
result = super(ActionModule, self).run(tmp, task_vars)
# more boilerplate ...
# check the arguments passed to the task, where if missing, return None
self._task.args.get('<TASK ARGUMENT NAME>', None)
# or
# check if the play has vars defined
task_vars['vars']['<ARGUMENT NAME>']
# or
# check if the host vars has something defined
task_vars['hostvars']['<HOST NAME FORM HOSTVARS>']['<ARGUMENT NAME>']
# again boilerplate...
# build arguments to pass to the module
some_module_args = dict(
arg1=arg1,
arg2=arg2
)
# call the module with the above arguments...
如果您的剧本变量带有 jinja 2 模板,您可以在插件中解析这些模板,如下所示:
from ansible.template import is_template
# check if the variable is a template through 'is_template'
if is_template(var, self._templar.environment):
# access the internal `_templar` object to resolve the template
resolved_arg = self._templar.template(var_arg)
一些注意事项:
# things ...
#
vars:
- pkcs12_path: '{{ pkcs12_full_path }}'
- pkcs12_pass: '{{ pkcs12_password }}'
变量pkcs12_path不得与 host_vars 名称匹配。
例如,如果您有pkcs12_path: '{{ pkcs12_path }}',那么使用上述代码解析模板将导致递归异常...这对某些人来说可能很明显,但对我来说,host_vars 变量和 playbook 变量令人惊讶必须不同名。
-
- 您也可以通过
task_vars['<ARG_NAME>'] 访问变量,但我不确定它是从哪里读取的。此外,它也没有从 task_vars['vars']['<ARG_NAME>'] 或主机变量中获取变量那么明确。
PS - 在撰写本文时,该示例遵循 Ansible 认为的动作插件的基本结构。将来,run 方法可能会更改其签名...