5

I'm passing a list of dir/subdirs into a playbook as follows:

dirs=['Web\this','Web\that','Web']

This works fine when I actually do tasks on those directories (win_shell, invoking a build process), but later I need to copy the files and the '\' does not work when used as part of a filename. I'm interested in using the following, so I'll get the module name for most builds and 'Web' for the one that is in the root folder:

dirs[1].split('\\')[-1]

I hoped this would return 'this', 'that', and 'Web', respectively.

But I can't find any combination of slashes or regex magic to split my strings. I've found about 5 questions/answers in StackExchange that are close, but none of them seem to do it.

I've also tried this with variations of

"{{ dirs[1] | regex_replace('\\','-') }}"
2
  • Note: I'm passing the list in like it is, with the backslash, because it maps seamlessly to the folder structure the developers have used for a long time, and because calling the build process with Ansible using these variables works quite well. I know I could rework this to eliminate the backslashes and just use the component names, but then that means extra exception handling for the top-level ('Web') folder which otherwise is unnecessary. I feel like I'm just overlooking something obvious on the split() function.
    – Wolske
    Sep 27, 2019 at 21:20
  • Can you show more of your playbook? Using the ` character can be tricky in some contexts, since the ` is a yaml escape character in addition to being a escape character for the regular expressions.
    – Zoredache
    Sep 27, 2019 at 23:00

1 Answer 1

6

Declare a variable with the separator to avoid the quotation&escaping alchemy. Use Single-Quoted Style; backslash '\' can be used freely. For example, the task below

  - debug:
      msg: "{{ dirs[1].split(separator)[-1] }}"
    vars:
      separator: '\'
      dirs: ['Web\this','Web\that','Web']

gives

  msg: that
1
  • 1
    Brilliant! works like a charm. "Alchemy" for sure...
    – Wolske
    Sep 28, 2019 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.