如何从Ansible插件获取所有vars_prompt?

时间:2019-09-26 21:46:57

标签: ansible ansible-2.x

我想将所有答案保存到文件中,以使我可以使用-e @answer.yml来避免再次回答相同的问题。为此,我正在编写一个插件,问题是我找不到从python获取vars_prompted的方法。我将它与另一个变量混合在一起,但是不知道如何区分另一个变量

我可以为所有提示变量添加一个通用前缀,但是我一直在寻找self._variable_manager.vars_prompt之类的东西,但是它不存在。

variable_manager.extra_vars,但这仅适用于在命令行上传递的变量。

我到目前为止有这个

"""
This plugin will dump all relevant variables to a file so that is
possible to run the playbook with the same variables again with
-e @answer-2019121212 switch

EXAMPLE PLAYBOOK:

---
- hosts: all
  pre_tasks:
    - dump_vars:

"""
from __future__ import absolute_import, division, print_function

__metaclass__ = type

from ansible.errors import AnsibleUndefinedVariable
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_text
from ansible.plugins.action import ActionBase
from ansible.vars.manager import VariableManager
from ansible.parsing.dataloader import DataLoader
from ansible.utils.display import Display

import re
import yaml
from datetime import datetime

display = Display()


class ActionModule(ActionBase):
    def run(self, tmp=None, task_vars=None):
        result = super(ActionModule, self).run(tmp, task_vars)
        # This includes the vars_prompt but I have no method for distinguishing
        # from another variables
        vars_ = {
            str(k): str(v)
            for k, v in task_vars.items()
            if k not in ("hostvars", "vars")
            and not k.startswith("ansible_")
            and not re.search("password", k)
        }
        filename = "answers-{}.yml".format(datetime.now().strftime("%Y%m%d%H"))
        with open(filename, "w") as f:
            yaml.dump(vars_, f)
        display.display("[INFO] {} file written".format(filename))
        return {"failed": False}


我正在使用这本剧本:

- hosts: localhost
  pre_tasks:
    - dump_vars:

像这样ansible-playbook -i localhost foo.yml

0 个答案:

没有答案