我正在尝试解析elasticache_factsansible 模块的输出,以“addr1: port1 addr2:port2 ...”形式的字符串提取 IPS 和 memcached 节点的端口(我想将此字符串存储在 configmap 中在应用程序中使用)。
基本上我想从这样的字典列表中获取两个字段“地址”和“端口”:
list1:
- endpoint:
address: "addr1"
port: "port1"
- endpoint:
address: "addr2"
port: "port2"
Run Code Online (Sandbox Code Playgroud)
并像上面一样连接它们。
我有一个丑陋的解决方案,如下所示:
# 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}}"
Run Code Online (Sandbox Code Playgroud)
有没有一些不太丑陋的方法来将列表过滤为所需的格式?
也许有一个我不知道的魔法过滤器?
我还可以获得两个列表,一个包含主机,一个包含端口,将它们压缩,从中创建一个字典,但我只发现一些丑陋的 to_json ,然后使用正则表达式将其变成字符串。我也在考虑用 python 编写一个自定义过滤器,但似乎也做得太过分了。
谢谢您的帮助!
以下有两种方法可以实现您的需求:
#!/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(' ') }}"
Run Code Online (Sandbox Code Playgroud)
以上输出:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5360 次 |
| 最近记录: |