21

I'm trying to turn these lines into something I can put in an ansible playbook:

# Install Prezto files
shopt -s extglob
shopt -s nullglob
files=( "${ZDOTDIR:-$HOME}"/.zprezto/runcoms/!(README.md) )
for rcfile in "${files[@]}"; do
    [[ -f $rcfile ]] && ln -s "$rcfile" "${ZDOTDIR:-$HOME}/.${rcfile##*/}"
done

So far I've got the following:

- name: Link Prezto files
  file: src={{ item }} dest=~ state=link
  with_fileglob:
    - ~/.zprezto/runcoms/z*

I know it isn't the same, but it would select the same files: except with_fileglob looks on the host machine, and I want it to look on the remote machine.

Is there any way to do this, or should I just use a shell script?

callumacrae
  • 8,185
  • 8
  • 32
  • 49

4 Answers4

25

A clean Ansible way of purging unwanted files matching a glob is:

- name: List all tmp files
  find:
    paths: /tmp/foo
    patterns: "*.tmp"
  register: tmp_glob

- name: Cleanup tmp files
  file:
    path: "{{ item.path }}"
    state: absent
  with_items:
    - "{{ tmp_glob.files }}"
Doru C.
  • 850
  • 9
  • 7
6

Bruce P's solution works, but it requires an addition file and gets a little messy. Below is a pure ansible solution.

The first task grabs a list of filenames and stores it in files_to_copy. The second task appends each filename to the path you provide and creates symlinks.

- name: grab file list
  shell: ls /path/to/src
  register: files_to_copy
- name: create symbolic links
  file:
    src: "/path/to/src/{{ item }}"
    dest: "path/to/dest/{{ item }}"
    state: link
  with_items: files_to_copy.stdout_lines
AdamY
  • 851
  • 2
  • 9
  • 20
2

The file module does indeed look on the server where ansible is running for files when using with_fileglob, etc. Since you want to work with files that exist solely on the remote machine then you could do a couple things. One approach would be to copy over a shell script in one task then invoke it in the next task. You could even use the fact that the file was copied as a way to only run the script if it didn't already exist:

- name: Copy link script
  copy: src=/path/to/foo.sh
        dest=/target/path/to/foo.sh
        mode=0755
  register: copied_script

- name: Invoke link script
  command: /target/path/to/foo.sh
  when: copied_script.changed

Another approach would be to create an entire command line that does what you want and invoke it using the shell module:

- name: Generate links
  shell: find ~/.zprezto/runcoms/z* -exec ln -s {} ~ \;
Bruce P
  • 19,995
  • 8
  • 63
  • 73
-3

You can use with_lines to accomplish this:

- name: Link Prezto files
  file: src={{ item }} dest=~ state=link
  with_lines: ls ~/.zprezto/runcoms/z*
kejadlen
  • 1,519
  • 1
  • 10
  • 10
  • In my case, I ran it and it still picked the pattern files from the SOURCE machine and not from the target (inventory host machine). – AKS Dec 09 '15 at 00:42
  • Oops, I didn't catch that this was for the remote machine. – kejadlen Dec 09 '15 at 19:53