遍历列表并复制文件(如果该文件仅存在于本地)

Loop over a list and copy a file if that file exists locally only

我的剧本使用了 2 个外部文件:

  - name: jimi
    status: present
    sudo: "yes"
-rw-rw-rw- 1 root root   0 Jul 19 10:45 jimi.pub

我的剧本将创建用户并复制密钥,但如果用户在 files/username.pub 中没有密钥文件,它将出错。我的最终目标是复制密钥 只有 如果密钥文件存在,如果不存在,则继续到列表中的下一个用户。

我可以在本地统计文件,但由于它会遍历用户列表,它最终会找到一个没有密钥的用户并出错。

密钥文件副本如下所示:

  - name: Setting the authorized key for users
    authorized_key:
      user: "{{ item.name }}"
      key: "{{ lookup('file', 'files/'+ item.name + '.pub') }}"
      state: "{{ item.status }}"
    loop: "{{ users }}"  

如果密钥文件存在,我如何才能复制密钥 ,如果不存在,则继续到列表中的下一个用户,而不会出现剧本错误!?

可以轻松测试本地文件。参见 Testing paths。例如,给定用户

    users: [alice, bob, jimi]

和文件

shell> ls -1 files/
bob.pub
jimi.pub

任务

    - debug:
        msg: "Setting the authorized key for {{ item }}"
      loop: "{{ users }}"
      vars:
        _file: "files/{{ item }}.pub"
      when: _file is exists

给予

TASK [debug] **************************************************************
skipping: [localhost] => (item=alice) 
ok: [localhost] => (item=bob) => 
  msg: Setting the authorized key for bob
ok: [localhost] => (item=jimi) => 
  msg: Setting the authorized key for jimi

这些 tests 始终提供有关控制器路径的信息,例如它们独立于主机任务 运行 at.