21

我正在尝试将这些行变成可以放入 ansible 剧本的内容:

# 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

到目前为止,我有以下内容:

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

我知道它不一样,但它会选择相同的文件:除了 with_fileglob 在主机上查找,我希望它在远程计算机上查找。

有什么办法可以做到这一点,还是我应该只使用 shell 脚本?

4

4 回答 4

23

清除与 glob 匹配的不需要的文件的一种干净的 Ansible 方法是:

- 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 }}"
于 2016-11-14T23:24:37.937 回答
6

Bruce P 的解决方案有效,但它需要一个附加文件并且有点混乱。下面是一个纯ansible解决方案。

第一个任务获取文件名列表并将其存储在 files_to_copy 中。第二个任务将每个文件名附加到您提供的路径并创建符号链接。

- 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
于 2016-06-02T22:04:23.183 回答
2

当使用 with_fileglob 等时,文件模块确实会在运行 ansible 的服务器上查找文件。由于您想处理仅存在于远程计算机上的文件,因此您可以做几件事。一种方法是在一个任务中复制一个 shell 脚本,然后在下一个任务中调用它。您甚至可以使用文件被复制的事实作为仅在脚本不存在时才运行脚本的方式:

- 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

另一种方法是创建一个完整的命令行来执行您想要的操作并使用 shell 模块调用它:

- name: Generate links
  shell: find ~/.zprezto/runcoms/z* -exec ln -s {} ~ \;
于 2014-06-11T14:17:39.587 回答
-3

您可以使用with_lines来完成此操作:

- name: Link Prezto files
  file: src={{ item }} dest=~ state=link
  with_lines: ls ~/.zprezto/runcoms/z*
于 2015-07-13T23:21:47.213 回答