This is a playbook that I use to manage SSH keys on my virtual machines. The playbook assumes that it is able to SSH in to the VM using a key. In the future, I would like to incorporate a way to log in to a VM if it is unable to log in via SSH key and insert the needed key.

---
- name: Add public keys to authorized_keys
  hosts: all
  gather_facts: false
 
  tasks:
    - name: "Ensure the ~/.ssh directory exists"
      ansible.builtin.file:
        path: ~/.ssh
        state: directory
        mode: '0700'
 
    - name: "Add public keys to authorized_keys file"
      ansible.posix.authorized_key:
        user: root
        key: "{{ item }}"
        state: present
      with_items:
        - "[cipher1] [key1] [comment1]"
        - "[cipher2] [key2] [comment2]"
        - "[cipher3] [key3] [comment3]"
 
    - name: "Remove public keys from authorized_keys file"
      ansible.posix.authorized_key:
        user: root
        key: "{{ item }}"
        state: absent
      with_items:
        - "[cipher4] [key4] [comment4]"
        - "[cipher5] [key5] [comment5]"