Ansible combine lists from variables

83 views Asked by At

I have the following list of keys and users:

---
case1:
  keys:
    - sshrsa1
    - sshrsa2
  users:
    - user1
    - user2
    - user4
case2:
  keys:
    - sshrsa3
    - sshrsa4
    - sshrsa5
  users:
    - user1
    - user2
    - user5

How can I combine these list to use with authorized_key in order to place all keys under case1 in all the users' authorized_file like the below example?

user1's auth file contains:
sshrsa1
sshrsa2
user2's auth file contains:
sshrsa1
sshrsa2
user4's auth file contains:
sshrsa1
sshrsa2

And the same with case2:

user1's auth file contains:
sshrsa3
sshrsa4
sshrsa5
user2's auth file contains:
sshrsa3
sshrsa4
sshrsa5
user5's auth file contains:
sshrsa3
sshrsa4
sshrsa5
1

There are 1 answers

0
Vladimir Botka On

Given the data

auth_keys:
  case1:
    keys: [sshrsa1, sshrsa2]
    users: [user1, user2, user4]
  case2:
    keys: [sshrsa3, sshrsa4, sshrsa5]
    users: [user1, user2, user5]

Q: "Place all keys under case* into the users' authorized_key files."

A: Convert the dictionary to a list and iterate with_subelements. For example,

    - debug:
        msg: "user: {{ item.1 }}, key: {{ item.0.value['keys'] }}"
      with_subelements:
        - "{{ auth_keys|dict2items }}"
        - value.users

gives (abridged)

  msg: 'user: user1, key: [''sshrsa1'', ''sshrsa2'']'
  msg: 'user: user2, key: [''sshrsa1'', ''sshrsa2'']'
  msg: 'user: user4, key: [''sshrsa1'', ''sshrsa2'']'
  msg: 'user: user1, key: [''sshrsa3'', ''sshrsa4'', ''sshrsa5'']'
  msg: 'user: user2, key: [''sshrsa3'', ''sshrsa4'', ''sshrsa5'']'
  msg: 'user: user5, key: [''sshrsa3'', ''sshrsa4'', ''sshrsa5'']'

Notes

The parameter key requires a string. Convert the keys from the list to lines in a string. For example,

    - ansible.posix.authorized_key:
        user: "{{ item.1 }}"
        key: "{{ _key }}"
      with_subelements:
        - "{{ auth_keys|dict2items }}"
        - value.users
      vars:
        _key: |
          {% for key in item.0.value['keys'] %}
          {{ key }}
          {% endfor %}