我正在尝试从github下载密钥并创建aws密钥对。目前我正在使用这些任务。
- 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
然而,这不是DRY。如何实现这样的目标?
- name: create ec2 keys
ec2_key: name=foo key_material="{{ line }}" state=present
with_lines: cat /tmp/{{item}}
with_items:
- foo
- bar
答案 0 :(得分:4)
有with_nested
和with_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