在下中,我使用来自testinfra.modules.ansible.Ansible的get_variables()方法,但似乎testinfra无法计算我的Ansible变量。
让我们来描述一下我的战俘。
~/tmp/ansible-testinfra
├── inventories
│ ├── group_vars
│ │ └── all.yml
│ └── inventory.ini
└── test_simple.py我定义了两个变量:
# inventories/group_vars/all.yml
---
one: "value one"
two: "{{ one }} and value two"我的inventory.ini是一个简单的本地主机:
# inventories/inventory
[all]
localhost我创建了这样一个非常简单的测试:
# test_simple.py
import pprint
def test_print_variables(host):
pprint.pprint(host.ansible.get_variables())
def test_variables(host):
my_vars = host.ansible.get_variables()
assert my_vars['two'] == 'value one and value two'当我运行pytest时,这里是我的sdtout:
~/tmp/ansible-testinfra$ pytest --hosts "ansible://all?ansible_inventory=inventories/inventory.ini" -s --tb=no
============================================================================ test session starts ============================================================================
platform linux -- Python 3.6.9, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: /home/olhoa/tmp/ansible-testinfra
plugins: testinfra-6.1.0
collected 2 items
test_simple.py {'group_names': ['ungrouped'],
'groups': {'all': ['localhost'], 'ungrouped': ['localhost']},
'inventory_hostname': 'localhost',
'one': 'value one',
'two': '{{ one }} and value two'}
.F
========================================================================== short test summary info ==========================================================================
FAILED test_simple.py::test_variables[ansible://localhost] - AssertionError: assert '{{ one }} and value two' == 'value one and value two'如您所见,变量one在变量two中使用时不会被解释。
那么,可以这样做吗?怎么做?
谢谢你的反馈!:)
发布于 2021-03-20 05:44:30
你在测试存货。结果是正确的
shell> ansible-inventory -i inventory.ini --graph --vars
@all:
|--@ungrouped:
| |--localhost
| | |--{one = value one}
| | |--{two = {{ one }} and value two}
|--{one = value one}
|--{two = {{ one }} and value two}引用术语表
惰性评估:一般来说,Ansible在最后一秒钟对剧本内容中的任何变量进行评估,这意味着如果您定义了数据结构,数据结构本身就可以在其中定义变量值,并且一切都如您所期望的“工作”。这也意味着变量字符串可以包括这些字符串中的其他变量。
要评估剧本内容中的变量,请编写一个。
shell> cat playbook
- hosts: localhost
tasks:
- debug:
var: one
- debug:
var: two给出
shell> ansible-playbook playbook.yml -i inventory.ini
...
TASK [debug] ************************************************************
ok: [localhost] =>
one: value one
TASK [debug] ************************************************************
ok: [localhost] =>
two: value one and value two作为附带说明,请参阅理解变量优先。在Ansible中,变量优先级是相当复杂的。
shell> ansible-playbook playbook.yml -i inventory.ini -e one=X
...
TASK [debug] ************************************************************
ok: [localhost] =>
one: X
TASK [debug] ************************************************************
ok: [localhost] =>
two: X and value twohttps://stackoverflow.com/questions/66715706
复制相似问题