2

I am trying to download keys from github and create aws key pairs. Currently I am using these tasks for that.

- 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

However, this is not DRY. How to achieve something like this?

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

1 Answer 1

7

There's with_nested and with_together, but you actually don't need them.

Try:

---
- 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 }}"

Note that you may have multiple keys in github user.keys, so ec2_key will overwrite them in your case. I just pull first one in my example.

Update: if you want to add all keys with indexed names

---
- 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
Sign up to request clarification or add additional context in comments.

3 Comments

How would you name them?
added example with multiple keys
here, in combination with knowledge of "Loops are actually a combination of things with + lookup(), so any lookup plugin can be used as a source for a loop, ‘items’ is lookup.".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.