我发现通过通配符选择变量的唯一方法是循环所有变量并测试match。例如
tasks:
- debug:
var: item
loop: "{{ query('dict', hostvars[inventory_hostname]) }}"
when: item.key is match("^.*_python_.*$")
Run Code Online (Sandbox Code Playgroud)
shell> ansible-playbook test.yml | grep key:
key: ansible_python_interpreter
key: ansible_python_version
key: ansible_selinux_python_present
Run Code Online (Sandbox Code Playgroud)
无论json_query([?键== '名']) ,也没有查找( '乏', '名')使用通配符的工作。
注意:regex_search在 regex_search() 中与变量匹配的语法是什么?
- debug:
msg: "{{ lookup('vars', item) }}"
loop: "{{ hostvars[inventory_hostname].keys() | select('match', '^.*_python_.*$') | list }}"
Run Code Online (Sandbox Code Playgroud)
给出:
ok: [localhost] => (item=ansible_selinux_python_present) => {
"msg": false
}
ok: [localhost] => (item=ansible_python_version) => {
"msg": "2.7.10"
}
Run Code Online (Sandbox Code Playgroud)
Ansible 2.8 及更高版本的更新。
Ansible 2.8 中添加了查找插件varnames 。到"List of Python regex patterns to search for in variable names"。查看具体信息
shell> ansible-doc -t lookup varnames
Run Code Online (Sandbox Code Playgroud)
例如,要列出.*_python_.*以下任务的变量
- debug:
msg: "{{ item }}: {{ lookup('vars', item) }}"
loop: "{{ query('varnames', '^.*_python_.*$') }}"
Run Code Online (Sandbox Code Playgroud)
给出
TASK [debug] ***************************************************************
ok: [localhost] => (item=ansible_python_interpreter) =>
msg: 'ansible_python_interpreter: /usr/bin/python3'
ok: [localhost] => (item=ansible_python_version) =>
msg: 'ansible_python_version: 3.8.5'
ok: [localhost] => (item=ansible_selinux_python_present) =>
msg: 'ansible_selinux_python_present: True
Run Code Online (Sandbox Code Playgroud)
此外,查找插件varnames还将查找尚未“实例化”的变量,因此未包含在hostvars中。
| 归档时间: |
|
| 查看次数: |
4206 次 |
| 最近记录: |