如何将数组分配给 Ansible-Playbook 中的变量 [英] How to assign an array to a variable in an Ansible-Playbook

查看:33
本文介绍了如何将数组分配给 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']
...

我想用我所有的网络服务器私有 ips 替换 postgresql_pg_hba_passwd_hosts 的值.我知道我可以获得像 this模板中:

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 将主机变量转换为按组选择的列表.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆