英文:
How to combine multiple Ansible filters?
问题
- name: set_fact
set_fact:
filename: "{{ file1 | json_query('files[*].path') | basename }}"
英文:
How do I combine the Ansible filters, json_query
and basename
so that I can do it in one task instead of using two tasks as shown here?
- name: set_fact
set_fact:
filename: "{{ file1 | json_query('files[*].path') }}"
- name: set_fact
set_fact:
filename: "{{ filename | basename }}"
I tried these ways, but both resulted in the same type of error:
- name: set_fact
set_fact:
filename: "{{ file1 | json_query('files[*].path') | basename }}"
"msg": "Unexpected templating type error occurred on ({{ file1 | json_query('files[*].path') | basename }}): expected str, bytes or os.PathLike object, not list"
- name: set_fact
set_fact:
filename: "{{ (file1 | json_query('files[*].path')) | basename }}"
"msg": "Unexpected templating type error occurred on ({{ (file1 | json_query('files[*].path')) | basename }}): expected str, bytes or os.PathLike object, not list"
}
答案1
得分: 3
给定用于测试的变量 *file1*
```yaml
file1:
files:
- path: /tmp/example/test_1.conf
- path: /tmp/example/test_2.conf
- path: /tmp/example/test_3.conf
您的查询
filename: "{{ file1|json_query('files[].path') }}"
给出了路径列表
filename:
- /tmp/example/test_1.conf
- /tmp/example/test_2.conf
- /tmp/example/test_3.conf
如果您只想要文件的名称,请在管道中使用 basename 过滤器 map
result: "{{ file1|json_query('files[].path')|map('basename') }}"
这将得到您想要的结果
result:
- test_1.conf
- test_2.conf
- test_3.conf
<hr>
<sup>
测试的完整playbook示例
- hosts: localhost
vars:
file1:
files:
- path: /tmp/example/test_1.conf
- path: /tmp/example/test_2.conf
- path: /tmp/example/test_3.conf
filename: "{{ file1|json_query('files[].path') }}"
result: "{{ file1|json_query('files[].path')|map('basename') }}"
tasks:
- debug:
var: filename
- debug:
var: result
</sup>
<details>
<summary>英文:</summary>
Given the variable *file1* for testing
```yaml
file1:
files:
- path: /tmp/example/test_1.conf
- path: /tmp/example/test_2.conf
- path: /tmp/example/test_3.conf
your query
filename: "{{ file1|json_query('files[].path') }}"
gives the list of the paths
filename:
- /tmp/example/test_1.conf
- /tmp/example/test_2.conf
- /tmp/example/test_3.conf
If you want the files' names only map the filter basename in the pipe
result: "{{ file1|json_query('files[].path')|map('basename') }}"
gives what you want
result:
- test_1.conf
- test_2.conf
- test_3.conf
<hr>
<sup>
Example of a complete playbook for testing
- hosts: localhost
vars:
file1:
files:
- path: /tmp/example/test_1.conf
- path: /tmp/example/test_2.conf
- path: /tmp/example/test_3.conf
filename: "{{ file1|json_query('files[].path') }}"
result: "{{ file1|json_query('files[].path')|map('basename') }}"
tasks:
- debug:
var: filename
- debug:
var: result
</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论