bob/roles/system/tasks/main.yaml
Marty Oehme 961e10223c
ref(system): Fix ssh authorized keys task
Fixed the loop for authorized keys. While I read previously that the
Ansible module can take keys in the array format:

```yaml
    key:
      - key1
      - key2
      - ...
```

This seems to not be the case.
Instead, we now do a 'sub-loop' through all the existing authorized_keys
entries in the data structure, running the task once for each key.

This also means we can simplify the 'when' condition to only check the
data structure itself exists, not the key since we only loop once for
each existing key anyway.

More in-depth explanation on the subelements filter here:
https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_filters.html#combining-objects-and-subelements

Concise explanation of use here:
https://overflow.ducks.party/questions/56086290/how-can-i-traverse-nested-lists-in-ansible

One drawback:
we can now _not_ change the key setting in the module to be exclusive
(`exclusive: true` for `authorized_keys` module). As described in the
documentation, if there are more than one key for a user, this would
lead to the following keys overwriting the first key.

Currently do not know how to fix this, but we are not supplying
exclusive keys so it is fine for the moment.
2025-11-28 18:39:33 +01:00

80 lines
1.6 KiB
YAML

---
- name: Ensure aptitude installed
ansible.builtin.apt:
name: "aptitude"
state: present
tags:
- apt
become: true
- name: Ensure OS upgraded
ansible.builtin.apt:
upgrade: dist
tags:
- apt
- update
- os
become: true
- name: Check if reboot is necessary
register: reboot_required_file
ansible.builtin.stat:
path: /var/run/reboot-required
get_checksum: false
tags:
- os
- reboot
notify: Reboot host
- name: All system packages updated
ansible.builtin.apt:
name: "*"
state: latest # noqa package-latest
tags:
- apt
- update
- packages
become: true
- name: Set correct timezone
community.general.timezone:
name: "{{ system_timezone }}"
when: "system_timezone"
tags:
- timezone
become: true
- name: Create necessary groups
ansible.builtin.group:
name: "{{ item }}"
state: present
loop: "{{ system_users | map(attribute='groups') | flatten | unique }}"
when: "system_users"
tags:
- groups
become: true
- name: Set up system users
ansible.builtin.user:
name: "{{ item.name }}"
groups: "{{ item.groups }}"
append: "{{ item.append | default(true) }}"
create_home: "{{ item.create_home | default(false) }}"
shell: "{{ item.shell | default('/bin/bash') }}"
loop: "{{ system_users }}"
when: "system_users"
tags:
- users
- groups
become: true
- name: Add authorized SSH keys
ansible.posix.authorized_key:
user: "{{ item.0.name }}"
state: present
key: "{{ item.1 }}"
loop: "{{ system_users | subelements('authorized_keys', skip_missing=True) }}"
when: system_users is defined
tags:
- ssh
become: true