当列表项不在路径字符串中时为Ansible条件

2024-09-20 22:52:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在文件列表上执行和Ansible任务,但前提是文件路径不包含其他列表中的元素

我在剧本中定义了一个列表变量。这些是我想从任务中排除的文件和目录。我之前在playbook中用ansible.builtin.find收集了files对象,现在我有了一个JSON对象列表。如果exclude中的任何元素位于被迭代项的文件路径中,我想跳过这些对象上的任务。选项是有限的,因为exclude中的一些列表项是文件名,一些是目录名,所以我不能使用filepath模块仅选择文件名

exclude:
  - README.md
  - .git
  - .gitlab
  - .gitignore

但我不知道如何以干净的方式做到这一点。这是正在讨论的任务

- name: Replace some text in files if their path doesn't contain any items from "exclude"
  ansible.builtin.replace:
    path: "{{ item.path }}"
    regexp: "Version1"
    replace: "Version2"
  with_items: files.files
  when: "(exclude|items) not in (item.path | from_json)"

有没有办法让这一切顺利进行?我需要一种完全不同的方法,还是ansible有能力做到这一点


Tags: 文件path对象infrom路径元素列表
1条回答
网友
1楼 · 发布于 2024-09-20 22:52:18

我找到了解决办法。在这里张贴,以防任何人遇到此问题

- name: Replace some text in files if their path does not contain any items from "exclude"
  ansible.builtin.replace:
    path: "{{ item.path }}"
    regexp: "Version1"
    replace: "Version2"
  with_items: "{{ (files).files }}"
  when: "item.path| split('/')| intersect(exclude)| length == 0"

相关问题 更多 >

    热门问题