Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

ansible - remove all files containing a certain name within a directory

I have the following directory and it has the following files:

/tmp/test/file1.txt
/tmp/test/file1.txt.backup
/tmp/test/mywords.csv

How do I use the file module to just remove file1* files?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

edit: Ansible 2.0 has been released now, so the previous answer should work, and you can also now loop over fileglobs. Note this only works if you are running Ansible locally:

- file:
    path: "{{item}}"
    state: absent
  with_fileglob:
    - /tmp/test/file*

original answer:

I can't find a way to do this currently without dropping to the shell, however if you can drop to the shell to gather a list of files that match the pattern and save that as a variable, then you can loop over the file module with with_items

Ansible 2.0 will include a "find" module that would get the list for you: http://docs.ansible.com/ansible/find_module.html

Here's a couple of tasks that should do it in ansible 2.0, but I don't have it installed so I haven't tested it and may be accessing the results of the find module incorrectly.

- find:
    paths: "/tmp/test"
    patterns: "file*"
  register: result

- file:
    path: "{{item.path}}" #correction code
    state: absent
  with_items: result.files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...