【问题标题】:ansible loop over file list and check file exists, if not download itansible 循环遍历文件列表并检查文件是否存在,如果不下载它
【发布时间】:2019-08-03 18:29:23
【问题描述】:

不确定如何实现此逻辑,我知道如何在单个文件中执行:

- name: Obtain information about a file
  win_stat:
    path: "C:\myfile.txt"
  register: fileinfo

- [...]
  when: fileinfo.exists == False

我应该如何处理文件列表?

【问题讨论】:

  • 都是txt扩展名,在同一个目录下?
  • 我想问题是如何在一个循环中将检查+另一个动作(这里下载)捆绑在一起。

标签: loops ansible yaml


【解决方案1】:

如果您只想减少执行此操作的步骤,您应该能够在下载命令中使用ignore_errors: yes 执行下载步骤(未在您的示例中显示)。如果你使用ignore_errors: yesregister的组合,你甚至可以判断命令是否失败。

如果您想让它更有效率,您可以在单个任务中完成统计,然后检查其结果。当您使用列表执行任务时,您会得到答案的哈希值。

假设您在ssh_key_config 中有一个文件名/路径列表,您可以使用 stat 然后您可以遍历这些项目(其中包含文件名很方便)。

- name: Check to see if file exists
  stat:
    path: "{{ remote_dir }}/{{ item }}"
  register: stat_results
  with_items: "{{ target_files }}"
  ignore_errors: True

- name: perform operation
  fetch:
    src: "{{ remote_dir }}/{{ item.item }}"
    dest: "{{ your_dest_dir }}"
    flat: yes
  with_items: "{{ stat_results.results }}"
  when: item.stat.exists == False

在这种情况下,假设remote_dir 包含主机上的远程目录,target_files 包含实际文件名,your_dest_dir 包含您希望将文件放置在本地的位置。

我对 Windows 和 Ansible 所做的不多,但 win_stat 的文档记录与 stat 几乎相同,因此您可以直接替换它。

另请注意,这需要文件列表,而不是 glob。如果您使用 glob(例如,您想从远程检索具有特定扩展名的所有文件),那么您将不会使用 with_items 子句,您需要使用 item.stat.filename 和/或 @ 987654333@ 远程检索文件(因为item.item 将包含请求项,这将是全局。

【讨论】:

  • 做得很好,谢谢。旁注,这些循环在执行过程中看起来很慢;(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 2021-02-20
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
相关资源
最近更新 更多