sorin
sorin

Reputation: 170568

How do I assure that a path variable ends with slash in Ansible?

I want to assure that a variable representing a folder set by the user has an ending slash, so I can avoid bugs related to missing slash or double slash.

Mainly I am considering a repair task like:

- when: my_path[-1] != '/'
  set_fact:
      my_path: "{{ mypath }}/"

If this condition can be written in pure jinja2 even better as I could avoid creating an extra set_fact and put that trick inside a "vars" block.

Any better way to implement that? Apparently there is no in-build jinja2 filter to format paths.

Upvotes: 3

Views: 1280

Answers (1)

dgw
dgw

Reputation: 13656

You can write your own filter.

In ansible.cfg you can specify your filter directory:

[defaults]
filter_plugins=<path/to/your/library/of/filters>

And now you put in <path/to/your/library/of/filters>/path_filter.py:

from ansible.module_utils import basic

def canonical_path(path):
    ''' Verify that path ends with / and add / if not '''
    if path[-1] != '/':
        return path + '/'
    return path

class FilterModule(object):
    ''' Ansible Filter to provide canonical_path '''
    def filters(self):
        return {'canonical_path': canonical_path}

That allows you to write in your playbooks

- name: Show canonical_path
  debug:
     msg: "Path is : {{ mypath | canonical_path }}" 

Upvotes: 4

Related Questions