> For the complete documentation index, see [llms.txt](https://huataihuang.gitbook.io/cloud-atlas-draft/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://huataihuang.gitbook.io/cloud-atlas-draft/devops/ansible/tips/ansible_copy_multi_files.md).

# Ansible批量复制文件

## Loops

当需要在一个任务里面做很多事情的时候，例如创建一批用户，安装一批软件包，或者重复执行步骤直到满足某个结果，此时可以使用Ansible loops来实现。

> 详细请参考编译手册 [Ansible Playbooks: Loops](https://github.com/huataihuang/cloud-atlas-draft/tree/6f3204fffc11cf006abd394631e2598d98b415c3/devops/ansible/playbooks/loops/README.md)

## 使用`with_fileglob` loop

`with_fileglob`会匹配单个目录下所有文件，非递归方式，所以可以使用通配符。它调用了 [Python's glob library](https://docs.python.org/2/library/glob.html) 使用方法类似如下

```
---
- hosts: all

  tasks:

    # first ensure our target directory exists
    - file: dest=/etc/fooapp state=directory

    # copy each file over that matches the given pattern
    - copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
      with_fileglob:
        - /playbooks/files/fooapp/*
```

> 这里`with_fileglob:`要使用绝对路径

## 参考

* [Copy multiple files with Ansible](https://github.com/huataihuang/cloud-atlas-draft/tree/6f3204fffc11cf006abd394631e2598d98b415c3/devops/ansible/tips/Copy%20multiple%20files%20with%20Ansible/README.md)
* [Ansible Documentation: Loops](http://docs.ansible.com/ansible/playbooks_loops.html)
