Ansible 如何使“with_fileglob”有条件

Ansible 如何使“with_fileglob”有条件,ansible,Ansible,我正在测试这个: #test.yml - hosts: localhost tasks: - set_fact: host_name: "project-specific" - stat: path: /home/user/work/infrastructure/{{ host_name }} register: file_exists - debug: var: file_exists - name: Dont creat

我正在测试这个:

#test.yml

- hosts: localhost
  tasks:
  - set_fact:
      host_name: "project-specific"

  - stat:
      path: /home/user/work/infrastructure/{{ host_name }}
    register: file_exists

  - debug:
      var: file_exists

  - name: Dont create a file
    template:
      src: "{{item}}"
      dest: /home/user/work/infrastructure/project-specific-2/
      mode: 0755
    with_fileglob: /home/user/work/infrastructure/{{ host_name }}/*
    when: file_exists
我想将project-specific-2中的所有文件复制到project-specific-2中作为演示,但仅当project-specific目录实际存在时。项目特定目录不存在,因此应跳过此步骤

这是输出:

user@laptop:~/work/infrastructure/ansible$ ansible-playbook test.yml
PLAY [localhost] *************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************
ok: [localhost]

TASK [set_fact] **************************************************************************************************************************************
ok: [localhost]

TASK [stat] ******************************************************************************************************************************************
ok: [localhost]

TASK [debug] *****************************************************************************************************************************************
ok: [localhost] => {
    "file_exists": {
        "changed": false, 
        "failed": false, 
        "stat": {
            "exists": false
        }
    }
}

TASK [Dont create a file] ****************************************************************************************************************************
[WARNING]: Unable to find '/home/user/work/infrastructure/project-specific' in expected paths (use -vvvvv to see paths)

PLAY RECAP *******************************************************************************************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

表示with_u子句在when之前执行。如果路径不存在,如何使其跳过此步骤?或者让它在“执行”时加上一个警告,这样就不会复制任何文件了,这样可以吗?

我想你已经被这个问题困扰了。如when语句中所述,对循环中的每个项分别求值

将条件与循环组合时,将分别为每个项处理When:语句

所以你看到的是预期的行为


在您的案例中,最终的结果是当找不到目录时,任务实际上被跳过,而不执行任何操作。它只是在打印警告时执行此操作

我想你被这件事难住了。如when语句中所述,对循环中的每个项分别求值

将条件与循环组合时,将分别为每个项处理When:语句

所以你看到的是预期的行为

在您的案例中,最终的结果是当找不到目录时,任务实际上被跳过,而不执行任何操作。它只是在打印警告时执行此操作