将对象的Ansible列表简化为连接对象值的单个字符串

时间:2019-04-22 10:13:52

标签: ansible

我正在尝试解析elasticache_facts ansible模块的输出,以格式为“ addr1:port1 addr2:port2 ...”的字符串的形式提取IPS和内存缓存节点的端口。将此字符串存储在要在应用程序中使用的configmap中。

基本上,我想从这样的字典列表中获取两个字段“地址”和“端口”:

list1:
- endpoint: 
    address: "addr1"
    port: "port1"
- endpoint: 
    address: "addr2"
    port: "port2"

并像上面那样将它们连接起来。

我有一个丑陋的解决方案,像这样:

# register the output of the facts to something I know
elasticache_facts:
  region: "{{ terraform.region }}"
  name: "{{ cluster }}-{{ env }}"
register: elasticache

#declare an empty var in vars file to be used as accumulator
memcache_hosts: ""

# iterate through the list of nodes and append the fields to my string; I will have some extra spaces(separators) but that's ok
set_fact:
  memcache_hosts: "{{ memcache_hosts }} {{item.endpoint.address}}:{{item.endpoint.port}}"
with_items: "{{ elasticache.elasticache_clusters[0].cache_nodes}}"

是否有一些不太丑陋的方法将列表过滤为所需格式?

也许有一个我不知道的魔术过滤器?

我还可以获得两个列表,一个带有主机,一个带有端口,将它们压缩,然后做一个字典,但是我只发现了一些难看的to_json然后是正则表达式使其成为字符串。 我也在考虑在python中编写自定义过滤器,但似乎也做得过分。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

有两种方法可以实现您要寻找的东西:

#!/usr/bin/env ansible-playbook
---
- name: Lets munge some data
  hosts: localhost
  become: false
  gather_facts: false
  vars:
    my_list:
    - address: '10.0.0.0'
      port: '80' 
    - address: '10.0.0.1'
      port: '88' 
  tasks:
  - name: Quicky and dirty inline jinja2
    debug: 
      msg: "{% for item in my_list %}{{ item.address }}:{{ item.port }}{% if not loop.last %} {% endif %}{% endfor %}"

  # Note the to_json | from_json workaround for https://github.com/ansible/ansible/issues/27299
  - name: Using JSON Query
    vars:
      jmes_path: "join(':', [address, port])"
    debug: 
      msg: "{{ my_list | to_json | from_json | map('json_query', jmes_path) | join(' ') }}"

以上输出:

PLAY [Lets munge some data] **********************************************************************************************************************************

TASK [Quicky and dirty inline jinja2] ************************************************************************************************************************
ok: [localhost] => {
    "msg": "10.0.0.0:80 10.0.0.1:88"
}

TASK [Using JSON Query] **************************************************************************************************************************************
ok: [localhost] => {
    "msg": "10.0.0.0:80 10.0.0.1:88"
}

PLAY RECAP ***************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0