首页 > 解决方案 > Ansible:如何从列表中连接字典的属性?

问题描述

假设我有这个列表:

hosts:
  - {"ip": "1.2.3.4", "hostname": "www.example.com"}
  - {"ip": "42.42.42.42", "hostname": "www.wikipedia.com"}

我想获得这样的字符串(将其放入模板中):

'1.2.3.4,42.42.42.42'

它类似于我用 获得的hosts|join(','),但我只想连接 的值ip,所以可能我应该首先获得一个 IP 列表......但是如何?

标签: ansiblejinja2ansible-template

解决方案


你可以通过hoststomap(attribute='ip')过滤器。

这里有一个 PB 来试试:

---
- hosts: localhost
  gather_facts: false
  vars:
    hosts:
      - {"ip": "1.2.3.4", "hostname": "www.example.com"}
      - {"ip": "42.42.42.42", "hostname": "www.wikipedia.com"}
  tasks:
  - debug:
      var: hosts | map(attribute='ip') | list | join(',')

干杯


推荐阅读