0

I have a directory that will have a series of subdirectories added to it, and I want to maintain only the most recent 5. Here are the two tasks that I think should accomplish this:

- name: Get directory listing
  shell: ls -tr1 chdir={{ project_root}}/sources
  register: sources_list

- name: Pare directories
  shell: rm -rf {{ sources_list.stdout_lines[0] }}; ls -tr1 chdir={{ project_root}}/sources
  register: sources_list
  until: sources_list.stdout_lines|length <= 5
  retries: 10

My thinking is that the first task will produce an ordered list of directory names and register it to sources_list. The second task will then get the name of the oldest directory (the first line in sources_list, rm -rf it, then output the list of the rest of the directories. It will do this until there are 5 directories or less in the list.

Instead I get this error message:

error while evaluating conditional: sources_list.stdout_lines|length <= 5

I have already confirmed that sources_list.stdout_lines|length does evaluate to the number of files in the directory, and that sources_list is correctly updated after the first iteration of the loop. But for some reason that conditional doesn't work. Any guidance would be appreciated.

Zach Smith
  • 1
  • 1
  • 1
  • Are you trying to replicate Capistrano-style timestamped deployment folders? – Mxx Feb 13 '15 at 05:06
  • This is quite complicated and unusual, and I don't think `ansible` is meant to work that way. Why don't you use some shell commands instead? `ls -t1 | tail -n +6 | xargs rm -rf` (untested). It's probably fine as it is, though if the directory names have spaces it may need some tricky elaboration. – Antonis Christofides Feb 13 '15 at 08:32
  • Thanks. I ended up using a different shell command: `(ls -t|head -n 5;ls)|sort|uniq -u|xargs rm -rf` – Zach Smith Apr 23 '15 at 20:39

1 Answers1

1

I ran into this same issue today. I was able to work around it by splitting stdout manually like this:

until: sources_list.stdout.split()|length <= 5

I think this is a bug, since stdout_lines and stdout.split() are supposed to give the same result. I've filed a bug report here: https://github.com/ansible/ansible/issues/10334