是否有人尝试在模板或剧本中使用通配符?
通配符在库存和列表主机中有效,但它不能在模板或playbook中使用。
以下命令有效:
ansible -i inventory/ec2.py tag_Name_Hbase* --list-host`
但同样的事情不适用于剧本。
示例(不工作):
Node: `{{ {{ ":2181,".join(groups["tag_Name_Zookeeper*"]) }}:2181 }}`
示例(工作):
Node: `{{ {{ ":2181,".join(groups["tag_Name_Zookeeper_Kafka01"]) }}:2181 }}`
答案 0 :(得分:2)
dict密钥的通配符不起作用。您需要迭代group.keys()
。
playbook.yml:
---
- hosts: all
gather_facts: no
vars:
Node: |
{% set o = [] %}
{%- for i in groups.keys() %}
{%- if i.startswith("tag_Name_Zookeeper") %}
{%- for j in groups[i] %}
{%- if o.append(j+":2181") %}
{%- endif %}
{%- endfor %}
{%- endif %}
{% endfor %}
{{ ",".join(o) }}
tasks:
- debug:
var: Node
run_once: yes
delegate_to: localhost
主机:
[tag_Name_Zookeeper_1]
a
b
[tag_Name_Zookeeper_2]
c
d
[tag_Name_Zookeeper_3]
e
f
[others]
localhost
示例会话:
$ ansible-playbook -i hosts playbook.yml
PLAY [all] ********************************************************************
TASK: [debug ] ****************************************************************
ok: [a -> localhost] => {
"var": {
"Node": "a:2181,b:2181,c:2181,d:2181,e:2181,f:2181"
}
}
PLAY RECAP ********************************************************************
a : ok=1 changed=0 unreachable=0 failed=0
b : ok=1 changed=0 unreachable=0 failed=0
c : ok=1 changed=0 unreachable=0 failed=0
d : ok=1 changed=0 unreachable=0 failed=0
e : ok=1 changed=0 unreachable=0 failed=0
f : ok=1 changed=0 unreachable=0 failed=0
localhost : ok=1 changed=0 unreachable=0 failed=0