Reputation: 910
I would like to use Ansible's synchronize
module to transfer files to a remote server based on a condition. The condition, is that the directory and its contents exist on the source server.
For example:
First play, check if the directory exists on the localhost:
hosts: localhost
stat:
path: some/path/to/dir/
register: st
Then, on the second play, use that variable in a when
statement to conditionally use the synchronize
module:
hosts: remote_hosts
synchronize:
src: some/path/to/dir/
dest: some/dest/path
when: st.stat.isdir is defined
My problem is that the st
variable can't be used between plays, so how can I only run the synchronize
task if the directory exists.
I would put them in the same play, but they're using different hosts as you can see.
My Ansible version is 2.3.1.0
Upvotes: 1
Views: 1790
Reputation: 1589
You have a couple options. You can put the localhost task in your play with remote_users
and use delegate_to: localhost
.
stat:
path: some/path/to/dir/
register: st
delegate_to: localhost
Or you can keep the localhost play as is and reference localhost's variables using hostvars
in the remote_hosts play.
hosts: remote_hosts
synchronize:
src: some/path/to/dir/
dest: some/dest/path
when: hostvars['localhost']['st'].stat.isdir is defined
Upvotes: 3