如何将数组分配给Ansible-Playbook中的变量

dab*_*bai 23 ansible ansible-playbook

在剧本中我得到了以下代码:

---
- hosts: db
  vars:
    postgresql_ext_install_contrib: yes
    postgresql_pg_hba_passwd_hosts: ['10.129.181.241/32']
...
Run Code Online (Sandbox Code Playgroud)

我想postgresql_pg_hba_passwd_hosts我所有的webservers私有ips替换值.我知道我能得到这样的价值观这样一个模板:

{% for host in groups['web'] %}
   {{ hostvars[host]['ansible_eth1']['ipv4']['address'] }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

将此循环的结果分配给剧本中的变量的最简单/最简单的方法是什么?或者,有没有更好的方法来收集这些信息?我应该把这个循环放在模板中吗?

额外的挑战:我必须添加/32到每个条目.

Yui*_*iro 25

您可以通过set_factansible 过滤器插件将列表分配给变量.

将自定义过滤器插件放到filter_plugins目录中,如下所示:

(ansible top directory)
site.yml
hosts
filter_plugins/
    to_group_vars.py
Run Code Online (Sandbox Code Playgroud)

to_group_vars.py将hostvars转换为按组选择的列表.

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}
Run Code Online (Sandbox Code Playgroud)

使用这样:

---
- 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
Run Code Online (Sandbox Code Playgroud)


ann*_*neb 9

在剧本中:

vars:
     - arrayname:
        - name: itemname
          value1: itemvalue1
          value2: itemvalue2
        - name: otheritem
          value1: itemvalue3
          value2: itemvalue4
Run Code Online (Sandbox Code Playgroud)

在模板中:(示例是ini文件类型,包含节,键和值):

{% for item in arrayname %}
[{{ item.name }}]
key1 = {{ item.value1 }}
key2 = {{ item.value2 }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

这应该将模板呈现为:

[itemname]
key1 = itemvalue1
key2 = itemvalue2
[otheritem]
key1 = itemvalue3
key2 = itemvalue4
Run Code Online (Sandbox Code Playgroud)


tim*_*ima 6

变量可以表示为标准YAML结构,因此您可以为这样的键分配一个列表值:

---
- hosts: db
  vars:
    postgresql_ext_install_contrib: yes
    postgresql_pg_hba_passwd_hosts:
      - '10.129.181.241/32'
      - '1.2.3.0/8'
Run Code Online (Sandbox Code Playgroud)