Pithikos February 2016

Get parent directory in Ansible?

Is there a way to evaluate a relative path in Ansible?

tasks:
  - name: Run docker containers
    include: tasks/dockerup.yml src_code='..'

Essentially I am interested in passing the source code path to my task. It happens that the source code is the parent path of {{ansible_inventory}} but there doesn't seem to be anything to accomplish that out of the box.

---- further info ----

Project structure:

myproj
  app
  deploy
    deploy.yml

So I am trying to access app from deploy.yml.

Answers


udondan February 2016

I just had a look at the source and found a filter I wasn't aware of. Forget previous string operations, it's this simple:

{{ inventory_dir | dirname }}

Other Useful Filters


Previous answer:

This should do it:

{{ inventory_dir.split("/")[0:-1]|join("/") }}

Previous answer:

Does {{ inventory_dir }} do what you want?

Also available, inventory_dir is the pathname of the directory holding Ansible’s inventory host file

Or if you mean by "parent directory" the path of the role your task is in, {{ role_path }} might do the trick.

And finally, role_path will return the current role’s pathname (since 1.8). This will only work inside a role.

From http://docs.ansible.com/ansible/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts


Pithikos February 2016

OK, a workaround is to use a separate task just for this:

tasks:
  - name: Get source code absolute path
    shell: dirname '{{inventory_dir}}'
    register: dirname
  - name: Run docker containers
    include: tasks/dockerup.yml src_code={{dirname.stdout}}

Thanks to udondan for hinting me on inventory_dir.


el_wichtel February 2016

You can use {{playbook_dir}} for the absolute path to your current playbook run. For me thats the best way, because you normally know where your playbook is located.

Post Status

Asked in February 2016
Viewed 3,097 times
Voted 6
Answered 3 times

Search




Leave an answer