如何使用fileglob模式进行嵌套循环?


13

我正在尝试为Ansible中的一组用户创建一组授权的SSH密钥。我有一个users像这样设置的变量:

users:
  - { username: root, name: 'root' }
  - { username: user, name: 'User' }

在同一角色中,我在files/public_keys目录中还有一组授权密钥文件,每个授权密钥一个文件:

roles/common/files/public_keys/home
roles/common/files/public_keys/work

我想将每个公钥复制到每个用户。

我尝试使用以下任务:

- name: copy authorized keys
  authorized_key: user={{ item.0.username }} key={{ item.1 }}
  with_nested:
    - users
    - lookup('fileglob', 'public_keys/*')

但是,item.1包含文字字符串"lookup('fileglob', 'public_keys/*')",而不是下的每个文件路径files/public_keys

有没有一种方法可以获取files/public_keys目录列表并将每个公钥复制到每个用户?

Answers:


8

技巧是通过split函数将fileglob返回值转换为列表,以便您可以迭代这些值:

- name: copy authorized keys
  authorized_key: 
    user: "{{ item.0.username }}"
    key: "{{ lookup('file', item.1) }}"
  with_nested:
    - "{{ users }}"
    - "{{ lookup('fileglob', 'public_keys/*').split(',') }}"

请注意,在Ansible v2中已弃用不带{{和的}}for 裸变量with_items


这应该被接受的答案
Beyers

0

您可能需要大量重写命令,但是有循环遍历fileglob的规定

从示例:

- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
  with_fileglob:
    - /playbooks/files/fooapp/*

其他有希望的选择是Looping over Subelements,实际上由SSH密钥说明


3
我知道您可以使用with_fileglob; 遍历文件glob 我只是不确定如何将其与嵌套循环结合使用。遍历子元素可以工作,但是我希望我不必手动指定要复制的键的整个列表,因为我应该能够将其作为列表(使用with_fileglob)获得。
mipadi 2014年

我也不确定。下一个最好的建议是流行到#ansibleirc.freenode.net,看看大师那里有什么好主意。
Tom O'Connor 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.