Ansible - Get file or directory name using the basename filter

by
Jeremy Canfield |
Updated: March 02 2022
| Ansible articles
There are two similar filters, basename and dirname.
For example, with "/tmp/foo.txt", the dirname will be "/tmp" and the basename will be "foo.txt".
---
- hosts: localhost
tasks:
- name: print dirname
debug:
msg: "{{ '/tmp/foo.txt' | dirname }}"
- name: print basename
debug:
msg: "{{ '/tmp/foo.txt' | basename }}"
...
This can also be used with map.
---
- hosts: localhost
tasks:
- name: set_fact dirname
set_fact:
dirname: "{{ '/tmp/foo.txt' | map('dirname') }}"
- name: set_fact basename
set_fact:
basename: "{{ '/tmp/foo.txt' | map('basename') }}"
...
The following should be returned.
TASK [print dirname]
ok: [localhost] => {
"msg": "/tmp"
}
TASK [print basename]
ok: [localhost] => {
"msg": "foo.txt"
}
Did you find this article helpful?
If so, consider buying me a coffee over at