Bootstrap FreeKB - Ansible - Get file or directory name using the basename filter
Ansible - Get file or directory name using the basename filter

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 2aeaa5 in the box below so that we can be sure you are a human.