Rahul Patil
Rahul Patil

Reputation: 1034

Wildcard in Ansible in template

Does anyone tried to use wildcard in template or in playbook?

The wildcard works in inventory and listing hosts but it's not working in template or in playbook.

Following command works:

ansible -i inventory/ec2.py tag_Name_Hbase*  --list-host`

but the same thing is not working in playbook.

Example (not working):

Node: `{{ {{ ":2181,".join(groups["tag_Name_Zookeeper*"]) }}:2181 }}`

Example (working):

Node: `{{ {{ ":2181,".join(groups["tag_Name_Zookeeper_Kafka01"]) }}:2181 }}`

Upvotes: 1

Views: 2417

Answers (1)

yaegashi
yaegashi

Reputation: 1520

Wildcards for dict key won't work. You need to iterate over 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

hosts:

[tag_Name_Zookeeper_1]
a
b
[tag_Name_Zookeeper_2]
c
d
[tag_Name_Zookeeper_3]
e
f
[others]
localhost

Sample session:

$ 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   

Upvotes: 2

Related Questions