Getting the Absolute Path of a Remote Directory in Ansible
(stable doodle) server room, neon, cables

Getting the Absolute Path of a Remote Directory in Ansible

ansible bash dev linux

by
published on

I recently had to find a way to delete a folder using Ansible that was being created by Docker. The folder had a path like ~/docker/myservice. Since docker had created it as part of a volume, the folder did not belong to the current user. So deleting the folder using normal permissions failed.

Deleting with elevated permission on the command line is easy: The command sudo rm -rf ~/docker/myservice performs the rm operation as the root user. In bash, this will delete the docker/myservice folder in the user's home directory, but when doing the equivalent in Ansible, this won't work!

# This does not work!
- name: Delete the folder using root permissions
  become: true
  ansible.builtin.file:
    path: "~/docker/myservice"
    state: "absent"

This code will try to delete the file /user/root/docker/myservice, which is not what we wanted.

The bash version works because the shell first resolves the tilde in the argument to the current users' directory before calling the sudo command. In Ansible, we first switch to the root user and only then the tilde is resolved: this time to the home directory of the root user.

To circumvent this, we can manually resolve the path to an absolute path. Unfortunately, I have not found a straightforward way to do this in Ansible, however the bash command readlink -f <path> does exactly this. To use it in Ansible, we can use the following configuration:

- name: Get absolute folder path
  ansible.builtin.command:
    cmd: "readlink -f ~/docker/myservice"
  register: folder_abs
  changed_when: False

- name: Debug
  debug:
    msg: "{{folder_abs.stdout}}" # prints /user/tim/docker/myservice

- name: Delete the folder using root permissions
  become: true
  ansible.builtin.file:
    path: "{{folder_abs.stdout}}"
    state: "absent"

With this Ansible script, we manually resolve the absolute path and use it to delete the folder using root permissions. If you know of an easier way to resolve to an absolute path, please let me know!

You found an error in this post? Open a pull request.
Photo of Tim Bachmann

Hi, my name is Tim Bachmann! I'm a master graduate in computer science at University of Basel, swimmer and swim coach.

I am passionate about all things web development, swimming, personal knowledge management and much more. If you liked this or any of my posts, feel free to follow me.

0 Comments and Interactions

Leave a comment or interact with this page via WebMention

Built with SvelteKit and hosted on GitHub Pages.

View this website on GitHub!

Other pages