仅当目标不存在时,使用 Ansible 移动远程系统上的文件 [英] Move files on remote system, only if destination doesn't exist, with Ansible
问题描述
我正在尝试编写一个 Ansible 角色来移动远程系统上的许多文件.我找到了一个关于如何执行此操作的 Stack Overflow 帖子,它基本上说只需将命令模块与 'mv' 一起使用".我有一个使用 with_items
语句定义的单个任务,其中 dirs
中的每个项目都是一个带有 src
和 dest的字典代码>键:
I'm trying to write an Ansible role that moves a number of files on the remote system. I found a Stack Overflow post about how to do this, which essentially says "just use the command module with 'mv'". I have a single task defined with a with_items
statement like this where each item in dirs
is a dictionary with src
and dest
keys:
- name: Move directories
command: mv {{ item.src }} {{ item.dest }}
with_items: dirs
这很好,而且有效,但如果目标目录已经存在,我会遇到问题.我不想覆盖它,所以我想先尝试统计每个 dest
目录.我想用统计信息更新 dirs
变量,但据我所知,一旦定义变量,就没有设置或更新变量的好方法.所以我使用 stat
来获取每个目录的信息,然后用 register
保存数据:
This is good and it works, but I run into problems if the destination directory already exists. I don't want to overwrite it, so I thought about trying to stat each dest
directory first. I wanted to update the dirs
variable with the stat info, but as far as I know, there isn't a good way to set or update variables once they're defined. So I used stat
to get the info on each directory and then saved the data with register
:
- name: Check if directories already exist
stat: path={{ item.dest }}
with_items: dirs
register: dirs_stat
有没有办法将注册的统计信息与 mv
命令联系起来?如果它是单个目录,这将很容易.循环是使这变得棘手的原因.有没有办法在不将此循环展开为每个目录的两个任务的情况下执行此操作?
Is there a way to tie the registered stat info to the mv
commands? This would be easy if it were a single directory. The looping is what makes this tricky. Is there a way to do this without unrolling this loop into two tasks per directory?
推荐答案
这无论如何都不是最简单的解决方案,但如果您想使用 Ansible 而不是展开":
This is not the simplest solution by any means, but if you wanted to use Ansible and not "unroll":
---
- hosts: all
vars:
dirs:
- src: /home/ubuntu/src/test/src1
dest: /home/ubuntu/src/test/dest1
- src: /home/ubuntu/src/test/src2
dest: /home/ubuntu/src/test/dest2
tasks:
- stat:
path: "{{item.dest}}"
with_items: dirs
register: dirs_stat
- debug:
msg: "should not copy {{ item.0.src }}"
with_together:
- dirs
- dirs_stat.results
when: item.1.stat.exists
只需调整调试任务以运行适当的command
任务,并将when:
改为when: not ...
.
Simply adapt the debug task to run the appropriate command
task instead and when:
to when: not ...
.
这篇关于仅当目标不存在时,使用 Ansible 移动远程系统上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!