首页 > 解决方案 > Ansible 变量通配符选择

问题描述

我发现通过通配符选择变量的唯一方法是循环所有变量并测试match。例如

  tasks:
    - debug:
        var: item
      loop: "{{ query('dict', hostvars[inventory_hostname]) }}"
      when: item.key is match("^.*_python_.*$")
shell> ansible-playbook test.yml | grep key:
    key: ansible_python_interpreter
    key: ansible_python_version
    key: ansible_selinux_python_present

json_query ([?key=='name'])lookup('vars', 'name')都不能使用通配符。

注意:regex_search在 regex_search() 中匹配变量的语法是什么?

标签: ansible

解决方案


您可以使用 Jinja 测试选择/拒绝:

- debug:
    msg: "{{ lookup('vars', item) }}"
  loop: "{{ hostvars[inventory_hostname].keys() | select('match', '^.*_python_.*$') | list }}"

给出:

ok: [localhost] => (item=ansible_selinux_python_present) => {
    "msg": false
}
ok: [localhost] => (item=ansible_python_version) => {
    "msg": "2.7.10"
}

推荐阅读