Bash ansible:对于远程机器上的文件,是否有类似的东西?

Bash ansible:对于远程机器上的文件,是否有类似的东西?,bash,shell,ansible,ansible-playbook,Bash,Shell,Ansible,Ansible Playbook,我试图把台词变成我可以放在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}/.${rc

我试图把台词变成我可以放在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*
我知道它不一样,但它会选择相同的文件:除了在主机上使用_fileglob查找,我希望它在远程机器上查找


有什么方法可以做到这一点,或者我应该使用shell脚本吗?

文件模块确实可以在服务器上查找ansible在与_fileglob等一起使用时正在运行的文件。因为您想处理仅存在于远程机器上的文件,所以您可以做一些事情。一种方法是在一个任务中复制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 {} ~ \;

您可以将
与_行一起使用
来完成以下操作:

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

BruceP的解决方案是可行的,但是它需要一个附加文件,并且会变得有点混乱。下面是一个纯ansible解决方案

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

- 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

清除与glob匹配的不需要的文件的一种简单可行的方法是:

- 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 }}"

在我的例子中,我运行了它,它仍然从源机器而不是目标机器(库存主机)中拾取模式文件。