仅在目标不存在的情况下,使用Ansible在远程系统上移动文件 [英] Move files on remote system, only if destination doesn't exist, with Ansible

查看:486
本文介绍了仅在目标不存在的情况下,使用Ansible在远程系统上移动文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个Ansible角色,该角色在远程系统上移动许多文件.我找到了 Stack Overflow帖子关于如何执行此操作,该帖子本质上说仅将命令模块与'mv'一起使用" .我用这样的with_items语句定义了一个任务,其中dirs中的每个项目都是带有srcdest键的字典:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆