Distributing SSH keys with Ansible is easy with the module authorized_key - Adds or removes an SSH authorized key and - as always with Ansible - you can feed this module with data in different ways.

The simple Ansible Playbook shows how this can be done - using the example of a function account in which several SSH keys are stored behind

By the way, I am not claiming that functional accounts with multiple SSH keys are "best practise", but sometimes you just have to solve this issue.

PRE-CONSIDERATIONS / Requirements

My consideration for the Playbook shown here is based on the following requirements:

  1. I want to be able to specify which SSH keys are distributed per target host.
  2. I want only the keys to land on the target host, not information about who the key is assigned to.
  3. I want to be able to see on the Ansible host which person or role the SSH key is assigned to.
  4. The Playbook should also remove SSH keys that I remove on the target host,
    So I want to make sure that only the SSH keys that I specify on the Ansible host are used on the system.

How do we do that?

I have chosen the following ways to achieve my goals:

  1. I put the keys (among other things for clarity) into a folder.
    In this folder I let Ansible search for them as follows:
    1. Search for a file <NamedofTargetHosts>.yaml and use it
    2. If you can't find them, use a default file
  2. The data is stored in a file in which the following informaion is stored in fields:
    1. Name or role assigned to the SSH key.
    2. SSH key

      Only the SSH-Key is read out by the Playbook and therefore only the SSH-Key lands on the target system, but the field with name/role gives me more information.
  3. An option of the module authorized_key - Adds or removes an SSH authorized key named "exclusive" is used to ensure this.

The Playbook

You can find the latest version here on Github.

---

- hosts: testfileservers
  remote_user: devopuser
 
  tasks:

  - name: Read variables
    include_vars: '{{ item }}'
    with_first_found:
      - files:
          - "{{ inventory_hostname }}.yml"
          - "default.yml"
        paths: "./vars/"

  - name: Deploy SSH-Keys to remote host
    authorized_key:
      user: functionaccount
      key: "{{ keystodeploy|map(attribute='sshkey')|join('\n') }}"
      exclusive: true

The Data

The SSH keys are stored in this way:

---

keystodeploy:
  - name: Petra Meier
    sshkey: ssh-rsa AAAABCe233e423...
  - name: Horst Lehmann
    sshkey: ssh-rsa AAAABDdsds...

Clone yourself the repository on here on Github and try it out for yourself.

Translated with www.DeepL.com/Translator