9

I'm using Ansible 2.3.2.0 and am trying to delete a file and folder inside a directory in one task.

Right now I have this

tasks:

  - name: Removing existing war
    file:
      path: /usr/share/tomcat/webapps/app.war
      state: absent

  - name: Removing existing folder
    file:
      path: /usr/share/tomcat/webapps/app
      state: absent

I cannot simply remove the webapps folder because I do not want to delete other files and folders in there. I want to reduce the number of tasks because I am using Duo push auth and this adds to the deploy time. I've tried looping over files and file globs but for some reason it never works.

http://docs.ansible.com/ansible/latest/playbooks_loops.html#looping-over-files

HarlemSquirrel
  • 8,966
  • 5
  • 34
  • 34

2 Answers2

14

Simply iterate over the two values:

tasks:
  - name: Removing
    file:
      path: "{{ item }}"
      state: absent
    with_items:
      - /usr/share/tomcat/webapps/app.war
      - /usr/share/tomcat/webapps/app

But it will still create 2 tasks executions: one for each item.

zigarn
  • 10,892
  • 2
  • 31
  • 45
5

If you simply want to delete a directory and its contents, just use the file module and pass the path to the directory only:

tasks:
 - name: Removing
   file:
     path: /usr/share/tomcat/webapps/app
     state: absent

See this post: Ansible: How to delete files and folders inside a directory?

and from the ansible docs:

If absent, directories will be recursively deleted, and files or symlinks will be unlinked.

see: http://docs.ansible.com/ansible/latest/file_module.html

spencerwjensen
  • 672
  • 4
  • 8
  • 1
    The issue is that I DO NOT want to delete all files in the directory. I want to delete just one file and one directory in there. – HarlemSquirrel Aug 25 '17 at 18:13
  • 1
    oh I see.. app.war and app are both at the same level in webapps.. I should have looked at that closer. sorry. then @zigarn's answer is correct. use with_items to loop over the paths you want to remove. – spencerwjensen Aug 25 '17 at 18:37