Vagrant Ansible节点IP作为一个字符串

Vagrant Ansible节点IP作为一个字符串,vagrant,ansible,Vagrant,Ansible,我用流浪汉和Ansible。在我的剧本中,我有以下变量: seeds: '192.168.56.11,192.168.56.12' 192.168.56.11和192.168.56.12这里是多机漫游配置的IP地址 我可以使用Ansible更灵活地进行配置吗?即Ansible可以为我以编程方式编写此字符串吗?您可以使用Jinja2从其他变量中模板化出您的变量 因此,如果我们有这样一个列表: seeds: - 192.168.56.11 - 192.168.56.12 seeds_stri

我用流浪汉和Ansible。在我的剧本中,我有以下变量:

seeds: '192.168.56.11,192.168.56.12'
192.168.56.11
192.168.56.12
这里是多机漫游配置的IP地址


我可以使用Ansible更灵活地进行配置吗?即Ansible可以为我以编程方式编写此字符串吗?

您可以使用Jinja2从其他变量中模板化出您的变量

因此,如果我们有这样一个列表:

seeds:
 - 192.168.56.11
 - 192.168.56.12
seeds_string: '{% for seed in seeds %} {{ seed }}{% if not loop.last %},{% endif %}{% endfor %}'
seeds: '{% for host in groups['all'] %} {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}{% if not loop.last %},{% endif %}{% endfor %}'
我们可以通过如下方式将其转换为逗号分隔的字符串:

seeds:
 - 192.168.56.11
 - 192.168.56.12
seeds_string: '{% for seed in seeds %} {{ seed }}{% if not loop.last %},{% endif %}{% endfor %}'
seeds: '{% for host in groups['all'] %} {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}{% if not loop.last %},{% endif %}{% endfor %}'
至于获取清单中主机的IP地址,我们可以访问有关其他主机的事实,而不是使用配置的主机

因此,要获取清单中所有主机的IP地址,我们可以使用以下方法:

{% for host in groups['all'] %}
   {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
将这些结合起来,我们就可以做这样的事情:

seeds:
 - 192.168.56.11
 - 192.168.56.12
seeds_string: '{% for seed in seeds %} {{ seed }}{% if not loop.last %},{% endif %}{% endfor %}'
seeds: '{% for host in groups['all'] %} {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}{% if not loop.last %},{% endif %}{% endfor %}'

非常感谢,这正是我想要的。刚在我的项目中检查过,效果很好。