1

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.

1 Answer 1

1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .