2017-02-28 97 views
0

我想从github下载密钥并创建aws密钥对。目前我正在使用这些任务。Ansible嵌套循环 - 如何遍历循环项目?

- name: download keys from github 
    get_url: 
    url: "https://github.com/{{ item }}.keys" 
    dest: "/tmp/{{ item }}" 
    with_items: 
    - foo 
    - bar 

- name: create ec2 keys 
    ec2_key: name=foo key_material="{{ item }}" state=present 
    with_lines: cat /tmp/foo 

- name: create ec2 keys 
    ec2_key: name=bar 
    with_lines: cat /tmp/bar 

但是,这不是干燥的。如何实现这样的事情?

- name: create ec2 keys 
    ec2_key: name=foo key_material="{{ line }}" state=present 
    with_lines: cat /tmp/{{item}} 
    with_items: 
    - foo 
    - bar 

回答

4

with_nestedwith_together,但你其实并不需要它们。

尝试:

--- 
- hosts: localhost 
    gather_facts: no 
    tasks: 
    - uri: 
     url: https://github.com/{{ item }}.keys 
     return_content: yes 
     with_items: 
     - user1 
     - user2 
     - user3 
     register: github_keys 
    - debug: 
     msg: "user={{ item.item }} first_key={{ item.content.split('\n')[0] }}" 
     with_items: "{{ github_keys.results }}" 

注意,你可以在GitHub上user.keys多个按键,所以ec2_key会在你的情况下,覆盖它们。我只是在我的例子中拉第一个。

更新:如果你想使用索引名

--- 
- hosts: localhost 
    gather_facts: no 
    tasks: 
    - uri: 
     url: https://github.com/{{ item }}.keys 
     return_content: yes 
     with_items: 
     - user1 
     - user2 
     - user3 
     register: github_keys 

    - set_fact: 
     github_name: "{{ item.item }}" 
     github_keys: "{{ lookup('indexed_items',item.content.split('\n')[:-1],wantlist=True) }}" 
     with_items: "{{ github_keys.results }}" 
     register: github_keys_split 

    - debug: 
     msg: "name={{ item[0].github_name }}_{{ item[1][0] }} key={{ item[1][1] }}" 
     with_subelements: 
     - "{{ github_keys_split.results | map(attribute='ansible_facts') | list }}" 
     - github_keys 
+0

你会如何命名它们添加所有的钥匙? –

+0

添加示例与多个键 –

+0

[这里](https://docs.ansible.com/ansible/playbooks_loops.html#looping-over-a-list-with-an-index),结合知识_“循环实际上是+ lookup()的组合,因此任何查找插件都可以用作循环的源代码,'items'正在查找。“_。 –