假设我具有以下输入结构
domain: topdomain.com
subdomains:
- name: foo
- name: bar
并希望获得此输出
domains:
- name: foo.topdomain.com
- name: bar.topdomain.com
例如可以在Python中实现的内容
domain = 'topdomain.com'
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
subdomains = [
{
'name': 'foo'
},
{
'name': 'bar'
}
]
domains = list(map(lambda sd: {'name': sd['name'] + '.' + domain}, subdomains))
print(domains)
如何在Ansible中使用过滤器完成此操作?理想情况下实现任何自定义或特殊功能?
注意:我不是在寻找如何将对象列表映射到字符串列表,就像使用map(attribute='name') | map('regex_replace', ...'
答案 0 :(得分:0)
尽管需要对work around a still unfixed feature request in jmespath进行小的修改(例如,下面的to_json | from_json
),但以下剧本可以满足您的要求。请注意,由于使用了json_query
filter
pip install jmespath
---
- hosts: localhost
gather_facts: false
vars:
domain: topdomain.com
subdomains:
- name: foo
- name: bar
domains_query: "[].{name: join('', [name,'.{{ domain }}'])}"
domains: "{{ subdomains | to_json | from_json | json_query(domains_query) }}"
tasks:
- name: Show the result
debug:
var: domains
结果:
$ ansible-playbook play.yml
PLAY [localhost] **************************************************************************************************************************************************************************************************
TASK [Show the result] ********************************************************************************************************************************************************************************************
ok: [localhost] => {
"domains": [
{
"name": "foo.topdomain.com"
},
{
"name": "bar.topdomain.com"
}
]
}
PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0