Ansible 行动手册 - 同步模块 - 寄存变量和with_items



我正在尝试编写一个剧本,以便在数据库刷新后将文件夹从源同步到目标。我们的Peoplesoft HR应用程序还需要文件系统刷新以及数据库。我是 ansible 的新手,不是 python 专家。我已经写了这篇文章,但如果任何with_items不存在,我的剧本就会失败。我想将此剧本用于所有应用,并且文件夹可能因应用而异。如何跳过源代码中不存在的文件夹。我正在命令行传递{{ target }}

---
- hosts: '<hostname>'
remote_user: <user>
tasks:
- shell: ls -l /opt/custhome/prod/
register: folders
- name:  "Copy PROD filesystem to target"
synchronize:
src: "/opt/custhome/prod/{{ item }}"
dest: "/opt/custhome/dev/"
delete: yes
when: "{{ folders == item }}"
with_items:
- 'src/cbl/'
- 'sqr/'
- 'bin/'
- 'NVISION/'

在这种情况下,NVISION 在 HR 应用中不存在,但在 FIN 应用中存在。但是剧本失败了,因为该文件夹在源代码中不存在。

可以使用 find 模块查找和存储源文件夹的路径,然后循环访问结果。示例剧本:

- hosts: '<hostname>'
remote_user: <user>
tasks:
- name: find all directories
find:
file_type: directory
paths: /opt/custhome/prod/
patterns:
- "src"
- "sqr"
- "bin"
register: folders
#debug to understand contents of {{ folders }} variable
# - debug: msg="{{ folders }}"
- name:  "Copy PROD filesystem to target"
synchronize:
src: "{{ item.path }}"
dest: "/opt/custhome/dev/"
delete: yes
with_items: "{{ folders.files }}"

您可能希望使用recurse下降到子目录,use_regex使用 python 正则表达式的强大功能而不是 shell 通配

最新更新