gpt4 book ai didi

ansible - 如何在 vars 中使用注册的 ansible 变量的字典?

转载 作者:行者123 更新时间:2023-12-02 22:25:15 29 4
gpt4 key购买 nike

我想使用 vars 将多个变量传递给任务。目前,我正在这样做

vars:
var1_name: "var1_value"
var2_name: "var2_value"

随着变量数量的增加,我宁愿使用 vars 将变量字典传递给任务。我构建了一个变量字典,如下所示

- name: set fact
hosts: localhost
tasks:
- set_fact:
variables: "{{ variables|default({}) | combine( {item.variable: item.value} ) }}"
with_items:
- variable: var1_name
value: "var1_value"
- variable: var2_name
value: "var2_name"

字典看起来像这样:

"variables": {
"var1_name": "var1_value",
"var2_name": "var2_value",
}

现在,我想让该字典中的变量可供在其他主机上执行的角色使用。

但是,当我尝试将字典传递给 vars 时,如下所示

vars: "{{ variables }}"

Ansible 抛出错误:

ERROR! Vars in a Play must be specified as a dictionary, or a list of dictionaries

如何在vars中传递字典变量?

最佳答案

在对 Ansible 源代码进行一些搜索后,看起来这甚至是 Ansible 开发人员也面临的问题。在某些集成测试中,有一些特定的测试由于同样的错误而被注释掉。

https://github.com/ansible/ansible/blob/devel/test/integration/targets/include_import/role/test_include_role.yml#L96

## FIXME Currently failing with
## ERROR! Vars in a IncludeRole must be specified as a dictionary, or a list of dictionaries
# - name: Pass all variables in a variable to role
# include_role:
# name: role1
# tasks_from: vartest.yml
# vars: "{{ role_vars }}"

我还发现这是被调用以包含变量的底层函数:

https://github.com/ansible/ansible/blob/devel/lib/ansible/playbook/base.py#L681

    def _load_vars(self, attr, ds):
'''
Vars in a play can be specified either as a dictionary directly, or
as a list of dictionaries. If the later, this method will turn the
list into a single dictionary.
'''

def _validate_variable_keys(ds):
for key in ds:
if not isidentifier(key):
raise TypeError("'%s' is not a valid variable name" % key)

try:
if isinstance(ds, dict):
_validate_variable_keys(ds)
return combine_vars(self.vars, ds)
elif isinstance(ds, list):
all_vars = self.vars
for item in ds:
if not isinstance(item, dict):
raise ValueError
_validate_variable_keys(item)
all_vars = combine_vars(all_vars, item)
return all_vars
elif ds is None:
return {}
else:
raise ValueError
except ValueError as e:
raise AnsibleParserError("Vars in a %s must be specified as a dictionary, or a list of dictionaries" % self.__class__.__name__,
obj=ds, orig_exc=e)
except TypeError as e:
raise AnsibleParserError("Invalid variable name in vars specified for %s: %s" % (self.__class__.__name__, e), obj=ds, orig_exc=e)

似乎由于“{{ }}”实际上只是一个 YAML 字符串,Ansible 不会将其识别为字典,这意味着 vars 属性没有通过 Jinja2 引擎传递,而是被评估为什么确实如此。

传递 YAML 对象的唯一方法是使用 anchor ,但这需要整个对象定义而不是动态定义。

    var: &_anchored_var 
attr1: "test"
att2: "bar"

vars:
<<: *_anchored_var

关于ansible - 如何在 vars 中使用注册的 ansible 变量的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477012/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com