如何在Ansible-Playbook中将数组分配给变量 [英] How to assign an array to a variable in an Ansible-Playbook
问题描述
在剧本中,我得到了以下代码:
In a playbook I got the following code:
---
- hosts: db
vars:
postgresql_ext_install_contrib: yes
postgresql_pg_hba_passwd_hosts: ['10.129.181.241/32']
...
我想将postgresql_pg_hba_passwd_hosts
的值替换为我的所有网络服务器专用ips .我了解我可以获得类似
I would like to replace the value of postgresql_pg_hba_passwd_hosts
with all of my webservers private ips. I understand I can get the values like this in a template:
{% for host in groups['web'] %}
{{ hostvars[host]['ansible_eth1']['ipv4']['address'] }}
{% endfor %}
将此循环的结果分配给剧本中的变量的最简单/最简单的方法是什么?还是首先有更好的方法来收集此信息?我应该将此循环放在模板中吗?
What is the simplest/easiest way to assign the result of this loop to a variable in a playbook? Or is there a better way to collect this information in the first place? Should I put this loop in a template?
其他挑战:我必须在每个条目中添加/32
.
Additional challenge: I'd have to add /32
to every entry.
推荐答案
您可以通过为变量分配列表set_fact 和ansible 过滤器插件.
You can assign a list to variable by set_fact and ansible filter plugin.
将自定义过滤器插件放置到 filter_plugins 目录中,如下所示:
Put custom filter plugin to filter_plugins directory like this:
(ansible top directory)
site.yml
hosts
filter_plugins/
to_group_vars.py
to_group_vars.py 将hostvars转换为按组选择的列表.
to_group_vars.py convert hostvars into list that selected by group.
from ansible import errors, runner
import json
def to_group_vars(host_vars, groups, target = 'all'):
if type(host_vars) != runner.HostVars:
raise errors.AnsibleFilterError("|failed expects a HostVars")
if type(groups) != dict:
raise errors.AnsibleFilterError("|failed expects a Dictionary")
data = []
for host in groups[target]:
data.append(host_vars[host])
return data
class FilterModule (object):
def filters(self):
return {"to_group_vars": to_group_vars}
像这样使用:
---
- hosts: all
tasks:
- set_fact:
web_ips: "{{hostvars|to_group_vars(groups, 'web')|map(attribute='ansible_eth0.ipv4.address')|list }}"
- debug:
msg: "web ip is {{item}}/32"
with_items: web_ips
这篇关于如何在Ansible-Playbook中将数组分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!