--- - name: Check and Add Authorized Key hosts: "{{ host }}" gather_facts: yes tasks: - name: Read authorized_keys file shell: cat ~/.ssh/authorized_keys | grep "{{ key_to_add }}" register: authorized_key_output ignore_errors: yes - name: Check if authorized key exists set_fact: authorized_key_exists: "{{ authorized_key_output.stdout | length > 0 }}" when: authorized_key_output.rc == 0 - name: Display result debug: msg: "Authorized key exists: {{ authorized_key_exists | default(false) }}" - name: Add authorized key if it does not exist block: - name: Add authorized key authorized_key: user: root # Replace with the remote user's name state: present key: "{{ key_to_add }}" rescue: - name: Handle error when key already exists debug: msg: "The authorized key already exists. Skipping addition." when: not authorized_key_exists | default(false)