带有条件语句的 Ansible 循环

标签 ansible

是否可以在 Ansible 中使用条件语句进行循环?我想要的是查找特定文件的路径是否存在。如果存在,就执行一个循环,并且只针对那个特定的文件看条件语句。下面的代码示例

  - name: File exist
    stat:
      path: <path to the file or directory you want to check>
    register: register_name

- name: Copy file
  copy:
    src: '{{ item }}'
    dest: '<destination path>'
  with_fileglob:
    - ../spring.jar
    - <perform if statement. if register_name.stat.exists, ../info.txt, else dont copy this info.txt >


# ... few other task with loop instead of with_fileglob

最佳答案

您可以,而且您提供的伪代码接近可行的解决方案。

有一个inline if expression可以让你对列表中的项目采取行动。
从那里开始,如果您期望的文件不存在,您可以创建一个空字符串 — 因为很遗憾,您不能 omit列表的一个元素

因为带有空元素的 copy 会导致失败,您现在有两个选择,要么过滤列表以删除空元素,要么使用 when 设置条件跳过它们。

这是过滤空元素的解决方案,使用 select过滤器:

- copy:
    src: "{{ item }}"
    dest: /tmp
  loop: "{{ _loop | select }}"
  vars:
    _loop:
      - ../spring.jar
      - "{{ '../info.txt' if register_name.stat.exists else '' }}"

这里是使用条件的解决方案:

- copy:
    src: "{{ item }}"
    dest: /tmp
  loop:
    - ../spring.jar
    - "{{ '../info.txt' if register_name.stat.exists else '' }}"
  when: "item != ''"

关于带有条件语句的 Ansible 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71629533/

相关文章:

ansible - 使用 ansible playbook 进行 Logrotate

python - 我如何确认 python 包是使用 ansible 安装的

Ansible:更改=0

Ansible playbook 具有串行 > 1 和 run_once

python - 消息 : ConnectionError(ProtocolError ('Connection aborted.' , 错误 (2, 'No such file or directory' )),)

docker - 带有远程Docker守护程序的Packer Docker Builder

ansible - 未设置远程 tmp 目录用于 ansible 脚本执行

mysql - 无法连接到通过ansible启动的MySQL docker容器

Ansible with_dict 模板使用

variables - 如何获取运行 ansible 的用户名的变量?