如果目录存在,Ansible 有条件地同步

Ansible Conditionally Synchronize if Directory Exists

我想使用 Ansible 的 synchronize 模块根据条件将文件传输到远程服务器。条件是 目录 及其内容存在于源服务器上。

例如:

首先播放,检查本地主机上是否存在该目录:

hosts: localhost
stat:
  path: some/path/to/dir/
register: st

然后,在第二次播放时,在 when 语句中使用该变量以有条件地使用 synchronize 模块:

hosts: remote_hosts
synchronize:
  src: some/path/to/dir/
  dest: some/dest/path
when: st.stat.isdir is defined

我的问题是 st 变量不能在播放之间使用,所以如果目录存在,我怎么能只 运行 synchronize 任务。

我会把它们放在同一个游戏中,但正如您所见,它们使用不同的主机。

我的 Ansible 版本是 2.3.1.0

你有几个选择。您可以使用 remote_users 将 localhost 任务放入游戏​​中并使用 delegate_to: localhost.

stat:
  path: some/path/to/dir/
register: st
delegate_to: localhost

或者您可以保持本地主机播放原样,并在 remote_hosts 播放中使用 hostvars 引用本地主机的变量。

hosts: remote_hosts
synchronize:
  src: some/path/to/dir/
  dest: some/dest/path
when: hostvars['localhost']['st'].stat.isdir is defined