I’m using ec2.py as my hostfile and I’m writing the following templating in
Jinja2.
{% for host in groups[“tag_provides_logstash-server”] %}
{{ hostvars[host][“ec2_ip_address”] }} {{ hostvars[host][“ec2_tag_Name”] }}
{% endfor %}
This isn’t valid in Jinja2, but is what I"m looking for:
groups[“tag_provides_logstash-server:&tag_env_dev”]
Other people have aimed for this behavior before:
https://groups.google.com/forum/#!topic/Ansible-project/QuqXUV_BEMM
Gustavo’s resolution isn’t as simple as I would like, though.
This is what I have settled on for now:
{% for host in groups[“tag_provides_logstash-server”] | intersect(groups[“tag_env_dev”]) %}
{{ hostvars[host][“ec2_ip_address”] }} {{ hostvars[host][“ec2_tag_Name”] }}
{% endfor %}
It looks good, but I would like to know if there’s anything grossly wrong or
devious with this approach.
In your template above I’d probably just assign a “my_hosts” variable to the expression to clean up the loop a bit.
{# set my_hosts = groups[“tag_provides_logstash-server”] | intersect(groups[“tag_env_dev”]) #}
{% for host in my_hosts %}
etc
The other thing you have is the “play_hosts” variable in Ansible which should return all the hosts in the current play.
So to your question, yes, there are easier ways now that can make things easier to follow.
Mark_Maas
(Mark Maas)
3
Gents,
Could you elaborate a bit on how to use this?
You see, i’m trying to do the same thing:
# Cluster connection URL
{# set mysql_hosts = groups["tag_type_mysql"] | intersect(groups["tag_environment_dev"]) #}
wsrep_cluster_address=gcomm://{% for host in mysql_hosts %}{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }},{% endfor %}
But the variable “mysql_hosts” does not seem to get populated:
fatal: [10.220.226.243] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'mysql_hosts' is undefined", 'failed': True
When I look at the two groups:
type mysql group
{{ groups.tag_type_mysql | to_nice_yaml }}
env dev group
{{ groups.tag_environment_dev | to_nice_yaml }}
They result in:
type mysql group
- 10.220.226.243
- 10.220.227.5
- 10.220.225.203
env dev group
- 10.220.2.242
- 10.220.3.129
- 10.220.227.77
- 10.220.222.24
- 10.220.221.8
- 10.220.226.9
- 10.220.226.243
- 10.220.226.70
- 10.220.227.5
- 10.220.225.203
- 10.220.227.20
- 10.220.1.169
- 10.220.225.84
- 10.220.220.247
- 10.220.225.126
so I know they exist and are filled…
Thanks for looking!
sivel
(sivel)
4
I think there was a typo, instead of using {# #} you should probably be using {% %}
The {# #} characters indicate a jinja2 comment.