如何使“with_fileglob”成为有条件的

A G*_*A G 1 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 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
Run Code Online (Sandbox Code Playgroud)

我想将所有文件复制到project-specificproject-specific-2作为演示),但前提是项目特定的目录确实存在。项目特定目录不存在,因此应该跳过此步骤。

这是输出:

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   
Run Code Online (Sandbox Code Playgroud)

https://github.com/ansible/ansible/issues/13296

声明with_子句在 之前执行when。如果路径不存在,如何使其跳过此步骤?或者可以让它“执行”并发出警告,因为无论如何都没有文件被复制?

Set*_*nta 5

我认为你被这个问题困住了。如文档中所述,该when语句针对循环中的每个项目单独评估。

将条件与循环组合时,将针对每个项目单独处理 when: 语句。

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

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