Score:1

Validate all public keys in authorized_file

hk flag

In my authorized_file i have multiple public keys against one private key. Now i want to add a task in ansible which will validate that all public keys are valid keys and good for connection. My aim is to remove bad/faulty key from authorized_file.

Score:1
by flag

You could do an Ansible playbook for that, it will validate all public keys in the authorized_file and remove the invalid ones, like for example:

---
- name: Validate SSH public keys in authorized_file
  hosts: all
  gather_facts: no
  tasks:
    - name: Fetch the authorized_keys file
      slurp:
        src: ~/.ssh/authorized_keys
      register: authorized_keys_slurp

    - name: Extract the authorized_keys content
      set_fact:
        authorized_keys_content: "{{ authorized_keys_slurp['content'] | b64decode | regex_replace('\r\n', '\n') }}"

    - name: Validate each key and filter out invalid ones
      shell: echo "{{ item }}" | ssh-keygen -l -f /dev/stdin
      register: key_validation
      loop: "{{ authorized_keys_content.splitlines() }}"
      ignore_errors: true

    - name: Collect valid keys
      set_fact:
        valid_keys: "{{ valid_keys | default([]) + [item.item] }}"
      loop: "{{ key_validation.results }}"
      when: item.rc == 0

    - name: Update authorized_keys with valid keys only
      copy:
        content: "{{ valid_keys | join('\n') }}"
        dest: ~/.ssh/authorized_keys
        mode: 0600

To make this work save it as a .yml file then you can execute it with ansible-playbook replace inventory.ini with your inventory file ansible-playbook -i inventory.ini validate_authorized_keys.yml

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.