在任务中访问 ansible.cfg 变量

Iva*_*hko 5 ansible ansible-playbook ansible-2.x

我如何引用remote_tmp(或任何其他)ansible.cfg在我的任务中定义的值?例如,在my_task/defaults/main.yml

file_ver: "1.5"
deb_file: "{{ defaults.remote_tmp }}/deb_file_{{ file_ver }}.deb"
Run Code Online (Sandbox Code Playgroud)

产生一个错误:

fatal: [x.x.x.x]: FAILED! => {"failed": true, 
    "msg": "the field 'args' has an invalid value, 
            which appears to include a variable that is undefined. 
            The error was: {{ defaults.remote_tmp }}/deb_file_{{ file_ver }}.deb: 
           'defaults' is undefined\... }
Run Code Online (Sandbox Code Playgroud)

Kon*_*rov 4

你不能开箱即用地这样做。
您需要操作插件或变量插件来读取不同的配置参数。
如果您采用操作插件方式,则必须调用新创建的操作才能remote_tmp定义。
如果您选择变量插件方式,remote_tmp则在清单初始化期间与其他主机变量一起定义。

例子./vars_plugins/tmp_dir.py

from ansible import constants as C

class VarsModule(object):

    def __init__(self, inventory):
        pass

    def run(self, host, vault_password=None):
        return dict(remote_tmp = C.DEFAULT_REMOTE_TMP)
Run Code Online (Sandbox Code Playgroud)

请注意,该vars_plugins文件夹应该靠近您的hosts文件,或者您应该在 ansible.cfg 中明确定义它。

您现在可以使用以下命令进行测试:

$ ansible localhost -i hosts -m debug -a "var=remote_tmp"
localhost | SUCCESS => {
    "remote_tmp": "$HOME/.ansible/tmp"
}
Run Code Online (Sandbox Code Playgroud)